repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
cstb/ifc2x3-SDK | src/ifc2x3/IfcChillerType.cpp | 2 | 3660 | // IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// 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.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include <ifc2x3/IfcChillerType.h>
#include <ifc2x3/CopyOp.h>
#include <ifc2x3/IfcEnergyConversionDeviceType.h>
#include <ifc2x3/Visitor.h>
#include <Step/BaseObject.h>
#include <Step/ClassType.h>
#include <string>
#include "precompiled.h"
using namespace ifc2x3;
IfcChillerType::IfcChillerType(Step::Id id, Step::SPFData *args) : IfcEnergyConversionDeviceType(id, args) {
m_predefinedType = IfcChillerTypeEnum_UNSET;
}
IfcChillerType::~IfcChillerType() {
}
bool IfcChillerType::acceptVisitor(Step::BaseVisitor *visitor) {
return static_cast< Visitor * > (visitor)->visitIfcChillerType(this);
}
const std::string &IfcChillerType::type() const {
return IfcChillerType::s_type.getName();
}
const Step::ClassType &IfcChillerType::getClassType() {
return IfcChillerType::s_type;
}
const Step::ClassType &IfcChillerType::getType() const {
return IfcChillerType::s_type;
}
bool IfcChillerType::isOfType(const Step::ClassType &t) const {
return IfcChillerType::s_type == t ? true : IfcEnergyConversionDeviceType::isOfType(t);
}
IfcChillerTypeEnum IfcChillerType::getPredefinedType() {
if (Step::BaseObject::inited()) {
return m_predefinedType;
}
else {
return IfcChillerTypeEnum_UNSET;
}
}
const IfcChillerTypeEnum IfcChillerType::getPredefinedType() const {
IfcChillerType * deConstObject = const_cast< IfcChillerType * > (this);
return deConstObject->getPredefinedType();
}
void IfcChillerType::setPredefinedType(IfcChillerTypeEnum value) {
m_predefinedType = value;
}
void IfcChillerType::unsetPredefinedType() {
m_predefinedType = IfcChillerTypeEnum_UNSET;
}
bool IfcChillerType::testPredefinedType() const {
return getPredefinedType() != IfcChillerTypeEnum_UNSET;
}
bool IfcChillerType::init() {
bool status = IfcEnergyConversionDeviceType::init();
std::string arg;
if (!status) {
return false;
}
arg = m_args->getNext();
if (arg == "$" || arg == "*") {
m_predefinedType = IfcChillerTypeEnum_UNSET;
}
else {
if (arg == ".AIRCOOLED.") {
m_predefinedType = IfcChillerTypeEnum_AIRCOOLED;
}
else if (arg == ".WATERCOOLED.") {
m_predefinedType = IfcChillerTypeEnum_WATERCOOLED;
}
else if (arg == ".HEATRECOVERY.") {
m_predefinedType = IfcChillerTypeEnum_HEATRECOVERY;
}
else if (arg == ".USERDEFINED.") {
m_predefinedType = IfcChillerTypeEnum_USERDEFINED;
}
else if (arg == ".NOTDEFINED.") {
m_predefinedType = IfcChillerTypeEnum_NOTDEFINED;
}
}
return true;
}
void IfcChillerType::copy(const IfcChillerType &obj, const CopyOp ©op) {
IfcEnergyConversionDeviceType::copy(obj, copyop);
setPredefinedType(obj.m_predefinedType);
return;
}
IFC2X3_EXPORT Step::ClassType IfcChillerType::s_type("IfcChillerType");
| lgpl-2.1 |
lxde/lxqt-config | lxqt-config-brightness/xrandrbrightness.cpp | 2 | 14376 | /* This file is part of the KDE project
* Copyright (C) 2010 Lukas Tinkl <ltinkl@redhat.com>
* Copyright (C) 2015 Kai Uwe Broulik <kde@privat.broulik.de>
*
* 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 <QX11Info>
#include <QDebug>
#include "xrandrbrightness.h"
XRandrBrightness::XRandrBrightness()
{
if (!QX11Info::isPlatformX11()) {
return;
}
ScopedCPointer<xcb_randr_query_version_reply_t> versionReply(xcb_randr_query_version_reply(QX11Info::connection(),
xcb_randr_query_version(QX11Info::connection(), 1, 2),
nullptr));
if (!versionReply) {
qDebug() << "RandR Query version returned null";
return;
}
if (versionReply->major_version < 1 || (versionReply->major_version == 1 && versionReply->minor_version < 2)) {
qDebug() << "RandR version" << versionReply->major_version << "." << versionReply->minor_version << " too old";
return;
}
ScopedCPointer<xcb_intern_atom_reply_t> backlightReply(xcb_intern_atom_reply(QX11Info::connection(),
xcb_intern_atom (QX11Info::connection(), 1, strlen("Backlight"), "Backlight"),
nullptr));
if (!backlightReply) {
qDebug() << "Intern Atom for Backlight returned null";
return;
}
m_backlight = backlightReply->atom;
if (m_backlight == XCB_NONE) {
qDebug() << "No outputs have backlight property";
//return;
}
xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(QX11Info::connection()));
if (!iter.rem) {
qDebug() << "XCB Screen Roots Iterator rem was null";
return;
}
xcb_screen_t *screen = iter.data;
xcb_window_t root = screen->root;
m_resources.reset(xcb_randr_get_screen_resources_current_reply(QX11Info::connection(),
xcb_randr_get_screen_resources_current(QX11Info::connection(), root)
, nullptr));
if (!m_resources) {
qDebug() << "RANDR Get Screen Resources returned null";
return;
}
}
bool XRandrBrightness::backlight_get_with_range(xcb_randr_output_t output, long &value, long &min, long &max) const {
long cur = backlight_get(output);
if (cur == -1) {
return false;
}
ScopedCPointer<xcb_randr_query_output_property_reply_t> propertyReply(xcb_randr_query_output_property_reply(QX11Info::connection(),
xcb_randr_query_output_property(QX11Info::connection(), output, m_backlight)
, nullptr));
if (!propertyReply) {
return false;
}
if (propertyReply->range && xcb_randr_query_output_property_valid_values_length(propertyReply.data()) == 2) {
int32_t *values = xcb_randr_query_output_property_valid_values(propertyReply.data());
value = cur;
min = values[0];
max = values[1];
return true;
}
return false;
}
long XRandrBrightness::backlight_get(xcb_randr_output_t output) const
{
ScopedCPointer<xcb_randr_get_output_property_reply_t> propertyReply;
long value;
if (m_backlight != XCB_ATOM_NONE) {
propertyReply.reset(xcb_randr_get_output_property_reply(QX11Info::connection(),
xcb_randr_get_output_property(QX11Info::connection(), output, m_backlight, XCB_ATOM_NONE, 0, 4, 0, 0)
, nullptr));
if (!propertyReply) {
return -1;
}
}
if (!propertyReply || propertyReply->type != XCB_ATOM_INTEGER || propertyReply->num_items != 1 || propertyReply->format != 32) {
value = -1;
} else {
value = *(reinterpret_cast<long *>(xcb_randr_get_output_property_data(propertyReply.data())));
}
return value;
}
void XRandrBrightness::backlight_set(xcb_randr_output_t output, long value)
{
xcb_randr_change_output_property(QX11Info::connection(), output, m_backlight, XCB_ATOM_INTEGER,
32, XCB_PROP_MODE_REPLACE,
1, reinterpret_cast<unsigned char *>(&value));
}
float XRandrBrightness::gamma_brightness_get(xcb_randr_output_t output)
{
xcb_generic_error_t *error;
xcb_randr_get_output_info_cookie_t output_info_cookie = xcb_randr_get_output_info (QX11Info::connection(), output, 0);
ScopedCPointer<xcb_randr_get_output_info_reply_t> output_info(xcb_randr_get_output_info_reply (QX11Info::connection(), output_info_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting output_info";
return -1;
}
if(output_info == nullptr)
{
qDebug() << "Error: output_info is null";
return -1;
}
// xcb_randr_get_output_info_reply_t tiene como elemento crtc
xcb_randr_get_crtc_gamma_cookie_t gamma_cookie = xcb_randr_get_crtc_gamma_unchecked (QX11Info::connection(), output_info->crtc);
ScopedCPointer<xcb_randr_get_crtc_gamma_reply_t> gamma_reply(xcb_randr_get_crtc_gamma_reply (QX11Info::connection(), gamma_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting gamma_reply";
return -1;
}
if(gamma_reply == nullptr)
{
qDebug() << "Error: gamma_reply is null";
return -1;
}
uint16_t * red = xcb_randr_get_crtc_gamma_red (gamma_reply.data());
if(red == nullptr)
{
qDebug() << "Error: red is null";
return -1;
}
int red_length = xcb_randr_get_crtc_gamma_red_length(gamma_reply.data());
// uint16_t *green = xcb_randr_get_crtc_gamma_green (gamma_reply);
// if(green == NULL)
// {
// qDebug() << "Error: green is null";
// return -1;
// }
// uint16_t *blue = xcb_randr_get_crtc_gamma_blue (gamma_reply);
// if(blue == NULL)
// {
// qDebug() << "Error: blue is null";
// return -1;
// }
float brightness = (float)red[red_length-1]/65535.0;
return brightness;
}
void XRandrBrightness::gamma_brightness_set(xcb_randr_output_t output, float percent)
{
xcb_generic_error_t *error;
xcb_randr_get_output_info_cookie_t output_info_cookie = xcb_randr_get_output_info (QX11Info::connection(), output, 0);
ScopedCPointer<xcb_randr_get_output_info_reply_t> output_info(xcb_randr_get_output_info_reply (QX11Info::connection(), output_info_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting output_info";
return;
}
if(output_info == nullptr)
{
qDebug() << "Error: output_info is null";
return;
}
// xcb_randr_get_output_info_reply_t tiene como elemento crtc
xcb_randr_get_crtc_gamma_cookie_t gamma_cookie = xcb_randr_get_crtc_gamma_unchecked (QX11Info::connection(), output_info->crtc);
ScopedCPointer<xcb_randr_get_crtc_gamma_reply_t> gamma_reply(xcb_randr_get_crtc_gamma_reply (QX11Info::connection(), gamma_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting gamma_reply";
return;
}
if(gamma_reply == nullptr)
{
qDebug() << "Error: gamma_reply is null";
return;
}
uint16_t *red = xcb_randr_get_crtc_gamma_red (gamma_reply.data());
if(red == nullptr)
{
qDebug() << "Error: red is null";
return;
}
int red_length = xcb_randr_get_crtc_gamma_red_length(gamma_reply.data());
uint16_t *green = xcb_randr_get_crtc_gamma_green (gamma_reply.data());
if(green == nullptr)
{
qDebug() << "Error: green is null";
return;
}
uint16_t *blue = xcb_randr_get_crtc_gamma_blue (gamma_reply.data());
if(blue == nullptr)
{
qDebug() << "Error: blue is null";
return;
}
float max_gamma = 65535*percent;
for(int i=0;i<red_length;i++)
{
int value = qMin((int)(((float)i/(float)(red_length-1))*max_gamma),65535);
green[i] = blue[i] = red[i] = value;
}
xcb_randr_set_crtc_gamma (QX11Info::connection(), output_info->crtc, red_length, red, green, blue);
}
QList<MonitorInfo> XRandrBrightness::getMonitorsInfo()
{
QList<MonitorInfo> monitors;
if (!m_resources) {
return monitors;
}
auto *outputs = xcb_randr_get_screen_resources_current_outputs(m_resources.data());
for (int i = 0; i < m_resources->num_outputs; ++i) {
xcb_randr_output_t output = outputs[i];
xcb_generic_error_t *error;
xcb_randr_get_output_info_cookie_t output_info_cookie = xcb_randr_get_output_info (QX11Info::connection(), output, 0);
ScopedCPointer <xcb_randr_get_output_info_reply_t> output_info(xcb_randr_get_output_info_reply (QX11Info::connection(), output_info_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting output_info";
continue;
}
if(output_info == nullptr)
{
qDebug() << "Error: output_info is null";
continue;
}
QString name = QString::fromUtf8((const char *) xcb_randr_get_output_info_name(output_info.data()), output_info->name_len);
qDebug() << "Found output:" << name;
// Is connected?
if ( (xcb_randr_connection_t)(output_info->connection) != XCB_RANDR_CONNECTION_CONNECTED )
{
qDebug() << "Output is not connected";
continue; // This output is not connected. Check other
}
// Is enabled?
if( output_info->crtc == 0)
{
qDebug() << "Crtc is not null. Output not enabled.";
continue;
}
xcb_randr_get_crtc_info_cookie_t crtc_info_cookie = xcb_randr_get_crtc_info_unchecked (QX11Info::connection(), output_info->crtc, 0);
ScopedCPointer<xcb_randr_get_crtc_info_reply_t> crtc_info(xcb_randr_get_crtc_info_reply (QX11Info::connection(), crtc_info_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting output_info";
continue;
}
if(crtc_info == nullptr)
{
qDebug() << "Error: output_info is null";
continue;
}
if( crtc_info->mode == XCB_NONE )
{
qDebug() << "No modes. Output not enabled.";
continue;
}
// Output is connected and enabled. Get data:
bool backlightIsSuported = false;
long cur, min, max, backlight_max = -1;
if (backlight_get(output) != -1)
{
if (backlight_get_with_range(output, cur, min, max))
{
backlightIsSuported = true;
backlight_max = max - min;
}
}
MonitorInfo monitor((int)output, name, backlight_max);
if(backlightIsSuported)
monitor.setBacklight(cur-min);
monitor.setBrightness(gamma_brightness_get(output));
qDebug() << "Output:" << name << "added";
monitors.append(monitor);
}
return monitors;
}
void XRandrBrightness::setMonitorsSettings(QList<MonitorInfo> monitors)
{
if (!m_resources) {
return;
}
auto *outputs = xcb_randr_get_screen_resources_current_outputs(m_resources.data());
for (int i = 0; i < m_resources->num_outputs; ++i) {
xcb_randr_output_t output = outputs[i];
xcb_generic_error_t *error;
xcb_randr_get_output_info_cookie_t output_info_cookie = xcb_randr_get_output_info (QX11Info::connection(), output, 0);
ScopedCPointer<xcb_randr_get_output_info_reply_t> output_info(xcb_randr_get_output_info_reply (QX11Info::connection(), output_info_cookie, &error));
if(error != nullptr)
{
qDebug() << "Error getting output_info";
continue;
}
if(output_info == nullptr)
{
qDebug() << "Error: output_info is null";
continue;
}
// Is connected?
if ( (xcb_randr_connection_t)(output_info->connection) != XCB_RANDR_CONNECTION_CONNECTED )
continue; // This output is not connected. Check other
// Is enabled?
if( output_info->crtc == 0)
continue;
xcb_randr_get_crtc_info_cookie_t crtc_info_cookie = xcb_randr_get_crtc_info_unchecked (QX11Info::connection(), output_info->crtc, 0);
ScopedCPointer<xcb_randr_get_crtc_info_reply_t> crtc_info(xcb_randr_get_crtc_info_reply (QX11Info::connection(), crtc_info_cookie, &error));
if(error != nullptr)
continue;
if(crtc_info == nullptr || crtc_info->mode == XCB_NONE )
continue;
QString name = QString::fromUtf8((const char *) xcb_randr_get_output_info_name(output_info.data()), output_info->name_len);
// Output is connected and enabled. Get data:
bool backlightIsSuported = false;
long cur, min, max, backlight_value = 0;
if (backlight_get(output) != -1)
{
if (backlight_get_with_range(output, cur, min, max))
{
backlightIsSuported = true;
backlight_value = cur - min;
}
}
float brightness_value = gamma_brightness_get(output);
// Compare output info with settings and set it.
for(const MonitorInfo &monitor: monitors)
{
//qDebug() << "[XRandrBrightness::setMonitorsSettings]" << monitor.id() << (int)output << monitor.name() << name ;
if(monitor.id() == (int)output && monitor.name() == name)
{
// Set settings
if(backlightIsSuported && monitor.backlight() != backlight_value)
backlight_set(output, min+monitor.backlight());
if(monitor.brightness() != brightness_value)
gamma_brightness_set(output, monitor.brightness());
break;
}
}
}
}
| lgpl-2.1 |
colede/qtcreator | src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp | 2 | 11698 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/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 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlprofilermodelmanager.h"
#include "qmlprofilerdatamodel.h"
#include "qv8profilerdatamodel.h"
#include "qmlprofilertracefile.h"
#include <utils/qtcassert.h>
#include <QDebug>
#include <QFile>
namespace QmlProfiler {
namespace Internal {
/////////////////////////////////////////////////////////////////////
QmlProfilerDataState::QmlProfilerDataState(QmlProfilerModelManager *modelManager, QObject *parent)
: QObject(parent), m_state(Empty), m_modelManager(modelManager)
{
connect(this, SIGNAL(error(QString)), m_modelManager, SIGNAL(error(QString)));
connect(this, SIGNAL(stateChanged()), m_modelManager, SIGNAL(stateChanged()));
}
void QmlProfilerDataState::setState(QmlProfilerDataState::State state)
{
// It's not an error, we are continuously calling "AcquiringData" for example
if (m_state == state)
return;
switch (state) {
case ClearingData:
QTC_ASSERT(m_state == Done || m_state == Empty || m_state == AcquiringData, /**/);
break;
case Empty:
// if it's not empty, complain but go on
QTC_ASSERT(m_modelManager->isEmpty(), /**/);
break;
case AcquiringData:
// we're not supposed to receive new data while processing older data
QTC_ASSERT(m_state != ProcessingData, return);
break;
case ProcessingData:
QTC_ASSERT(m_state == AcquiringData, return);
break;
case Done:
QTC_ASSERT(m_state == ProcessingData || m_state == Empty, return);
break;
default:
emit error(tr("Trying to set unknown state in events list."));
break;
}
m_state = state;
emit stateChanged();
return;
}
/////////////////////////////////////////////////////////////////////
QmlProfilerTraceTime::QmlProfilerTraceTime(QObject *parent) : QObject(parent)
{
clear();
}
QmlProfilerTraceTime::~QmlProfilerTraceTime()
{
}
qint64 QmlProfilerTraceTime::startTime() const
{
return m_startTime;
}
qint64 QmlProfilerTraceTime::endTime() const
{
return m_endTime;
}
qint64 QmlProfilerTraceTime::duration() const
{
return endTime() - startTime();
}
void QmlProfilerTraceTime::clear()
{
setStartTime(-1);
setEndTime(-1);
}
void QmlProfilerTraceTime::setStartTime(qint64 time)
{
if (time != m_startTime) {
m_startTime = time;
emit startTimeChanged(time);
}
}
void QmlProfilerTraceTime::setEndTime(qint64 time)
{
if (time != m_endTime) {
m_endTime = time;
emit endTimeChanged(time);
}
}
} // namespace Internal
/////////////////////////////////////////////////////////////////////
class QmlProfilerModelManager::QmlProfilerModelManagerPrivate
{
public:
QmlProfilerModelManagerPrivate(QmlProfilerModelManager *qq) : q(qq) {}
~QmlProfilerModelManagerPrivate() {}
QmlProfilerModelManager *q;
QmlProfilerDataModel *model;
QV8ProfilerDataModel *v8Model;
QmlProfilerDataState *dataState;
QmlProfilerTraceTime *traceTime;
QVector <double> partialCounts;
QVector <int> partialCountWeights;
int totalWeight;
double progress;
double previousProgress;
qint64 estimatedTime;
// file to load
QString fileName;
};
QmlProfilerModelManager::QmlProfilerModelManager(Utils::FileInProjectFinder *finder, QObject *parent) :
QObject(parent), d(new QmlProfilerModelManagerPrivate(this))
{
d->totalWeight = 0;
d->model = new QmlProfilerDataModel(finder, this);
d->v8Model = new QV8ProfilerDataModel(finder, this);
d->dataState = new QmlProfilerDataState(this, this);
d->traceTime = new QmlProfilerTraceTime(this);
}
QmlProfilerModelManager::~QmlProfilerModelManager()
{
delete d;
}
QmlProfilerTraceTime *QmlProfilerModelManager::traceTime() const
{
return d->traceTime;
}
QmlProfilerDataModel *QmlProfilerModelManager::qmlModel() const
{
return d->model;
}
QV8ProfilerDataModel *QmlProfilerModelManager::v8Model() const
{
return d->v8Model;
}
bool QmlProfilerModelManager::isEmpty() const
{
return d->model->isEmpty() && d->v8Model->isEmpty();
}
int QmlProfilerModelManager::count() const
{
return d->model->count();
}
double QmlProfilerModelManager::progress() const
{
return d->progress;
}
int QmlProfilerModelManager::registerModelProxy()
{
d->partialCounts << 0;
d->partialCountWeights << 1;
d->totalWeight++;
return d->partialCounts.count()-1;
}
void QmlProfilerModelManager::setProxyCountWeight(int proxyId, int weight)
{
d->totalWeight += weight - d->partialCountWeights[proxyId];
d->partialCountWeights[proxyId] = weight;
}
void QmlProfilerModelManager::modelProxyCountUpdated(int proxyId, qint64 count, qint64 max)
{
d->progress -= d->partialCounts[proxyId] * d->partialCountWeights[proxyId] /
d->totalWeight;
if (max <= 0)
d->partialCounts[proxyId] = 1;
else
d->partialCounts[proxyId] = (double)count / (double) max;
d->progress += d->partialCounts[proxyId] * d->partialCountWeights[proxyId] /
d->totalWeight;
if (d->progress - d->previousProgress > 0.01) {
d->previousProgress = d->progress;
emit progressChanged();
}
}
qint64 QmlProfilerModelManager::estimatedProfilingTime() const
{
return d->estimatedTime;
}
void QmlProfilerModelManager::newTimeEstimation(qint64 estimation)
{
d->estimatedTime = estimation;
}
void QmlProfilerModelManager::addQmlEvent(int type,
int bindingType,
qint64 startTime,
qint64 length,
const QStringList &data,
const QmlDebug::QmlEventLocation &location,
qint64 ndata1,
qint64 ndata2,
qint64 ndata3,
qint64 ndata4,
qint64 ndata5)
{
// If trace start time was not explicitly set, use the first event
if (d->traceTime->startTime() == -1)
d->traceTime->setStartTime(startTime);
QTC_ASSERT(state() == QmlProfilerDataState::AcquiringData, /**/);
d->model->addQmlEvent(type, bindingType, startTime, length, data, location, ndata1, ndata2, ndata3, ndata4, ndata5);
}
void QmlProfilerModelManager::addV8Event(int depth, const QString &function, const QString &filename,
int lineNumber, double totalTime, double selfTime)
{
d->v8Model->addV8Event(depth, function, filename, lineNumber,totalTime, selfTime);
}
void QmlProfilerModelManager::complete()
{
switch (state()) {
case QmlProfilerDataState::ProcessingData:
setState(QmlProfilerDataState::Done);
emit dataAvailable();
break;
case QmlProfilerDataState::AcquiringData:
// If trace end time was not explicitly set, use the last event
if (d->traceTime->endTime() == 0)
d->traceTime->setEndTime(d->model->lastTimeMark());
setState(QmlProfilerDataState::ProcessingData);
d->model->complete();
d->v8Model->complete();
break;
case QmlProfilerDataState::Empty:
setState(QmlProfilerDataState::Done);
break;
case QmlProfilerDataState::Done:
break;
default:
emit error(tr("Unexpected complete signal in data model."));
break;
}
}
void QmlProfilerModelManager::modelProcessingDone()
{
Q_ASSERT(state() == QmlProfilerDataState::ProcessingData);
if (d->model->processingDone() && d->v8Model->processingDone())
complete();
}
void QmlProfilerModelManager::save(const QString &filename)
{
QFile file(filename);
if (!file.open(QIODevice::WriteOnly)) {
emit error(tr("Could not open %1 for writing.").arg(filename));
return;
}
QmlProfilerFileWriter writer;
writer.setTraceTime(traceTime()->startTime(), traceTime()->endTime(), traceTime()->duration());
writer.setV8DataModel(d->v8Model);
writer.setQmlEvents(d->model->getEvents());
writer.save(&file);
}
void QmlProfilerModelManager::load(const QString &filename)
{
d->fileName = filename;
load();
}
void QmlProfilerModelManager::setFilename(const QString &filename)
{
d->fileName = filename;
}
void QmlProfilerModelManager::load()
{
QString filename = d->fileName;
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
emit error(tr("Could not open %1 for reading.").arg(filename));
return;
}
// erase current
clear();
setState(QmlProfilerDataState::AcquiringData);
QmlProfilerFileReader reader;
connect(&reader, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
connect(&reader, SIGNAL(rangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
qint64, qint64, qint64, qint64, qint64)),
this, SLOT(addQmlEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
qint64, qint64, qint64, qint64, qint64)));
connect(&reader, SIGNAL(traceStartTime(qint64)), traceTime(), SLOT(setStartTime(qint64)));
connect(&reader, SIGNAL(traceEndTime(qint64)), traceTime(), SLOT(setEndTime(qint64)));
reader.setV8DataModel(d->v8Model);
reader.load(&file);
complete();
}
void QmlProfilerModelManager::setState(QmlProfilerDataState::State state)
{
d->dataState->setState(state);
}
QmlProfilerDataState::State QmlProfilerModelManager::state() const
{
return d->dataState->state();
}
void QmlProfilerModelManager::clear()
{
setState(QmlProfilerDataState::ClearingData);
for (int i = 0; i < d->partialCounts.count(); i++)
d->partialCounts[i] = 0;
d->progress = 0;
d->previousProgress = 0;
d->model->clear();
d->v8Model->clear();
d->traceTime->clear();
setState(QmlProfilerDataState::Empty);
}
void QmlProfilerModelManager::prepareForWriting()
{
setState(QmlProfilerDataState::AcquiringData);
}
} // namespace QmlProfiler
| lgpl-2.1 |
kobolabs/qt-everywhere-4.8.0 | src/xmlpatterns/expr/qaxisstep.cpp | 3 | 9905 | /****************************************************************************
**
** Copyright (C) 2011 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$
** GNU Lesser General Public License Usage
** 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.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qbuiltintypes_p.h"
#include "qcommonsequencetypes_p.h"
#include "qitemmappingiterator_p.h"
#include "qgenericsequencetype_p.h"
#include "qparentnodeaxis_p.h"
#include "qaxisstep_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
namespace QPatternist
{
/**
* This operator is needed for the s_whenAxisNodeKindEmpty array. The @c int constructors
* ensure we invoke another operator| such that we don't get an infinite loop.
*/
static inline QXmlNodeModelIndex::NodeKind operator|(const QXmlNodeModelIndex::NodeKind &op1, const QXmlNodeModelIndex::NodeKind &op2)
{
return QXmlNodeModelIndex::NodeKind(int(op1) | int(op2));
}
}
/**
* @note The order is significant. It is of the same order as the values in QXmlNodeModelIndex::Axis is declared.
*/
const QXmlNodeModelIndex::NodeKind AxisStep::s_whenAxisNodeKindEmpty[] =
{
QXmlNodeModelIndex::Attribute|QXmlNodeModelIndex::Text|QXmlNodeModelIndex::ProcessingInstruction|QXmlNodeModelIndex::Comment|QXmlNodeModelIndex::Namespace, // child;
QXmlNodeModelIndex::Attribute|QXmlNodeModelIndex::Text|QXmlNodeModelIndex::ProcessingInstruction|QXmlNodeModelIndex::Comment|QXmlNodeModelIndex::Namespace, // descendant;
QXmlNodeModelIndex::Document|QXmlNodeModelIndex::Attribute|QXmlNodeModelIndex::Text|QXmlNodeModelIndex::ProcessingInstruction|QXmlNodeModelIndex::Comment|QXmlNodeModelIndex::Namespace,// attribute;
QXmlNodeModelIndex::NodeKind(0), // self;
QXmlNodeModelIndex::NodeKind(0), // descendant-or-self;
QXmlNodeModelIndex::Document|QXmlNodeModelIndex::Attribute|QXmlNodeModelIndex::Text|QXmlNodeModelIndex::ProcessingInstruction|QXmlNodeModelIndex::Comment|QXmlNodeModelIndex::Namespace, // namespace;
QXmlNodeModelIndex::Document, // following;
QXmlNodeModelIndex::Document, // parent;
QXmlNodeModelIndex::Document, // ancestor
QXmlNodeModelIndex::Document|QXmlNodeModelIndex::Attribute|QXmlNodeModelIndex::Namespace, // preceding-sibling;
QXmlNodeModelIndex::Document|QXmlNodeModelIndex::Attribute|QXmlNodeModelIndex::Namespace, // following-sibling;
QXmlNodeModelIndex::Document, // preceding;
QXmlNodeModelIndex::NodeKind(0) // ancestor-or-self;
};
bool AxisStep::isAlwaysEmpty(const QXmlNodeModelIndex::Axis axis, const QXmlNodeModelIndex::NodeKind nodeKind)
{
return (s_whenAxisNodeKindEmpty[(1 >> axis) - 1] & nodeKind) != 0;
}
AxisStep::AxisStep(const QXmlNodeModelIndex::Axis a,
const ItemType::Ptr &nt) : m_axis(a),
m_nodeTest(nt)
{
Q_ASSERT(m_nodeTest);
Q_ASSERT_X(BuiltinTypes::node->xdtTypeMatches(m_nodeTest), Q_FUNC_INFO,
"We assume we're a node type.");
}
Item AxisStep::mapToItem(const QXmlNodeModelIndex &node,
const DynamicContext::Ptr &context) const
{
Q_ASSERT(!node.isNull());
Q_ASSERT(Item(node).isNode());
Q_ASSERT(Item(node));
Q_UNUSED(context);
if(m_nodeTest->itemMatches(Item(node)))
return Item(node);
else
return Item();
}
Item::Iterator::Ptr AxisStep::evaluateSequence(const DynamicContext::Ptr &context) const
{
/* If we don't have a focus, it's either a bug or our parent isn't a Path
* that have advanced the focus iterator. Hence, attempt to advance the focus on our own. */
if(!context->contextItem())
context->focusIterator()->next();
Q_ASSERT(context->contextItem());
const QXmlNodeModelIndex::Iterator::Ptr source(context->contextItem().asNode().iterate(m_axis));
return makeItemMappingIterator<Item>(ConstPtr(this), source, context);
}
Item AxisStep::evaluateSingleton(const DynamicContext::Ptr &context) const
{
/* If we don't have a focus, it's either a bug or our parent isn't a Path
* that have advanced the focus iterator. Hence, attempt to advance the focus on our own. */
if(!context->contextItem())
context->focusIterator()->next();
Q_ASSERT(context->contextItem());
const QXmlNodeModelIndex::Iterator::Ptr it(context->contextItem().asNode().iterate(m_axis));
QXmlNodeModelIndex next(it->next());
while(!next.isNull())
{
const Item candidate(mapToItem(next, context));
if(candidate)
return candidate;
else
next = it->next();
};
return Item();
}
Expression::Ptr AxisStep::typeCheck(const StaticContext::Ptr &context,
const SequenceType::Ptr &reqType)
{
if(m_axis == QXmlNodeModelIndex::AxisParent && *m_nodeTest == *BuiltinTypes::node)
{
/* We only rewrite parent::node() to ParentNodeAxis. */
return rewrite(Expression::Ptr(new ParentNodeAxis()), context)->typeCheck(context, reqType);
}
/* TODO temporarily disabled
else if(isAlwaysEmpty(m_axis, static_cast<const AnyNodeType *>(m_nodeTest.data())->nodeKind()))
return EmptySequence::create(this, context);
*/
else
return EmptyContainer::typeCheck(context, reqType);
}
SequenceType::Ptr AxisStep::staticType() const
{
Cardinality cardinality;
if(m_axis == QXmlNodeModelIndex::AxisSelf || m_axis == QXmlNodeModelIndex::AxisParent)
cardinality = Cardinality::zeroOrOne();
else
cardinality = Cardinality::zeroOrMore();
return makeGenericSequenceType(m_nodeTest,
cardinality);
}
SequenceType::List AxisStep::expectedOperandTypes() const
{
SequenceType::List result;
result.append(CommonSequenceTypes::ZeroOrMoreNodes);
return result;
}
Expression::Properties AxisStep::properties() const
{
return RequiresContextItem | DisableElimination;
}
ItemType::Ptr AxisStep::expectedContextItemType() const
{
return BuiltinTypes::node;
}
ExpressionVisitorResult::Ptr AxisStep::accept(const ExpressionVisitor::Ptr &visitor) const
{
return visitor->visit(this);
}
QXmlNodeModelIndex::Axis AxisStep::axis() const
{
return m_axis;
}
QString AxisStep::axisName(const QXmlNodeModelIndex::Axis axis)
{
const char *result = 0;
switch(axis)
{
/* These must not be translated. */
case QXmlNodeModelIndex::AxisAncestorOrSelf: result = "ancestor-or-self"; break;
case QXmlNodeModelIndex::AxisAncestor: result = "ancestor"; break;
case QXmlNodeModelIndex::AxisAttributeOrTop: result = "attribute-or-top"; break;
case QXmlNodeModelIndex::AxisAttribute: result = "attribute"; break;
case QXmlNodeModelIndex::AxisChildOrTop: result = "child-or-top"; break;
case QXmlNodeModelIndex::AxisChild: result = "child"; break;
case QXmlNodeModelIndex::AxisDescendantOrSelf: result = "descendant-or-self"; break;
case QXmlNodeModelIndex::AxisDescendant: result = "descendant"; break;
case QXmlNodeModelIndex::AxisFollowing: result = "following"; break;
case QXmlNodeModelIndex::AxisFollowingSibling: result = "following-sibling"; break;
case QXmlNodeModelIndex::AxisNamespace: result = "namespace"; break;
case QXmlNodeModelIndex::AxisParent: result = "parent"; break;
case QXmlNodeModelIndex::AxisPreceding: result = "preceding"; break;
case QXmlNodeModelIndex::AxisPrecedingSibling: result = "preceding-sibling"; break;
case QXmlNodeModelIndex::AxisSelf: result = "self"; break;
}
Q_ASSERT_X(result, Q_FUNC_INFO, "An unknown axis type was apparently encountered.");
return QString::fromLatin1(result);
}
PatternPriority AxisStep::patternPriority() const
{
return static_cast<const AnyNodeType *>(m_nodeTest.data())->patternPriority();
}
Expression::ID AxisStep::id() const
{
return IDAxisStep;
}
QT_END_NAMESPACE
| lgpl-2.1 |
fjardon/motif | tests/Toolkit/Shells/Visual.c | 3 | 3956 | /* $XConsortium: Visual.c /main/5 1995/07/15 21:09:39 drk $ */
/*
* Motif
*
* Copyright (c) 1987-2012, The Open Group. All rights reserved.
*
* These libraries and programs are free software; you can
* redistribute them and/or modify them 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.
*
* These libraries and programs are distributed in the hope that
* they will be useful, but WITHOUT ANY WARRANTY; without even the
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with these librararies and programs; if not, write
* to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301 USA
*
*/
/*
* HISTORY
*/
/* Test created to check the setting of the resource XmNvisual in the Shell
widget
*/
#include <testlib.h>
#include <string.h>
void
doit()
{
Screen * screen;
XrmValue args[10];
Cardinal num_args = 0;
Boolean result;
static char string[100];
static char * visual_class[] = { "StaticGray",
"StaticColor",
"TrueColor",
"GrayScale",
"PseudoColor",
"DirectColor" };
int visual_found[6];
int i = 0;
static Visual * visual[6];
Display * display;
XrmValue fromVal;
XrmValue toVal;
Arg shell_args[10];
Cardinal num_shell_args = 0;
Visual * ret_visual;
int depth;
int size;
char buf[512];
char tmp[256];
screen = XtScreen(Shell1);
display = DisplayOfScreen(screen);
depth = DefaultDepthOfScreen(screen);
args[0].addr = (XPointer) &screen;
args[0].size = sizeof(Screen *);
num_args++;
args[1].addr = (XPointer) &depth;
args[1].size = sizeof(int);
num_args++;
sprintf(buf,
"\nVisual Class\tVisual Found\n------------\t------------\n\n");
for (i = 0; i < 6; i++) {
strcpy(string, XrmQuarkToString(XrmStringToQuark(visual_class[i])));
size = strlen((char *)string);
fromVal.addr = (XPointer)string;
fromVal.size = sizeof(size);
toVal.addr = (XPointer) &visual[i];
toVal.size = sizeof(Visual);
result = XtCallConverter(display, XtCvtStringToVisual, args, num_args,
&fromVal, &toVal, NULL);
if (result == False) {
sprintf(tmp, "%s\tNo\n", visual_class[i]);
strcat(buf, tmp);
visual_found[i] = False;
}
else {
sprintf(tmp, "%s\tYes\n", visual_class[i]);
strcat(buf, tmp);
visual_found[i] = True;
}
}
printf("%s\n", buf);
for (i = 0; i < 6 ; i++) {
if (!visual_found[i])
continue;
num_shell_args = 0;
printf("For visual class %s...\n\n", visual_class[i]);
XtSetArg(shell_args[0], XmNvisual, &ret_visual); num_shell_args++;
XtGetValues(Shell1, shell_args, num_shell_args);
printf("original visual: %x\n", ret_visual);
printf("replacement visual: %x\n", visual[i]);
num_shell_args = 0;
XtSetArg(shell_args[0], XmNvisual, visual[i]); num_shell_args++;
XtSetValues(Shell1, shell_args, num_shell_args);
num_shell_args = 0;
XtSetArg(shell_args[0], XmNvisual, &ret_visual); num_shell_args++;
XtGetValues(Shell1, shell_args, num_shell_args);
if (visual[i] != ret_visual) {
printf("Error. Incorrect visual value returned. Visual class: %s\n\n",
visual_class[i]);
}
else {
printf("Visual successfully modified\n\n");
}
}
}
void
main (int argc, char **argv)
{
Arg args[10];
int n;
CommonTestInit (argc,argv);
n=0;
XtSetArg (args[n], XmNiconName, "TESTING"); n++;
XtSetArg (args[n], XmNwidth,100); n++;
XtSetArg (args[n], XmNheight,100); n++;
XtSetValues (Shell1, args, n);
XtRealizeWidget (Shell1);
CommonPause();
doit();
CommonPause();
CommonPause();
XtAppMainLoop (app_context);
}
| lgpl-2.1 |
tfar/relic | test/test_rand.c | 4 | 18991 | /*
* RELIC is an Efficient LIbrary for Cryptography
* Copyright (C) 2007-2015 RELIC Authors
*
* This file is part of RELIC. RELIC is legal property of its developers,
* whose names are not listed here. Please refer to the COPYRIGHT file
* for contact information.
*
* RELIC is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* RELIC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with RELIC. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
*
* Tests for random number generation.
*
* @ingroup test
*/
#include <stdio.h>
#include "relic.h"
#include "relic_test.h"
#if RAND == HASH
/*
* Test vectors taken from:
* - http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/Hash_DRBG.pdf
*/
#if MD_MAP == SHONE
#define FUNCTION "sha-1"
uint8_t seed1[60];
uint8_t result1[] = {
0x9F, 0x7C, 0xFF, 0x1E, 0xCA, 0x23, 0xE7, 0x50, 0xF6, 0x63,
0x26, 0x96, 0x9F, 0x11, 0x80, 0x0F, 0x12, 0x08, 0x8B, 0xA6,
0x8E, 0x44, 0x1D, 0x15, 0xD8, 0x88, 0xB3, 0xFE, 0x12, 0xBF,
0x66, 0xFE, 0x05, 0x74, 0x94, 0xF4, 0x54, 0x6D, 0xE2, 0xF1,
0xB7, 0x7A, 0xA5, 0xC0, 0xCD, 0x55, 0xBB, 0xCE, 0xED, 0x75,
0x74, 0xAF, 0x22, 0x3A, 0xFD, 0x98, 0x8C, 0x7E, 0xEC, 0x8E,
0xFF, 0x4A, 0x94, 0xE5, 0xE8, 0x9D, 0x26, 0xA0, 0x4F, 0x58,
0xFA, 0x79, 0xF5, 0xE0, 0xD3, 0x70, 0x2D, 0x7A, 0x9A, 0x6A,
};
uint8_t result2[] = {
0x56, 0xEF, 0x49, 0x13, 0x37, 0x39, 0x94, 0xD5, 0x53, 0x9F,
0x4D, 0x7D, 0x17, 0xAF, 0xE7, 0x44, 0x8C, 0xDF, 0x5E, 0x72,
0x41, 0x6C, 0xC6, 0xA7, 0x1A, 0x34, 0x00, 0x59, 0xFA, 0x0D,
0x5A, 0xE5, 0x26, 0xB2, 0x32, 0x50, 0xC4, 0x6C, 0x09, 0x44,
0x57, 0x5B, 0x37, 0xA2, 0x73, 0x98, 0x14, 0xF9, 0x66, 0xC6,
0x3B, 0x60, 0xA2, 0xC4, 0xF1, 0x49, 0xCA, 0x9A, 0xCC, 0x84,
0xFC, 0x4B, 0x25, 0x49, 0x32, 0x89, 0xB0, 0x85, 0xC6, 0x7B,
0x2E, 0x30, 0xF5, 0xF0, 0xB9, 0x9A, 0x2C, 0x34, 0x9E, 0x2A,
};
#elif MD_MAP == SH224
#define FUNCTION "sha-224"
uint8_t seed1[62];
uint8_t result1[] = {
0x5E, 0x68, 0xBD, 0xE0, 0x9A, 0xAA, 0x08, 0xBC, 0x11, 0xB3,
0x27, 0x90, 0x2C, 0x82, 0xF0, 0x11, 0x4C, 0xBA, 0x0F, 0x9C,
0xCC, 0xA6, 0x20, 0x3B, 0xA3, 0x94, 0x00, 0x91, 0x3E, 0xCD,
0x36, 0x71, 0xA5, 0xB6, 0x0E, 0xF9, 0x22, 0x99, 0x9D, 0x90,
0xFC, 0xEE, 0xEC, 0x5C, 0x22, 0x7E, 0x5D, 0x25, 0xC5, 0x69,
0x21, 0xEE, 0x57, 0x2E, 0xD4, 0x72, 0xDC, 0x05, 0x6F, 0xCB,
0x35, 0xFF, 0x51, 0xD7, 0xD9, 0xFB, 0x72, 0xFD, 0x4F, 0xD1,
0xB1, 0xD2, 0x46, 0x45, 0x1D, 0xB5, 0x6C, 0xD4, 0xF8, 0x89,
0xE4, 0x32, 0xE3, 0x27, 0x3F, 0x9E, 0xD8, 0x2D, 0xE3, 0xEF,
0x7C, 0xD2, 0x8B, 0x6A, 0x9C, 0x0F, 0x4D, 0x78, 0xE5, 0xC8,
0x45, 0x1D, 0x36, 0x34, 0x0A, 0x2B, 0xD7, 0xE6, 0x9F, 0xAB,
0x32, 0xEB
};
uint8_t result2[] = {
0x3F, 0xE2, 0xAD, 0x85, 0x24, 0xCE, 0x60, 0xE7, 0xC2, 0x1C,
0x38, 0xA1, 0xDA, 0xB0, 0x2F, 0x3C, 0x20, 0x50, 0x11, 0x82,
0xF3, 0x89, 0xEE, 0x69, 0x9F, 0x03, 0xFD, 0x87, 0x79, 0xED,
0x17, 0xC6, 0x5B, 0x87, 0xAC, 0xEE, 0xEB, 0xF1, 0xD1, 0x46,
0xE7, 0xEE, 0x10, 0x6C, 0xEC, 0x89, 0x55, 0xEE, 0xAF, 0xC1,
0x8A, 0xBB, 0xC5, 0x62, 0xA5, 0x66, 0x8B, 0xB4, 0x9B, 0x0B,
0x9C, 0x2F, 0xC7, 0x01, 0x89, 0xB2, 0x4E, 0x02, 0x73, 0x59,
0x54, 0x58, 0xCD, 0x78, 0x0F, 0xBF, 0xA5, 0xF2, 0x16, 0x12,
0x24, 0x21, 0xB8, 0x0B, 0xF7, 0x73, 0xD7, 0x36, 0xE6, 0xE1,
0x1D, 0xEB, 0xB4, 0x24, 0x77, 0xD6, 0x96, 0x68, 0xD2, 0xF9,
0x40, 0xC6, 0x60, 0xF6, 0xA2, 0xC1, 0xC9, 0xB4, 0x17, 0x95,
0x92, 0xE0
};
#elif MD_MAP == SH256
uint8_t seed1[63];
#define FUNCTION "sha-256"
uint8_t result1[] = {
0x77, 0xE0, 0x5A, 0x0E, 0x7D, 0xC7, 0x8A, 0xB5, 0xD8, 0x93,
0x4D, 0x5E, 0x93, 0xE8, 0x2C, 0x06, 0xA0, 0x7C, 0x04, 0xCE,
0xE6, 0xC9, 0xC5, 0x30, 0x45, 0xEE, 0xB4, 0x85, 0x87, 0x27,
0x77, 0xCF, 0x3B, 0x3E, 0x35, 0xC4, 0x74, 0xF9, 0x76, 0xB8,
0x94, 0xBF, 0x30, 0x1A, 0x86, 0xFA, 0x65, 0x1F, 0x46, 0x39,
0x70, 0xE8, 0x9D, 0x4A, 0x05, 0x34, 0xB2, 0xEC, 0xAD, 0x29,
0xEC, 0x04, 0x4E, 0x7E, 0x5F, 0xF4, 0xBA, 0x49, 0x3C, 0x40,
0xCF, 0xFF, 0x3B, 0x01, 0xE4, 0x72, 0xC5, 0x75, 0x66, 0x8C,
0xCE, 0x38, 0x80, 0xB9, 0x29, 0x0B, 0x05, 0xBF, 0xED, 0xE5,
0xEC, 0x96, 0xED, 0x5E, 0x9B, 0x28, 0x98, 0x50, 0x8B, 0x09,
0xBC, 0x80, 0x0E, 0xEE, 0x09, 0x9A, 0x3C, 0x90, 0x60, 0x2A,
0xBD, 0x4B, 0x1D, 0x4F, 0x34, 0x3D, 0x49, 0x7C, 0x60, 0x55,
0xC8, 0x7B, 0xB9, 0x56, 0xD5, 0x3B, 0xF3, 0x51
};
uint8_t result2[] = {
0x92, 0x27, 0x55, 0x23, 0xC7, 0x0E, 0x56, 0x7B, 0xCF, 0x9B,
0x35, 0xEC, 0x50, 0xB9, 0x33, 0xF8, 0x12, 0x61, 0x6D, 0xF5,
0x86, 0xB7, 0xF7, 0x2E, 0xE1, 0xBC, 0x77, 0x35, 0xA5, 0xC2,
0x65, 0x43, 0x73, 0xCB, 0xBC, 0x72, 0x31, 0x6D, 0xFF, 0x84,
0x20, 0xA3, 0x3B, 0xF0, 0x2B, 0x97, 0xAC, 0x8D, 0x19, 0x52,
0x58, 0x3F, 0x27, 0x0A, 0xCD, 0x70, 0x05, 0xCC, 0x02, 0x7F,
0x4C, 0xF1, 0x18, 0x7E, 0x68, 0x1A, 0x46, 0xB2, 0xAA, 0x86,
0x94, 0xA0, 0xFE, 0x4D, 0xEE, 0xA7, 0x20, 0x92, 0x7A, 0x84,
0xEA, 0xAA, 0x98, 0x5E, 0x59, 0xC1, 0x9F, 0x8B, 0xE0, 0x98,
0x4D, 0x8C, 0xBE, 0xF8, 0xC6, 0x9B, 0x75, 0x41, 0x67, 0x64,
0x19, 0x46, 0xE0, 0x40, 0xEE, 0x20, 0x43, 0xE1, 0xCC, 0xB2,
0x9D, 0xCF, 0x06, 0x3C, 0x0A, 0x50, 0x83, 0x0E, 0x42, 0x8E,
0x6D, 0xCA, 0x26, 0x2E, 0xCD, 0x77, 0xC5, 0x42
};
#elif MD_MAP == SH384
#define FUNCTION "sha-384"
uint8_t seed1[123];
uint8_t result1[] = {
0x04, 0xFF, 0x23, 0xAD, 0x15, 0xE7, 0x87, 0x90, 0xAD, 0xD3,
0x6B, 0x43, 0x8B, 0xBC, 0x09, 0x7C, 0x7A, 0x11, 0x74, 0x7C,
0xC2, 0xCC, 0xEE, 0xDE, 0x2C, 0x97, 0x8B, 0x23, 0xB3, 0xDC,
0x63, 0xB7, 0x32, 0xC9, 0x53, 0x06, 0x1D, 0x77, 0x64, 0x99,
0x0A, 0xBF, 0xEF, 0xC4, 0x7A, 0x58, 0x1B, 0x92, 0x1B, 0xC0,
0x42, 0x8C, 0x4F, 0x12, 0x21, 0x24, 0x60, 0xE4, 0x06, 0xA0,
0xF0, 0x65, 0x1E, 0x7F, 0x0C, 0xB9, 0xA9, 0x0A, 0xBF, 0xDB,
0x07, 0xB5, 0x25, 0x56, 0x5C, 0x74, 0xF0, 0xAA, 0x08, 0x50,
0x82, 0xF6, 0xCF, 0x21, 0x3A, 0xAF, 0xAD, 0x0C, 0x06, 0x46,
0x89, 0x50, 0x78, 0xF1, 0xE1, 0xFE, 0x4F, 0x35, 0xB8, 0x5F,
0x95, 0xDE, 0xE3, 0xE8, 0x73, 0x05, 0x49, 0x05, 0xCF, 0xD0,
0x23, 0x41, 0x65, 0x3E, 0x18, 0xF5, 0x29, 0x93, 0x0C, 0xBE,
0x14, 0xD9, 0x09, 0xF3, 0x7F, 0xEA, 0xF2, 0xC7, 0x90, 0xD2,
0x2F, 0xAE, 0x75, 0x16, 0xB4, 0x59, 0x0B, 0xE3, 0x5D, 0x53,
0xE2, 0xFE, 0x1A, 0x35, 0xAF, 0xE4, 0xB6, 0x60, 0x7C, 0xB3,
0x58, 0x58, 0x9C, 0x3B, 0x4D, 0x09, 0x4A, 0x1D, 0x81, 0xFE,
0x07, 0x17, 0xF1, 0xDF, 0x5B, 0xDD, 0xEB, 0x3E, 0x11, 0x4F,
0x13, 0x0B, 0xB7, 0x81, 0xE6, 0x6C, 0x22, 0xB5, 0xB7, 0x70,
0xE8, 0xAE, 0x11, 0x5F, 0xF3, 0x9F, 0x8A, 0xDA, 0xF6, 0x6D,
0xEE, 0xDF
};
uint8_t result2[] = {
0x97, 0x99, 0x3B, 0x78, 0xF7, 0xC3, 0x1C, 0x0E, 0x87, 0x6D,
0xC9, 0x2E, 0xB7, 0xD6, 0xC4, 0x08, 0xE0, 0x9D, 0x60, 0x8A,
0xD6, 0xB9, 0x9D, 0x0E, 0xA2, 0x22, 0x9B, 0x05, 0xA5, 0x78,
0xC4, 0x26, 0x33, 0x4F, 0xCC, 0x8A, 0x1C, 0x7E, 0x67, 0x6E,
0xD2, 0xD8, 0x9A, 0x5B, 0x4C, 0xDF, 0x5B, 0x3F, 0x4A, 0xDF,
0x11, 0x93, 0x6B, 0xF1, 0x4F, 0x4E, 0x10, 0x90, 0x9D, 0xBA,
0x9C, 0x24, 0xF4, 0xFD, 0xFF, 0xDE, 0x72, 0x35, 0x1D, 0xA8,
0xE2, 0xCC, 0x3B, 0x13, 0x5A, 0x39, 0x53, 0x73, 0x89, 0x9E,
0x5F, 0x1A, 0x59, 0x55, 0xB8, 0x80, 0xCA, 0x9B, 0x9E, 0x9D,
0xD4, 0xC9, 0xCA, 0x7F, 0xA4, 0xD4, 0xF5, 0x98, 0x39, 0x46,
0x32, 0x0E, 0x36, 0xC6, 0x4E, 0xF2, 0x83, 0xCA, 0x1F, 0x65,
0xD1, 0x97, 0xCF, 0x81, 0x62, 0x4E, 0xC6, 0x77, 0x8E, 0x77,
0x0E, 0x78, 0x94, 0x9D, 0x84, 0xEF, 0x21, 0xA4, 0x5C, 0xDD,
0x62, 0xD1, 0xDB, 0x76, 0x92, 0x0D, 0x4C, 0x28, 0x36, 0xFC,
0x6A, 0xE5, 0x29, 0x9F, 0xAF, 0x13, 0x57, 0xD9, 0x70, 0x1F,
0xAD, 0x10, 0xFB, 0xD8, 0x8D, 0x1E, 0x28, 0x32, 0x23, 0x94,
0x36, 0xD7, 0x6E, 0xB2, 0x71, 0xBD, 0xC3, 0xCA, 0x04, 0x42,
0x5E, 0xC8, 0x8B, 0xC0, 0xE8, 0x9A, 0x4D, 0x5C, 0x37, 0xFF,
0xCE, 0x7C, 0x6C, 0x3A, 0xBD, 0xE9, 0xC4, 0x13, 0xAE, 0x6D,
0x3F, 0xEA
};
#elif MD_MAP == SH512
#define FUNCTION "sha-512"
uint8_t seed1[127];
uint8_t result1[] = {
0x17, 0x0C, 0xC7, 0x07, 0xC7, 0x1C, 0x69, 0xCE, 0x45, 0xC4,
0x3C, 0xBA, 0xFF, 0x52, 0x10, 0x14, 0x05, 0x72, 0xD4, 0x78,
0x59, 0x52, 0x1B, 0xA1, 0x31, 0x41, 0xBA, 0xDD, 0x2E, 0x5B,
0x9A, 0x7B, 0x3E, 0x80, 0x20, 0x62, 0x5C, 0xD8, 0x89, 0x3F,
0xD6, 0xA4, 0x73, 0x9C, 0x58, 0x1E, 0xD5, 0xBE, 0x7F, 0xA3,
0x14, 0x8A, 0x05, 0xD7, 0xF5, 0x4A, 0xE9, 0xEA, 0xDA, 0xE8,
0xF1, 0xA7, 0x19, 0x4D, 0xF9, 0x4B, 0x6B, 0x75, 0x5B, 0x94,
0x8E, 0x0C, 0x27, 0xE1, 0x74, 0x7F, 0x02, 0xF6, 0x63, 0xD6,
0xB5, 0x14, 0xA0, 0xF5, 0x86, 0xF9, 0x4E, 0x53, 0xD3, 0x21,
0x69, 0xE1, 0xCC, 0xC6, 0x21, 0x1A, 0xD0, 0x34, 0x81, 0x24,
0x19, 0xB6, 0xBA, 0x8F, 0x3C, 0x82, 0x93, 0x04, 0x89, 0x83,
0x93, 0xBF, 0x39, 0xE5, 0x7E, 0x2F, 0xED, 0xF7, 0x75, 0xFC,
0x6E, 0x5E, 0xB0, 0xE3, 0x07, 0xED, 0xCA, 0x0B, 0xD5, 0x15,
0xB9, 0x2B, 0x18, 0x11, 0xF5, 0xAA, 0xD0, 0x2A, 0xAC, 0x9B,
0x39, 0xDF, 0xA5, 0xB8, 0xB1, 0xA9, 0x50, 0x48, 0x7D, 0x34,
0x29, 0xB1, 0x08, 0x1D, 0x0F, 0xEC, 0x28, 0xD5, 0x76, 0x86,
0xD8, 0x5B, 0xC6, 0xB4, 0x5A, 0xB8, 0xB8, 0x4C, 0x54, 0xDD,
0x80, 0xB2, 0x82, 0x59, 0x1F, 0x55, 0x07, 0xED, 0x9B, 0x3F,
0xB1, 0xCD, 0xEE, 0xFD, 0x58, 0xAD, 0x5A, 0x98, 0x12, 0xED,
0x92, 0x9C, 0x77, 0x9B, 0x0F, 0x54, 0xBA, 0xDF, 0x2C, 0xAF,
0xBA, 0xCF, 0xAC, 0xB3, 0xEC, 0xAC, 0xC1, 0x27, 0xC7, 0x64,
0x0C, 0xBB, 0x67, 0x15, 0x4F, 0x54, 0x5A, 0x62, 0x2B, 0xE0,
0xA9, 0xB5, 0x52, 0xA2, 0x42, 0x08, 0x31, 0x3B, 0xFA, 0x49,
0x1F, 0x53, 0xAA, 0xA3, 0x07, 0x4B, 0xDC, 0x48, 0xBC, 0x5B,
0xDB, 0x3F, 0xF0, 0xE2, 0xD0, 0x5B, 0xB4, 0x77, 0xB5, 0x9F,
0x87, 0xE3, 0xA1, 0xEA, 0xB3, 0xE6
};
uint8_t result2[] = {
0xF9, 0x3C, 0xA6, 0x85, 0x55, 0x90, 0xA7, 0x7F, 0x07, 0x35,
0x40, 0x97, 0xE9, 0x0E, 0x02, 0x66, 0x48, 0xB6, 0x11, 0x5D,
0xF0, 0x08, 0xFF, 0xED, 0xBD, 0x9D, 0x98, 0x11, 0xF5, 0x4E,
0x82, 0x86, 0xEF, 0x00, 0xFD, 0xD6, 0xBA, 0x1E, 0x58, 0xDF,
0x25, 0x35, 0xE3, 0xFB, 0xDD, 0x9A, 0x9B, 0xA3, 0x75, 0x4A,
0x97, 0xF3, 0x6E, 0xE8, 0x33, 0x22, 0x15, 0x82, 0x06, 0x0A,
0x1F, 0x37, 0xFC, 0xE4, 0xEE, 0x88, 0x26, 0x63, 0x6B, 0x28,
0xEA, 0xD5, 0x89, 0x59, 0x3F, 0x4C, 0xA8, 0xB6, 0x47, 0x38,
0x8F, 0x24, 0xEB, 0x3F, 0x0A, 0x34, 0x79, 0x69, 0x68, 0xD2,
0x1B, 0xDE, 0xE6, 0xF8, 0x1F, 0xD5, 0xDF, 0x93, 0x53, 0x6F,
0x93, 0x59, 0x37, 0xB8, 0x02, 0x5E, 0xC8, 0xCB, 0xF5, 0x7D,
0xDB, 0x0C, 0x61, 0xF2, 0xE4, 0x14, 0x63, 0xCC, 0x15, 0x16,
0xD6, 0x57, 0xDA, 0x28, 0x29, 0xC6, 0xBF, 0x90, 0x48, 0x17,
0x61, 0x8F, 0x48, 0xC6, 0x0F, 0xB1, 0xCE, 0x5B, 0xFB, 0xDA,
0x0C, 0xAF, 0x45, 0x91, 0x88, 0x2A, 0x31, 0xF6, 0xEE, 0x3F,
0xE0, 0xF7, 0x87, 0x79, 0x99, 0x2A, 0x06, 0xEC, 0x60, 0xF3,
0x7F, 0xB9, 0xA8, 0xD6, 0x10, 0x8C, 0x23, 0x1F, 0x0A, 0x92,
0x77, 0x54, 0xB0, 0x59, 0x9F, 0xA4, 0xFA, 0x27, 0xA4, 0xE2,
0x5E, 0x06, 0x5E, 0xF0, 0x30, 0x85, 0xB8, 0x92, 0x97, 0x9D,
0xC0, 0xE7, 0xA1, 0x08, 0x08, 0x83, 0xCA, 0xEB, 0xFD, 0xFD,
0x36, 0x65, 0xA8, 0xF2, 0xD0, 0x61, 0xC5, 0x21, 0xF7, 0xD6,
0xE3, 0xDA, 0x2A, 0xF8, 0xB9, 0x7B, 0x6B, 0x43, 0xB6, 0xEC,
0x83, 0x1A, 0xF5, 0x15, 0x07, 0x0A, 0x83, 0xBB, 0xB9, 0xAC,
0x95, 0xED, 0x4E, 0xF4, 0x9B, 0x75, 0x6A, 0x23, 0x77, 0xA5,
0xF0, 0x83, 0x3D, 0x84, 0x7E, 0x27, 0xA8, 0x8D, 0xDB, 0x0C,
0x2C, 0xE4, 0xAD, 0x78, 0x2E, 0x7B
};
#elif MD_MAP == BLAKE2S_160
#define FUNCTION "blake2s-160"
uint8_t seed1[60];
uint8_t result1[] = {
0x3B, 0xFB, 0x98, 0xB1, 0x75, 0x4A, 0x85, 0x1D, 0x82, 0x51,
0x09, 0xE7, 0xA9, 0x7B, 0x45, 0x25, 0x3F, 0x82, 0xEC, 0xBB,
0x8A, 0xF6, 0x7A, 0x15, 0x6B, 0x8D, 0x8A, 0xE7, 0x1E, 0xD9,
0x17, 0xED, 0x24, 0x35, 0x00, 0x87, 0x7B, 0xE6, 0xBD, 0xEF,
0xF5, 0xD7, 0xD0, 0x6C, 0x57, 0x08, 0xF6, 0x62, 0x43, 0x51,
0xD6, 0x9C, 0x6A, 0x7A, 0xF1, 0xC9, 0xB3, 0xF6, 0xD9, 0x5B,
0x94, 0x3C, 0xBB, 0x1A, 0xF4, 0x3C, 0xD8, 0xB4, 0x2A, 0xA3,
0xE8, 0x7C, 0x62, 0x40, 0xD1, 0xBD, 0x5D, 0x6B, 0x8C, 0xF0
};
uint8_t result2[] = {
0xAD, 0xF3, 0x6B, 0x2A, 0x4A, 0xAA, 0x78, 0xEC, 0x4B, 0xE7,
0x50, 0xEA, 0x91, 0x08, 0xD7, 0xBC, 0x9A, 0x7B, 0x52, 0x0A,
0x46, 0x0D, 0xA5, 0xD9, 0x12, 0xCC, 0xF8, 0x3C, 0x51, 0x48,
0xFD, 0xD3, 0x45, 0x9E, 0xC5, 0x84, 0xF1, 0x29, 0xFD, 0x0C,
0x03, 0x28, 0xD1, 0xEF, 0x0B, 0xBE, 0x73, 0x8B, 0xD4, 0x77,
0xA2, 0x48, 0x05, 0xDE, 0xA3, 0xFD, 0xB2, 0x75, 0xF2, 0x9F,
0xE8, 0xCA, 0xEF, 0xDB, 0x5D, 0x4F, 0xBF, 0xB6, 0x27, 0x93,
0x98, 0x7B, 0x11, 0x8D, 0x9F, 0x97, 0xA1, 0x4E, 0x67, 0x82
};
#elif MD_MAP == BLAKE2S_256
uint8_t seed1[63];
#define FUNCTION "blake2s-256"
uint8_t result1[] = {
0xD5, 0x26, 0xBD, 0x3B, 0x1A, 0x08, 0x91, 0x25, 0xB1, 0x2D,
0xFF, 0x63, 0x57, 0x33, 0x85, 0x11, 0x7A, 0x1E, 0xF3, 0x7E,
0xE0, 0xAE, 0xCE, 0x77, 0xAC, 0x19, 0x8B, 0x92, 0x7A, 0xDE,
0x79, 0x23, 0x0E, 0xA9, 0x25, 0xF3, 0x33, 0xB4, 0x17, 0xC7,
0xF7, 0x0A, 0xEB, 0x25, 0x0C, 0x9B, 0xAF, 0x38, 0xD0, 0x5C,
0xCE, 0xC6, 0xB5, 0x63, 0x70, 0x15, 0xD7, 0x36, 0x4A, 0x99,
0x25, 0xE9, 0xE1, 0x76, 0x75, 0xE0, 0x1C, 0x8E, 0x1E, 0x0B,
0xC1, 0xE2, 0x8F, 0xB7, 0xCA, 0x56, 0x69, 0xB7, 0xAB, 0x5B,
0x45, 0x6F, 0x5B, 0xA4, 0xF3, 0xAA, 0x54, 0x30, 0x3B, 0x44,
0xFF, 0x35, 0xBF, 0xBB, 0xD8, 0xA3, 0xEA, 0xFA, 0x32, 0x8F,
0xD0, 0x68, 0x76, 0x5B, 0x47, 0x9E, 0x61, 0x73, 0xEB, 0xF8,
0x84, 0x1D, 0xF5, 0xA7, 0xEF, 0x91, 0x47, 0x19, 0x30, 0x12,
0xF6, 0x7C, 0x04, 0x7A, 0x4F, 0x4F, 0x07, 0xA0
};
uint8_t result2[] = {
0xAB, 0x61, 0x58, 0xF2, 0x82, 0x88, 0xAA, 0x0A, 0xD1, 0xA3,
0x98, 0xAD, 0x73, 0xD5, 0xD5, 0x1D, 0x6E, 0xDE, 0xA4, 0x24,
0xA7, 0x76, 0x3D, 0x77, 0xD5, 0x33, 0xB8, 0x1B, 0xE7, 0x43,
0x32, 0x0A, 0xB6, 0x44, 0x4D, 0x47, 0x54, 0x68, 0x69, 0x1B,
0xA7, 0x5E, 0xA4, 0x90, 0x1D, 0x21, 0xBA, 0x3B, 0xC3, 0x7B,
0x60, 0x3A, 0xDB, 0xD5, 0xDC, 0xCB, 0x8B, 0x6E, 0xB6, 0x6A,
0xA0, 0xA7, 0x5B, 0xBB, 0x40, 0xC4, 0x7E, 0xB9, 0xD0, 0xC9,
0xDB, 0xFF, 0xAC, 0x19, 0xFA, 0xB2, 0x71, 0x41, 0xAB, 0x0A,
0x41, 0xEB, 0x9C, 0xD1, 0x42, 0x08, 0x97, 0xAF, 0x17, 0x87,
0x45, 0x7A, 0x2C, 0x7D, 0x8F, 0x43, 0xB3, 0x85, 0x49, 0xFF,
0x28, 0x81, 0xE9, 0x5C, 0x85, 0x58, 0x06, 0x74, 0x11, 0x3A,
0xDC, 0x00, 0x29, 0xA0, 0x78, 0xC8, 0xA7, 0xE4, 0xEB, 0x2D,
0x9D, 0x07, 0xE1, 0x64, 0xCC, 0x0B, 0x94, 0x37
};
#endif
static int test(void) {
int i, len = 2 * MD_LEN, size = (RAND_SIZE - 1) / 2, code = STS_ERR;
uint8_t out[len], seed2[size], seed3[size];
for (i = 0; i < (RAND_SIZE - 1) / 2; i++) {
seed1[i] = i;
seed2[i] = 0x80 + i;
seed3[i] = 0xC0 + i;
}
for (; i < sizeof(seed1); i++) {
seed1[i] = 0x20 + (i - (RAND_SIZE - 1) / 2);
}
TEST_ONCE("hash-dbrg (" FUNCTION ") random generator is correct") {
rand_clean();
rand_seed(seed1, sizeof(seed1));
rand_bytes(out, len);
TEST_ASSERT(memcmp(out, result1, len) == 0, end);
rand_bytes(out, len);
TEST_ASSERT(memcmp(out, result1 + len, len) == 0, end);
}
TEST_END;
TEST_ONCE("hash-dbrg (" FUNCTION ") reseeding is correct") {
rand_clean();
rand_seed(seed1, sizeof(seed1));
rand_seed(seed2, sizeof(seed2));
rand_bytes(out, len);
TEST_ASSERT(memcmp(out, result2, len) == 0, end);
rand_seed(seed3, sizeof(seed3));
rand_bytes(out, len);
TEST_ASSERT(memcmp(out, result2 + len, len) == 0, end);
}
TEST_END;
code = STS_OK;
end:
return code;
}
#elif RAND == FIPS
/*
* Test vectors taken from:
* - http://csrc.nist.gov/encryption/dss/Examples-1024bit.pdf
* - http://www.ietf.org/rfc/rfc4186.txt
*/
uint8_t test1[20] = {
0xBD, 0x02, 0x9B, 0xBE, 0x7F, 0x51, 0x96, 0x0B, 0xCF, 0x9E,
0xDB, 0x2B, 0x61, 0xF0, 0x6F, 0x0F, 0xEB, 0x5A, 0x38, 0xB6
};
uint8_t test2[20] = {
0xE5, 0x76, 0xD5, 0xCA, 0x33, 0x2E, 0x99, 0x30, 0x01, 0x8B,
0xF1, 0xBA, 0xEE, 0x27, 0x63, 0xC7, 0x95, 0xB3, 0xC7, 0x12
};
uint8_t result1[40] = {
0x20, 0x70, 0xb3, 0x22, 0x3D, 0xBA, 0x37, 0x2F, 0xDE, 0x1C,
0x0F, 0xFC, 0x7B, 0x2E, 0x3B, 0x49, 0x8B, 0x26, 0x06, 0x14,
0x3C, 0x6C, 0x18, 0xBA, 0xCB, 0x0F, 0x6C, 0x55, 0xBA, 0xBB,
0x13, 0x78, 0x8E, 0x20, 0xD7, 0x37, 0xA3, 0x27, 0x51, 0x16
};
uint8_t result2[160] = {
0x53, 0x6E, 0x5E, 0xBC, 0x44, 0x65, 0x58, 0x2A, 0xA6, 0xA8,
0xEC, 0x99, 0x86, 0xEB, 0xB6, 0x20, 0x25, 0xAF, 0x19, 0x42,
0xEF, 0xCB, 0xF4, 0xBC, 0x72, 0xB3, 0x94, 0x34, 0x21, 0xF2,
0xA9, 0x74, 0x39, 0xD4, 0x5A, 0xEA, 0xF4, 0xE3, 0x06, 0x01,
0x98, 0x3E, 0x97, 0x2B, 0x6C, 0xFD, 0x46, 0xD1, 0xC3, 0x63,
0x77, 0x33, 0x65, 0x69, 0x0D, 0x09, 0xCD, 0x44, 0x97, 0x6B,
0x52, 0x5F, 0x47, 0xD3, 0xA6, 0x0A, 0x98, 0x5E, 0x95, 0x5C,
0x53, 0xB0, 0x90, 0xB2, 0xE4, 0xB7, 0x37, 0x19, 0x19, 0x6A,
0x40, 0x25, 0x42, 0x96, 0x8F, 0xD1, 0x4A, 0x88, 0x8F, 0x46,
0xB9, 0xA7, 0x88, 0x6E, 0x44, 0x88, 0x59, 0x49, 0xEA, 0xB0,
0xFF, 0xF6, 0x9D, 0x52, 0x31, 0x5C, 0x6C, 0x63, 0x4F, 0xD1,
0x4A, 0x7F, 0x0D, 0x52, 0x02, 0x3D, 0x56, 0xF7, 0x96, 0x98,
0xFA, 0x65, 0x96, 0xAB, 0xEE, 0xD4, 0xF9, 0x3F, 0xBB, 0x48,
0xEB, 0x53, 0x4D, 0x98, 0x54, 0x14, 0xCE, 0xED, 0x0D, 0x9A,
0x8E, 0xD3, 0x3C, 0x38, 0x7C, 0x9D, 0xFD, 0xAB, 0x92, 0xFF,
0xBD, 0xF2, 0x40, 0xFC, 0xEC, 0xF6, 0x5A, 0x2C, 0x93, 0xB9,
};
static int test(void) {
int code = STS_ERR;
uint8_t out[160];
TEST_ONCE("fips 186-2 (cn1) random generator is correct") {
rand_seed(test1, 20);
rand_bytes(out, 40);
TEST_ASSERT(memcmp(out, result1, 40) == 0, end);
rand_seed(test2, 20);
rand_bytes(out, 160);
TEST_ASSERT(memcmp(out, result2, 160) == 0, end);
}
TEST_END;
code = STS_OK;
end:
return code;
}
#elif RAND == UDEV
static int test(void) {
uint8_t out[20], digit;
TEST_ONCE("reading from /dev/urandom is correct") {
digit = 0;
memset(out, 0, sizeof(out));
rand_bytes(out, sizeof(out));
for (int j = 0; j < sizeof(20); j++) {
digit ^= out[j];
}
TEST_ASSERT(digit != 0, end);
}
TEST_END;
end:
return STS_OK;
}
#elif RAND == RDRND
static int test(void) {
uint8_t out[64];
int len = sizeof(out) / 2, code = STS_ERR;
TEST_ONCE("rdrand hardware generator is non-trivial") {
memset(out, 0, 2 * len);
rand_bytes(out, len);
/* This fails with negligible probability. */
TEST_ASSERT(memcmp(out, out + len, len) != 0, end);
}
TEST_END;
code = STS_OK;
end:
return code;
}
#elif RAND == CALL
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
static void test_bytes(uint8_t *buf, int size, void *args) {
int c, l, fd = *(int *)args;
if (fd == -1) {
THROW(ERR_NO_FILE);
}
l = 0;
do {
c = read(fd, buf + l, size - l);
l += c;
if (c == -1) {
THROW(ERR_NO_READ);
}
} while (l < size);
}
static int test(void) {
uint8_t out[20], digit;
int fd = open("/dev/urandom", O_RDONLY);
TEST_ONCE("callback to reading /dev/urandom is correct") {
digit = 0;
memset(out, 0, sizeof(out));
rand_bytes(out, sizeof(out));
for (int j = 0; j < sizeof(20); j++) {
digit ^= out[j];
}
TEST_ASSERT(digit != 0, end);
rand_seed(&test_bytes, (void *)&fd);
rand_bytes(out, sizeof(out));
for (int j = 0; j < sizeof(20); j++) {
digit ^= out[j];
}
TEST_ASSERT(digit != 0, end);
}
TEST_END;
end:
close(fd);
return STS_OK;
}
#endif
int main(void) {
if (core_init() != STS_OK) {
core_clean();
return 1;
}
util_banner("Tests for the RAND module:\n", 0);
if (test() != STS_OK) {
core_clean();
return 1;
}
util_banner("All tests have passed.\n", 0);
core_clean();
return 0;
}
| lgpl-2.1 |
kctan0805/vdpm | share/gdal/gdal-2.0.0/ogr/ogrsf_frmts/oci/ogrociwritablelayer.cpp | 5 | 20097 | /******************************************************************************
* $Id: ogrociwritablelayer.cpp 28481 2015-02-13 17:11:15Z rouault $
*
* Project: Oracle Spatial Driver
* Purpose: Implementation of the OGROCIWritableLayer class. This provides
* some services for converting OGRGeometries into Oracle structures
* that is shared between OGROCITableLayer and OGROCILoaderLayer.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com>
*
* 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 "ogr_oci.h"
#include "cpl_conv.h"
#include "cpl_string.h"
CPL_CVSID("$Id: ogrociwritablelayer.cpp 28481 2015-02-13 17:11:15Z rouault $");
/************************************************************************/
/* OGROCIWritableLayer() */
/************************************************************************/
OGROCIWritableLayer::OGROCIWritableLayer()
{
nDimension = MAX(2,MIN(3,atoi(CPLGetConfigOption("OCI_DEFAULT_DIM","3"))));
nSRID = -1;
nOrdinalCount = 0;
nOrdinalMax = 0;
padfOrdinals = NULL;
nElemInfoCount = 0;
nElemInfoMax = 0;
panElemInfo = NULL;
bLaunderColumnNames = TRUE;
bTruncationReported = FALSE;
nSRID = -1;
poSRS = NULL;
papszOptions = NULL;
}
/************************************************************************/
/* ~OGROCIWritableLayer() */
/************************************************************************/
OGROCIWritableLayer::~OGROCIWritableLayer()
{
CPLFree( padfOrdinals );
CPLFree( panElemInfo );
CSLDestroy( papszOptions );
}
/************************************************************************/
/* PushOrdinal() */
/************************************************************************/
void OGROCIWritableLayer::PushOrdinal( double dfOrd )
{
if( nOrdinalCount == nOrdinalMax )
{
nOrdinalMax = nOrdinalMax * 2 + 100;
padfOrdinals = (double *) CPLRealloc(padfOrdinals,
sizeof(double) * nOrdinalMax);
}
padfOrdinals[nOrdinalCount++] = dfOrd;
}
/************************************************************************/
/* PushElemInfo() */
/************************************************************************/
void OGROCIWritableLayer::PushElemInfo( int nOffset, int nEType, int nInterp )
{
if( nElemInfoCount+3 >= nElemInfoMax )
{
nElemInfoMax = nElemInfoMax * 2 + 100;
panElemInfo = (int *) CPLRealloc(panElemInfo,sizeof(int)*nElemInfoMax);
}
panElemInfo[nElemInfoCount++] = nOffset;
panElemInfo[nElemInfoCount++] = nEType;
panElemInfo[nElemInfoCount++] = nInterp;
}
/************************************************************************/
/* TranslateElementGroup() */
/* */
/* Append one or more element groups to the existing element */
/* info and ordinates lists for the passed geometry. */
/************************************************************************/
OGRErr
OGROCIWritableLayer::TranslateElementGroup( OGRGeometry *poGeometry )
{
switch( wkbFlatten(poGeometry->getGeometryType()) )
{
case wkbPoint:
{
OGRPoint *poPoint = (OGRPoint *) poGeometry;
PushElemInfo( nOrdinalCount+1, 1, 1 );
PushOrdinal( poPoint->getX() );
PushOrdinal( poPoint->getY() );
if( nDimension == 3 )
PushOrdinal( poPoint->getZ() );
return OGRERR_NONE;
}
case wkbLineString:
{
OGRLineString *poLine = (OGRLineString *) poGeometry;
int iVert;
PushElemInfo( nOrdinalCount+1, 2, 1 );
for( iVert = 0; iVert < poLine->getNumPoints(); iVert++ )
{
PushOrdinal( poLine->getX(iVert) );
PushOrdinal( poLine->getY(iVert) );
if( nDimension == 3 )
PushOrdinal( poLine->getZ(iVert) );
}
return OGRERR_NONE;
}
case wkbPolygon:
{
OGRPolygon *poPoly = (OGRPolygon *) poGeometry;
int iRing;
for( iRing = -1; iRing < poPoly->getNumInteriorRings(); iRing++ )
{
OGRLinearRing *poRing;
int iVert;
if( iRing == -1 )
poRing = poPoly->getExteriorRing();
else
poRing = poPoly->getInteriorRing(iRing);
if( iRing == -1 )
PushElemInfo( nOrdinalCount+1, 1003, 1 );
else
PushElemInfo( nOrdinalCount+1, 2003, 1 );
if( (iRing == -1 && poRing->isClockwise())
|| (iRing != -1 && !poRing->isClockwise()) )
{
for( iVert = poRing->getNumPoints()-1; iVert >= 0; iVert-- )
{
PushOrdinal( poRing->getX(iVert) );
PushOrdinal( poRing->getY(iVert) );
if( nDimension == 3 )
PushOrdinal( poRing->getZ(iVert) );
}
}
else
{
for( iVert = 0; iVert < poRing->getNumPoints(); iVert++ )
{
PushOrdinal( poRing->getX(iVert) );
PushOrdinal( poRing->getY(iVert) );
if( nDimension == 3 )
PushOrdinal( poRing->getZ(iVert) );
}
}
}
return OGRERR_NONE;
}
default:
{
return OGRERR_FAILURE;
}
}
}
/************************************************************************/
/* ReportTruncation() */
/************************************************************************/
void OGROCIWritableLayer::ReportTruncation( OGRFieldDefn * psFldDefn )
{
if( bTruncationReported )
return;
CPLError( CE_Warning, CPLE_AppDefined,
"The value for the field %s is being truncated to fit the\n"
"declared width/precision of the field. No more truncations\n"
"for table %s will be reported.",
psFldDefn->GetNameRef(), poFeatureDefn->GetName() );
bTruncationReported = TRUE;
}
/************************************************************************/
/* SetOptions() */
/* */
/* Set layer creation or other options. */
/************************************************************************/
void OGROCIWritableLayer::SetOptions( char **papszOptionsIn )
{
CSLDestroy( papszOptions );
papszOptions = CSLDuplicate( papszOptionsIn );
}
/************************************************************************/
/* CreateField() */
/************************************************************************/
OGRErr OGROCIWritableLayer::CreateField( OGRFieldDefn *poFieldIn, int bApproxOK )
{
OGROCISession *poSession = poDS->GetSession();
char szFieldType[256];
char szFieldName[30]; // specify at most 30 characters, see ORA-00972
OGRFieldDefn oField( poFieldIn );
/* -------------------------------------------------------------------- */
/* Do we want to "launder" the column names into Oracle */
/* friendly format? */
/* -------------------------------------------------------------------- */
if( bLaunderColumnNames )
{
char *pszSafeName = CPLStrdup( oField.GetNameRef() );
poSession->CleanName( pszSafeName );
oField.SetName( pszSafeName );
CPLFree( pszSafeName );
}
/* -------------------------------------------------------------------- */
/* Work out the Oracle type. */
/* -------------------------------------------------------------------- */
if( oField.GetType() == OFTInteger )
{
if( bPreservePrecision && oField.GetWidth() != 0 )
sprintf( szFieldType, "NUMBER(%d)", oField.GetWidth() );
else
strcpy( szFieldType, "INTEGER" );
}
else if( oField.GetType() == OFTInteger64 )
{
if( bPreservePrecision && oField.GetWidth() != 0 )
sprintf( szFieldType, "NUMBER(%d)", oField.GetWidth() );
else
strcpy( szFieldType, "NUMBER(20)" );
}
else if( oField.GetType() == OFTReal )
{
if( bPreservePrecision && oField.GetWidth() != 0 )
sprintf( szFieldType, "NUMBER(%d,%d)",
oField.GetWidth(), oField.GetPrecision() );
else
strcpy( szFieldType, "FLOAT(126)" );
}
else if( oField.GetType() == OFTString )
{
if( oField.GetWidth() == 0 || !bPreservePrecision )
strcpy( szFieldType, "VARCHAR2(2047)" );
else
sprintf( szFieldType, "VARCHAR2(%d)", oField.GetWidth() );
}
else if ( oField.GetType() == OFTDate )
{
sprintf( szFieldType, "DATE" );
}
else if ( oField.GetType() == OFTDateTime )
{
sprintf( szFieldType, "TIMESTAMP" );
}
else if( bApproxOK )
{
oField.SetDefault(NULL);
CPLError( CE_Warning, CPLE_NotSupported,
"Can't create field %s with type %s on Oracle layers. Creating as VARCHAR.",
oField.GetNameRef(),
OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
strcpy( szFieldType, "VARCHAR2(2047)" );
}
else
{
CPLError( CE_Failure, CPLE_NotSupported,
"Can't create field %s with type %s on Oracle layers.",
oField.GetNameRef(),
OGRFieldDefn::GetFieldTypeName(oField.GetType()) );
return OGRERR_FAILURE;
}
/* -------------------------------------------------------------------- */
/* Create the new field. */
/* -------------------------------------------------------------------- */
OGROCIStringBuf oCommand;
OGROCIStatement oAddField( poSession );
oCommand.MakeRoomFor( 70 + strlen(poFeatureDefn->GetName())
+ strlen(oField.GetNameRef())
+ strlen(szFieldType)
+ (oField.GetDefault() ? strlen(oField.GetDefault()) : 0) );
snprintf( szFieldName, sizeof( szFieldName ), "%s", oField.GetNameRef());
szFieldName[sizeof( szFieldName )-1] = '\0';
if ( strlen(oField.GetNameRef()) > sizeof ( szFieldName ) )
{
szFieldName[sizeof( szFieldName ) - 1] = '_';
CPLError( CE_Warning, CPLE_AppDefined,
"Column %s is too long (at most 30 characters). Using %s.",
oField.GetNameRef(), szFieldName );
oField.SetName(szFieldName);
}
sprintf( oCommand.GetString(), "ALTER TABLE %s ADD \"%s\" %s",
poFeatureDefn->GetName(), szFieldName, szFieldType);
if( oField.GetDefault() != NULL && !oField.IsDefaultDriverSpecific() )
{
sprintf( oCommand.GetString() + strlen(oCommand.GetString()),
" DEFAULT %s", oField.GetDefault() );
}
if( !oField.IsNullable() )
strcat( oCommand.GetString(), " NOT NULL");
if( oAddField.Execute( oCommand.GetString() ) != CE_None )
return OGRERR_FAILURE;
poFeatureDefn->AddFieldDefn( &oField );
return OGRERR_NONE;
}
/************************************************************************/
/* SetDimension() */
/************************************************************************/
void OGROCIWritableLayer::SetDimension( int nNewDim )
{
nDimension = nNewDim;
}
/************************************************************************/
/* ParseDIMINFO() */
/************************************************************************/
void OGROCIWritableLayer::ParseDIMINFO( const char *pszOptionName,
double *pdfMin,
double *pdfMax,
double *pdfRes )
{
const char *pszUserDIMINFO;
char **papszTokens;
pszUserDIMINFO = CSLFetchNameValue( papszOptions, pszOptionName );
if( pszUserDIMINFO == NULL )
return;
papszTokens =
CSLTokenizeStringComplex( pszUserDIMINFO, ",", FALSE, FALSE );
if( CSLCount(papszTokens) != 3 )
{
CSLDestroy( papszTokens );
CPLError( CE_Warning, CPLE_AppDefined,
"Ignoring %s, it does not contain three comma separated values.",
pszOptionName );
return;
}
*pdfMin = CPLAtof(papszTokens[0]);
*pdfMax = CPLAtof(papszTokens[1]);
*pdfRes = CPLAtof(papszTokens[2]);
CSLDestroy( papszTokens );
}
/************************************************************************/
/* TranslateToSDOGeometry() */
/************************************************************************/
OGRErr OGROCIWritableLayer::TranslateToSDOGeometry( OGRGeometry * poGeometry,
int *pnGType )
{
nOrdinalCount = 0;
nElemInfoCount = 0;
if( poGeometry == NULL )
return OGRERR_FAILURE;
/* ==================================================================== */
/* Handle a point geometry. */
/* ==================================================================== */
if( wkbFlatten(poGeometry->getGeometryType()) == wkbPoint )
{
#ifdef notdef
char szResult[1024];
OGRPoint *poPoint = (OGRPoint *) poGeometry;
if( nDimension == 2 )
CPLsprintf( szResult,
"%s(%d,%s,MDSYS.SDO_POINT_TYPE(%.16g,%.16g,0.0),NULL,NULL)",
SDO_GEOMETRY, 2001, szSRID,
poPoint->getX(), poPoint->getY() );
else
CPLsprintf( szResult,
"%s(%d,%s,MDSYS.SDO_POINT_TYPE(%.16g,%.16g,%.16g),NULL,NULL)",
SDO_GEOMETRY, 3001, szSRID,
poPoint->getX(), poPoint->getY(), poPoint->getZ() );
return CPLStrdup(szResult );
#endif
}
/* ==================================================================== */
/* Handle a line string geometry. */
/* ==================================================================== */
else if( wkbFlatten(poGeometry->getGeometryType()) == wkbLineString )
{
*pnGType = nDimension * 1000 + 2;
TranslateElementGroup( poGeometry );
return OGRERR_NONE;
}
/* ==================================================================== */
/* Handle a polygon geometry. */
/* ==================================================================== */
else if( wkbFlatten(poGeometry->getGeometryType()) == wkbPolygon )
{
*pnGType = nDimension == 2 ? 2003 : 3003;
TranslateElementGroup( poGeometry );
return OGRERR_NONE;
}
/* ==================================================================== */
/* Handle a multi point geometry. */
/* ==================================================================== */
else if( wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPoint )
{
OGRMultiPoint *poMP = (OGRMultiPoint *) poGeometry;
int iVert;
*pnGType = nDimension*1000 + 5;
PushElemInfo( 1, 1, poMP->getNumGeometries() );
for( iVert = 0; iVert < poMP->getNumGeometries(); iVert++ )
{
OGRPoint *poPoint = (OGRPoint *)poMP->getGeometryRef( iVert );
PushOrdinal( poPoint->getX() );
PushOrdinal( poPoint->getY() );
if( nDimension == 3 )
PushOrdinal( poPoint->getZ() );
}
return OGRERR_NONE;
}
/* ==================================================================== */
/* Handle other geometry collections. */
/* ==================================================================== */
else
{
/* -------------------------------------------------------------------- */
/* Identify the GType. */
/* -------------------------------------------------------------------- */
if( wkbFlatten(poGeometry->getGeometryType()) == wkbMultiLineString )
*pnGType = nDimension * 1000 + 6;
else if( wkbFlatten(poGeometry->getGeometryType()) == wkbMultiPolygon )
*pnGType = nDimension * 1000 + 7;
else if( wkbFlatten(poGeometry->getGeometryType())
== wkbGeometryCollection )
*pnGType = nDimension * 1000 + 4;
else
{
CPLError( CE_Failure, CPLE_AppDefined,
"Unexpected geometry type (%d/%s) in "
"OGROCIWritableLayer::TranslateToSDOGeometry()",
poGeometry->getGeometryType(),
poGeometry->getGeometryName() );
return OGRERR_FAILURE;
}
/* -------------------------------------------------------------------- */
/* Translate each child in turn. */
/* -------------------------------------------------------------------- */
OGRGeometryCollection *poGC = (OGRGeometryCollection *) poGeometry;
int iChild;
for( iChild = 0; iChild < poGC->getNumGeometries(); iChild++ )
TranslateElementGroup( poGC->getGeometryRef(iChild) );
return OGRERR_NONE;
}
return OGRERR_FAILURE;
}
int OGROCIWritableLayer::FindFieldIndex( const char *pszFieldName, int bExactMatch )
{
int iField = GetLayerDefn()->GetFieldIndex( pszFieldName );
if( !bExactMatch && iField < 0 )
{
// try laundered version
OGROCISession *poSession = poDS->GetSession();
char *pszSafeName = CPLStrdup( pszFieldName );
poSession->CleanName( pszSafeName );
iField = GetLayerDefn()->GetFieldIndex( pszSafeName );
CPLFree( pszSafeName );
}
return iField;
}
| lgpl-2.1 |
authmillenon/RIOT | sys/shell/commands/sc_netstats_nb.c | 6 | 2686 | /*
* Copyright (C) Koen Zandberg <koen@bergzand.net>
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup sys_shell_commands
* @{
*
* @file
* @brief Shell commands for displaying neighbor statistics
*
* @author Koen Zandberg <koen@bergzand.net>
* @author Benjamin Valentin <benpicco@beuth-hochschule.de>
*
* @}
*/
#include <stdio.h>
#include "net/gnrc/netif.h"
#include "net/netstats.h"
#include "net/netstats/neighbor.h"
static void _print_neighbors(netif_t *dev)
{
netstats_nb_t *stats = &dev->neighbors.pstats[0];
unsigned header_len = 0;
char l2addr_str[3 * L2UTIL_ADDR_MAX_LEN];
puts("Neighbor link layer stats:");
header_len += printf("L2 address fresh");
if (IS_USED(MODULE_NETSTATS_NEIGHBOR_ETX)) {
header_len += printf(" etx");
}
if (IS_USED(MODULE_NETSTATS_NEIGHBOR_COUNT)) {
header_len += printf(" sent received");
}
if (IS_USED(MODULE_NETSTATS_NEIGHBOR_RSSI)) {
header_len += printf(" rssi ");
}
if (IS_USED(MODULE_NETSTATS_NEIGHBOR_LQI)) {
header_len += printf(" lqi");
}
if (IS_USED(MODULE_NETSTATS_NEIGHBOR_TX_TIME)) {
header_len += printf(" avg tx time");
}
printf("\n");
while (header_len--) {
printf("-");
}
printf("\n");
for (unsigned i = 0; i < NETSTATS_NB_SIZE; ++i) {
netstats_nb_t *entry = &stats[i];
if (entry->l2_addr_len == 0) {
continue;
}
printf("%-24s ",
gnrc_netif_addr_to_str(entry->l2_addr, entry->l2_addr_len, l2addr_str));
if (netstats_nb_isfresh(dev, entry)) {
printf("%5u", (unsigned)entry->freshness);
} else {
printf("STALE");
}
#if IS_USED(MODULE_NETSTATS_NEIGHBOR_ETX)
printf(" %3u%%", (100 * entry->etx) / NETSTATS_NB_ETX_DIVISOR);
#endif
#if IS_USED(MODULE_NETSTATS_NEIGHBOR_COUNT)
printf(" %4"PRIu16" %8"PRIu16, entry->tx_count, entry->rx_count);
#endif
#if IS_USED(MODULE_NETSTATS_NEIGHBOR_RSSI)
printf(" %4i dBm", (int8_t) entry->rssi);
#endif
#if IS_USED(MODULE_NETSTATS_NEIGHBOR_LQI)
printf(" %u", entry->lqi);
#endif
#if IS_USED(MODULE_NETSTATS_NEIGHBOR_TX_TIME)
printf(" %7"PRIu32" µs", entry->time_tx_avg);
#endif
printf("\n");
}
}
int _netstats_nb(int argc, char **argv)
{
(void) argc;
(void) argv;
gnrc_netif_t *netif = NULL;
while ((netif = gnrc_netif_iter(netif))) {
_print_neighbors(&netif->netif);
}
return 0;
}
| lgpl-2.1 |
vancegroup-mirrors/open-dynamics-engine-svnmirror | ode/src/joints/piston.cpp | 8 | 23233 | /*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) 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 text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
#include <ode/odeconfig.h>
#include "config.h"
#include "piston.h"
#include "joint_internal.h"
//****************************************************************************
// Piston
//
dxJointPiston::dxJointPiston ( dxWorld *w ) :
dxJoint ( w )
{
dSetZero ( axis1, 4 );
dSetZero ( axis2, 4 );
axis1[0] = 1;
axis2[0] = 1;
dSetZero ( qrel, 4 );
dSetZero ( anchor1, 4 );
dSetZero ( anchor2, 4 );
limotP.init ( world );
limotR.init ( world );
}
dReal dJointGetPistonPosition ( dJointID j )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
if ( joint->node[0].body )
{
dVector3 q;
// get the anchor (or offset) in global coordinates
dMultiply0_331 ( q, joint->node[0].body->posr.R, joint->anchor1 );
if ( joint->node[1].body )
{
dVector3 anchor2;
// get the anchor2 in global coordinates
dMultiply0_331 ( anchor2, joint->node[1].body->posr.R, joint->anchor2 );
q[0] = ( ( joint->node[0].body->posr.pos[0] + q[0] ) -
( joint->node[1].body->posr.pos[0] + anchor2[0] ) );
q[1] = ( ( joint->node[0].body->posr.pos[1] + q[1] ) -
( joint->node[1].body->posr.pos[1] + anchor2[1] ) );
q[2] = ( ( joint->node[0].body->posr.pos[2] + q[2] ) -
( joint->node[1].body->posr.pos[2] + anchor2[2] ) );
}
else
{
// N.B. When there is no body 2 the joint->anchor2 is already in
// global coordinates
q[0] = ( ( joint->node[0].body->posr.pos[0] + q[0] ) -
( joint->anchor2[0] ) );
q[1] = ( ( joint->node[0].body->posr.pos[1] + q[1] ) -
( joint->anchor2[1] ) );
q[2] = ( ( joint->node[0].body->posr.pos[2] + q[2] ) -
( joint->anchor2[2] ) );
if ( joint->flags & dJOINT_REVERSE )
{
q[0] = -q[0];
q[1] = -q[1];
q[2] = -q[2];
}
}
// get axis in global coordinates
dVector3 ax;
dMultiply0_331 ( ax, joint->node[0].body->posr.R, joint->axis1 );
return dCalcVectorDot3 ( ax, q );
}
dDEBUGMSG ( "The function always return 0 since no body are attached" );
return 0;
}
dReal dJointGetPistonPositionRate ( dJointID j )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
// get axis in global coordinates
dVector3 ax;
dMultiply0_331 ( ax, joint->node[0].body->posr.R, joint->axis1 );
// The linear velocity created by the rotation can be discarded since
// the rotation is along the prismatic axis and this rotation don't create
// linear velocity in the direction of the prismatic axis.
if ( joint->node[1].body )
{
return ( dCalcVectorDot3 ( ax, joint->node[0].body->lvel ) -
dCalcVectorDot3 ( ax, joint->node[1].body->lvel ) );
}
else
{
dReal rate = dCalcVectorDot3 ( ax, joint->node[0].body->lvel );
return ( (joint->flags & dJOINT_REVERSE) ? -rate : rate);
}
}
dReal dJointGetPistonAngle ( dJointID j )
{
dxJointPiston* joint = ( dxJointPiston * ) j;
dAASSERT ( joint );
checktype ( joint, Piston );
if ( joint->node[0].body )
{
dReal ang = getHingeAngle ( joint->node[0].body, joint->node[1].body, joint->axis1,
joint->qrel );
if ( joint->flags & dJOINT_REVERSE )
return -ang;
else
return ang;
}
else return 0;
}
dReal dJointGetPistonAngleRate ( dJointID j )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dAASSERT ( joint );
checktype ( joint, Piston );
if ( joint->node[0].body )
{
dVector3 axis;
dMultiply0_331 ( axis, joint->node[0].body->posr.R, joint->axis1 );
dReal rate = dCalcVectorDot3 ( axis, joint->node[0].body->avel );
if ( joint->node[1].body ) rate -= dCalcVectorDot3 ( axis, joint->node[1].body->avel );
if ( joint->flags & dJOINT_REVERSE ) rate = - rate;
return rate;
}
else return 0;
}
void
dxJointPiston::getSureMaxInfo( SureMaxInfo* info )
{
info->max_m = 6;
}
void
dxJointPiston::getInfo1 ( dxJoint::Info1 *info )
{
info->nub = 4; // Number of unbound variables
// The only bound variable is one linear displacement
info->m = 4; // Default number of constraint row
// see if we're at a joint limit.
limotP.limit = 0;
if ( ( limotP.lostop > -dInfinity || limotP.histop < dInfinity ) &&
limotP.lostop <= limotP.histop )
{
// measure joint position
dReal pos = dJointGetPistonPosition ( this );
limotP.testRotationalLimit ( pos ); // N.B. The fucntion is ill named
}
// powered Piston or at limits needs an extra constraint row
if ( limotP.limit || limotP.fmax > 0 ) info->m++;
// see if we're at a joint limit.
limotR.limit = 0;
if ( ( limotR.lostop > -dInfinity || limotR.histop < dInfinity ) &&
limotR.lostop <= limotR.histop )
{
// measure joint position
dReal angle = getHingeAngle ( node[0].body, node[1].body, axis1,
qrel );
limotR.testRotationalLimit ( angle );
}
// powered Piston or at limits needs an extra constraint row
if ( limotR.limit || limotR.fmax > 0 ) info->m++;
}
void
dxJointPiston::getInfo2 ( dReal worldFPS, dReal worldERP, const Info2Descr *info )
{
const int s0 = 0;
const int s1 = info->rowskip;
const int s2 = 2 * s1, s3 = 3 * s1 /*, s4=4*s1*/;
const dReal k = worldFPS * worldERP;
// Pull out pos and R for both bodies. also get the `connection'
// vector pos2-pos1.
dReal *pos1, *pos2, *R1, *R2=0;
dVector3 dist; // Current position of body_1 w.r.t "anchor"
// 2 bodies anchor is center of body 2
// 1 bodies anchor is origin
dVector3 lanchor2=
{
0,0,0
};
pos1 = node[0].body->posr.pos;
R1 = node[0].body->posr.R;
if ( node[1].body )
{
pos2 = node[1].body->posr.pos;
R2 = node[1].body->posr.R;
dMultiply0_331 ( lanchor2, R2, anchor2 );
dist[0] = lanchor2[0] + pos2[0] - pos1[0];
dist[1] = lanchor2[1] + pos2[1] - pos1[1];
dist[2] = lanchor2[2] + pos2[2] - pos1[2];
}
else
{
// pos2 = 0; // N.B. We can do that to be safe but it is no necessary
// R2 = 0; // N.B. We can do that to be safe but it is no necessary
if (flags & dJOINT_REVERSE )
{
dist[0] = pos1[0] - anchor2[0]; // Invert the value
dist[1] = pos1[1] - anchor2[1];
dist[2] = pos1[2] - anchor2[2];
}
else
{
dist[0] = anchor2[0] - pos1[0];
dist[1] = anchor2[1] - pos1[1];
dist[2] = anchor2[2] - pos1[2];
}
}
// ======================================================================
// Work on the angular part (i.e. row 0, 1)
// Set the two orientation rows. The rotoide axis should be the only
// unconstrained rotational axis, the angular velocity of the two bodies
// perpendicular to the rotoide axis should be equal.
// Thus the constraint equations are:
// p*w1 - p*w2 = 0
// q*w1 - q*w2 = 0
// where p and q are unit vectors normal to the rotoide axis, and w1 and w2
// are the angular velocity vectors of the two bodies.
// Since the rotoide axis is the same as the prismatic axis.
//
//
// Also, compute the right hand side (RHS) of the rotation constraint equation set.
// The first 2 element will result in the relative angular velocity of the two
// bodies along axis p and q. This is set to bring the rotoide back into alignment.
// if `theta' is the angle between ax1 and ax2, we need an angular velocity
// along u to cover angle erp*theta in one step :
// |angular_velocity| = angle/time = erp*theta / stepsize
// = (erp*fps) * theta
// angular_velocity = |angular_velocity| * u
// = (erp*fps) * theta * u
// where rotation along unit length axis u by theta brings body 2's frame
//
// if theta is smallish, sin(theta) ~= theta and cos(theta) ~= 1
// where the quaternion of the relative rotation between the two bodies is
// quat = [cos(theta/2) sin(theta/2)*u]
// quat = [1 theta/2*u]
// => q[0] ~= 1
// 2 * q[1+i] = theta * u[i]
//
// Since there is no constraint along the rotoide axis
// only along p and q that we want the same angular velocity and need to reduce
// the error
dVector3 ax1, p, q;
dMultiply0_331 ( ax1, node[0].body->posr.R, axis1 );
// Find the 2 axis perpendicular to the rotoide axis.
dPlaneSpace ( ax1, p, q );
// LHS
dCopyVector3 ( ( info->J1a ) + s0, p );
dCopyVector3 ( ( info->J1a ) + s1, q );
dVector3 b;
if ( node[1].body )
{
// LHS
// info->J2a[s0+i] = -p[i]
dCopyNegatedVector3 ( ( info->J2a ) + s0, p );
dCopyNegatedVector3 ( ( info->J2a ) + s1, q );
// Some math for the RHS
dVector3 ax2;
dMultiply0_331 ( ax2, R2, axis2 );
dCalcVectorCross3( b, ax1, ax2 );
}
else
{
// Some math for the RHS
dCalcVectorCross3( b, ax1, axis2 );
}
// RHS
info->c[0] = k * dCalcVectorDot3 ( p, b );
info->c[1] = k * dCalcVectorDot3 ( q, b );
// ======================================================================
// Work on the linear part (i.e row 2,3)
// p2 + R2 anchor2' = p1 + R1 dist'
// v2 + w2 R2 anchor2' + R2 d(anchor2')/dt = v1 + w1 R1 dist' + R1 d(dist')/dt
// v2 + w2 x anchor2 = v1 + w1 x dist + v_p
// v_p is speed of prismatic joint (i.e. elongation rate)
// Since the constraints are perpendicular to v_p we have:
// p . v_p = 0 and q . v_p = 0
// Along p and q we have (since sliding along the prismatic axis is disregarded):
// u . ( v2 + w2 x anchor2 = v1 + w1 x dist + v_p) ( where u is p or q )
// Simplify
// u . v2 + u. w2 x anchor2 = u . v1 + u . w1 x dist
// or
// u . v1 - u . v2 + u . w1 x dist - u2 . w2 x anchor2 = 0
// using the fact that (a x b = - b x a)
// u . v1 - u . v2 - u . dist x w1 + u . anchor2 x w2 = 0
// With the help of the triple product:
// i.e. a . b x c = b . c x a = c . a x b or a . b x c = a x b . c
// Ref: http://mathworld.wolfram.com/ScalarTripleProduct.html
// u . v1 - u . v2 - u x dist . w1 + u x anchor2 . w2 = 0
// u . v1 - u . v2 + dist x u . w1 - u x anchor2 . w2 = 0
//
// Coeff for 1er line of: J1l => p, J2l => -p
// Coeff for 2er line of: J1l => q, J2l => -q
// Coeff for 1er line of: J1a => dist x p, J2a => p x anchor2
// Coeff for 2er line of: J1a => dist x q, J2a => q x anchor2
dCalcVectorCross3( ( info->J1a ) + s2, dist, p );
dCalcVectorCross3( ( info->J1a ) + s3, dist, q );
dCopyVector3 ( ( info->J1l ) + s2, p );
dCopyVector3 ( ( info->J1l ) + s3, q );
if ( node[1].body )
{
// q x anchor2 instead of anchor2 x q since we want the negative value
dCalcVectorCross3( ( info->J2a ) + s2, p, lanchor2 );
// The cross product is in reverse order since we want the negative value
dCalcVectorCross3( ( info->J2a ) + s3, q, lanchor2 );
// info->J2l[s2+i] = -p[i];
dCopyNegatedVector3 ( ( info->J2l ) + s2, p );
dCopyNegatedVector3 ( ( info->J2l ) + s3, q );
}
// We want to make correction for motion not in the line of the axis
// We calculate the displacement w.r.t. the "anchor" pt.
// i.e. Find the difference between the current position and the initial
// position along the constrained axies (i.e. axis p and q).
// The bodies can move w.r.t each other only along the prismatic axis
//
// Compute the RHS of rows 2 and 3
dVector3 err;
dMultiply0_331 ( err, R1, anchor1 );
dSubtractVectors3( err, dist, err );
info->c[2] = k * dCalcVectorDot3 ( p, err );
info->c[3] = k * dCalcVectorDot3 ( q, err );
int row = 4;
if ( node[1].body )
{
row += limotP.addLimot ( this, worldFPS, info, 4, ax1, 0 );
}
else if (flags & dJOINT_REVERSE )
{
dVector3 rAx1;
rAx1[0] = -ax1[0];
rAx1[1] = -ax1[1];
rAx1[2] = -ax1[2];
row += limotP.addLimot ( this, worldFPS, info, 4, rAx1, 0 );
}
else
row += limotP.addLimot ( this, worldFPS, info, 4, ax1, 0 );
limotR.addLimot ( this, worldFPS, info, row, ax1, 1 );
}
void dJointSetPistonAnchor ( dJointID j, dReal x, dReal y, dReal z )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
setAnchors ( joint, x, y, z, joint->anchor1, joint->anchor2 );
joint->computeInitialRelativeRotation();
}
void dJointSetPistonAnchorOffset (dJointID j, dReal x, dReal y, dReal z,
dReal dx, dReal dy, dReal dz)
{
dxJointPiston* joint = (dxJointPiston*) j;
dUASSERT (joint,"bad joint argument");
checktype ( joint, Piston );
if (joint->flags & dJOINT_REVERSE)
{
dx = -dx;
dy = -dy;
dz = -dz;
}
if (joint->node[0].body)
{
joint->node[0].body->posr.pos[0] -= dx;
joint->node[0].body->posr.pos[1] -= dy;
joint->node[0].body->posr.pos[2] -= dz;
}
setAnchors (joint,x ,y, z, joint->anchor1, joint->anchor2);
if (joint->node[0].body)
{
joint->node[0].body->posr.pos[0] += dx;
joint->node[0].body->posr.pos[1] += dy;
joint->node[0].body->posr.pos[2] += dz;
}
joint->computeInitialRelativeRotation();
}
void dJointGetPistonAnchor ( dJointID j, dVector3 result )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
dUASSERT ( result, "bad result argument" );
checktype ( joint, Piston );
if ( joint->flags & dJOINT_REVERSE )
getAnchor2 ( joint, result, joint->anchor2 );
else
getAnchor ( joint, result, joint->anchor1 );
}
void dJointGetPistonAnchor2 ( dJointID j, dVector3 result )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
dUASSERT ( result, "bad result argument" );
checktype ( joint, Piston );
if ( joint->flags & dJOINT_REVERSE )
getAnchor ( joint, result, joint->anchor1 );
else
getAnchor2 ( joint, result, joint->anchor2 );
}
void dJointSetPistonAxis ( dJointID j, dReal x, dReal y, dReal z )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
setAxes ( joint, x, y, z, joint->axis1, joint->axis2 );
joint->computeInitialRelativeRotation();
}
void dJointSetPistonAxisDelta ( dJointID j, dReal x, dReal y, dReal z,
dReal dx, dReal dy, dReal dz )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
setAxes ( joint, x, y, z, joint->axis1, joint->axis2 );
joint->computeInitialRelativeRotation();
dVector3 c = {0,0,0};
if ( joint->node[1].body )
{
c[0] = ( joint->node[0].body->posr.pos[0] -
joint->node[1].body->posr.pos[0] - dx );
c[1] = ( joint->node[0].body->posr.pos[1] -
joint->node[1].body->posr.pos[1] - dy );
c[2] = ( joint->node[0].body->posr.pos[2] -
joint->node[1].body->posr.pos[2] - dz );
}
else if ( joint->node[0].body )
{
c[0] = joint->node[0].body->posr.pos[0] - dx;
c[1] = joint->node[0].body->posr.pos[1] - dy;
c[2] = joint->node[0].body->posr.pos[2] - dz;
}
// Convert into frame of body 1
dMultiply1_331 ( joint->anchor1, joint->node[0].body->posr.R, c );
}
void dJointGetPistonAxis ( dJointID j, dVector3 result )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
dUASSERT ( result, "bad result argument" );
checktype ( joint, Piston );
getAxis ( joint, result, joint->axis1 );
}
void dJointSetPistonParam ( dJointID j, int parameter, dReal value )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
if ( ( parameter & 0xff00 ) == 0x100 )
{
joint->limotR.set ( parameter & 0xff, value );
}
else
{
joint->limotP.set ( parameter, value );
}
}
dReal dJointGetPistonParam ( dJointID j, int parameter )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
if ( ( parameter & 0xff00 ) == 0x100 )
{
return joint->limotR.get ( parameter & 0xff );
}
else
{
return joint->limotP.get ( parameter );
}
}
void dJointAddPistonForce ( dJointID j, dReal force )
{
dxJointPiston* joint = ( dxJointPiston* ) j;
dUASSERT ( joint, "bad joint argument" );
checktype ( joint, Piston );
if ( joint->flags & dJOINT_REVERSE )
force -= force;
dVector3 axis;
getAxis ( joint, axis, joint->axis1 );
// axis[i] *= force
dScaleVector3( axis, force );
if ( joint->node[0].body != 0 )
dBodyAddForce ( joint->node[0].body, axis[0], axis[1], axis[2] );
if ( joint->node[1].body != 0 )
dBodyAddForce ( joint->node[1].body, -axis[0], -axis[1], -axis[2] );
if ( joint->node[0].body != 0 && joint->node[1].body != 0 )
{
// Case where we don't need ltd since center of mass of both bodies
// pass by the anchor point '*' when travelling along the prismatic axis.
// Body_2
// Body_1 -----
// --- |-- | |
// | |---------------*-------------| | ---> prismatic axis
// --- |-- | |
// -----
// Body_2
// Case where we need ltd
// Body_1
// ---
// | |---------
// --- |
// | |--
// -----*----- ---> prismatic axis
// |-- |
// |
// |
// | -----
// | | |
// -------| |
// | |
// -----
// Body_2
//
// In real life force apply at the '*' point
// But in ODE the force are applied on the center of mass of Body_1 and Body_2
// So we have to add torques on both bodies to compensate for that when there
// is an offset between the anchor point and the center of mass of both bodies.
//
// We need to add to each body T = r x F
// Where r is the distance between the cm and '*'
dVector3 ltd; // Linear Torque Decoupling vector (a torque)
dVector3 c; // Distance of the body w.r.t the anchor
// N.B. The distance along the prismatic axis might not
// not be included in this variable since it won't add
// anything to the ltd.
// Calculate the distance of the body w.r.t the anchor
// The anchor1 of body1 can be used since:
// Real anchor = Position of body 1 + anchor + d* axis1 = anchor in world frame
// d is the position of the prismatic joint (i.e. elongation)
// Since axis1 x axis1 == 0
// We can do the following.
dMultiply0_331 ( c, joint->node[0].body->posr.R, joint->anchor1 );
dCalcVectorCross3( ltd, c, axis );
dBodyAddTorque ( joint->node[0].body, ltd[0], ltd[1], ltd[2] );
dMultiply0_331 ( c, joint->node[1].body->posr.R, joint->anchor2 );
dCalcVectorCross3( ltd, c, axis );
dBodyAddTorque ( joint->node[1].body, ltd[0], ltd[1], ltd[2] );
}
}
dJointType
dxJointPiston::type() const
{
return dJointTypePiston;
}
size_t
dxJointPiston::size() const
{
return sizeof ( *this );
}
void
dxJointPiston::setRelativeValues()
{
dVector3 vec;
dJointGetPistonAnchor(this, vec);
setAnchors( this, vec[0], vec[1], vec[2], anchor1, anchor2 );
dJointGetPistonAxis(this, vec);
setAxes( this, vec[0], vec[1], vec[2], axis1, axis2 );
computeInitialRelativeRotation();
}
void
dxJointPiston::computeInitialRelativeRotation()
{
if ( node[0].body )
{
if ( node[1].body )
{
dQMultiply1 ( qrel, node[0].body->q, node[1].body->q );
}
else
{
// set joint->qrel to the transpose of the first body q
qrel[0] = node[0].body->q[0];
for ( int i = 1; i < 4; i++ )
qrel[i] = -node[0].body->q[i];
// WARNING do we need the - in -joint->node[0].body->q[i]; or not
}
}
}
| lgpl-2.1 |
simonpf/root | interpreter/llvm/src/lib/Target/X86/X86CallLowering.cpp | 8 | 6818 | //===-- llvm/lib/Target/X86/X86CallLowering.cpp - Call lowering -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the lowering of LLVM calls to machine code calls for
/// GlobalISel.
///
//===----------------------------------------------------------------------===//
#include "X86CallLowering.h"
#include "X86CallingConv.h"
#include "X86ISelLowering.h"
#include "X86InstrInfo.h"
#include "X86TargetMachine.h"
#include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineValueType.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#include "X86GenCallingConv.inc"
#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "This shouldn't be built without GISel"
#endif
X86CallLowering::X86CallLowering(const X86TargetLowering &TLI)
: CallLowering(&TLI) {}
void X86CallLowering::splitToValueTypes(const ArgInfo &OrigArg,
SmallVectorImpl<ArgInfo> &SplitArgs,
const DataLayout &DL,
MachineRegisterInfo &MRI,
SplitArgTy PerformArgSplit) const {
const X86TargetLowering &TLI = *getTLI<X86TargetLowering>();
LLVMContext &Context = OrigArg.Ty->getContext();
EVT VT = TLI.getValueType(DL, OrigArg.Ty);
unsigned NumParts = TLI.getNumRegisters(Context, VT);
if (NumParts == 1) {
// replace the original type ( pointer -> GPR ).
SplitArgs.emplace_back(OrigArg.Reg, VT.getTypeForEVT(Context),
OrigArg.Flags, OrigArg.IsFixed);
return;
}
SmallVector<unsigned, 8> SplitRegs;
EVT PartVT = TLI.getRegisterType(Context, VT);
Type *PartTy = PartVT.getTypeForEVT(Context);
for (unsigned i = 0; i < NumParts; ++i) {
ArgInfo Info =
ArgInfo{MRI.createGenericVirtualRegister(getLLTForType(*PartTy, DL)),
PartTy, OrigArg.Flags};
SplitArgs.push_back(Info);
SplitRegs.push_back(Info.Reg);
}
PerformArgSplit(SplitRegs);
}
namespace {
struct FuncReturnHandler : public CallLowering::ValueHandler {
FuncReturnHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
MachineInstrBuilder &MIB, CCAssignFn *AssignFn)
: ValueHandler(MIRBuilder, MRI, AssignFn), MIB(MIB) {}
unsigned getStackAddress(uint64_t Size, int64_t Offset,
MachinePointerInfo &MPO) override {
llvm_unreachable("Don't know how to get a stack address yet");
}
void assignValueToReg(unsigned ValVReg, unsigned PhysReg,
CCValAssign &VA) override {
MIB.addUse(PhysReg, RegState::Implicit);
unsigned ExtReg = extendRegister(ValVReg, VA);
MIRBuilder.buildCopy(PhysReg, ExtReg);
}
void assignValueToAddress(unsigned ValVReg, unsigned Addr, uint64_t Size,
MachinePointerInfo &MPO, CCValAssign &VA) override {
llvm_unreachable("Don't know how to assign a value to an address yet");
}
MachineInstrBuilder &MIB;
};
} // End anonymous namespace.
bool X86CallLowering::lowerReturn(MachineIRBuilder &MIRBuilder,
const Value *Val, unsigned VReg) const {
assert(((Val && VReg) || (!Val && !VReg)) && "Return value without a vreg");
auto MIB = MIRBuilder.buildInstrNoInsert(X86::RET).addImm(0);
if (VReg) {
MachineFunction &MF = MIRBuilder.getMF();
MachineRegisterInfo &MRI = MF.getRegInfo();
auto &DL = MF.getDataLayout();
const Function &F = *MF.getFunction();
ArgInfo OrigArg{VReg, Val->getType()};
setArgFlags(OrigArg, AttributeList::ReturnIndex, DL, F);
SmallVector<ArgInfo, 8> SplitArgs;
splitToValueTypes(
OrigArg, SplitArgs, DL, MRI,
[&](ArrayRef<unsigned> Regs) { MIRBuilder.buildUnmerge(Regs, VReg); });
FuncReturnHandler Handler(MIRBuilder, MRI, MIB, RetCC_X86);
if (!handleAssignments(MIRBuilder, SplitArgs, Handler))
return false;
}
MIRBuilder.insertInstr(MIB);
return true;
}
namespace {
struct FormalArgHandler : public CallLowering::ValueHandler {
FormalArgHandler(MachineIRBuilder &MIRBuilder, MachineRegisterInfo &MRI,
CCAssignFn *AssignFn, const DataLayout &DL)
: ValueHandler(MIRBuilder, MRI, AssignFn), DL(DL) {}
unsigned getStackAddress(uint64_t Size, int64_t Offset,
MachinePointerInfo &MPO) override {
auto &MFI = MIRBuilder.getMF().getFrameInfo();
int FI = MFI.CreateFixedObject(Size, Offset, true);
MPO = MachinePointerInfo::getFixedStack(MIRBuilder.getMF(), FI);
unsigned AddrReg = MRI.createGenericVirtualRegister(
LLT::pointer(0, DL.getPointerSizeInBits(0)));
MIRBuilder.buildFrameIndex(AddrReg, FI);
return AddrReg;
}
void assignValueToAddress(unsigned ValVReg, unsigned Addr, uint64_t Size,
MachinePointerInfo &MPO, CCValAssign &VA) override {
auto MMO = MIRBuilder.getMF().getMachineMemOperand(
MPO, MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant, Size,
0);
MIRBuilder.buildLoad(ValVReg, Addr, *MMO);
}
void assignValueToReg(unsigned ValVReg, unsigned PhysReg,
CCValAssign &VA) override {
MIRBuilder.getMBB().addLiveIn(PhysReg);
MIRBuilder.buildCopy(ValVReg, PhysReg);
}
const DataLayout &DL;
};
} // namespace
bool X86CallLowering::lowerFormalArguments(MachineIRBuilder &MIRBuilder,
const Function &F,
ArrayRef<unsigned> VRegs) const {
if (F.arg_empty())
return true;
// TODO: handle variadic function
if (F.isVarArg())
return false;
MachineFunction &MF = MIRBuilder.getMF();
MachineRegisterInfo &MRI = MF.getRegInfo();
auto DL = MF.getDataLayout();
SmallVector<ArgInfo, 8> SplitArgs;
unsigned Idx = 0;
for (auto &Arg : F.args()) {
ArgInfo OrigArg(VRegs[Idx], Arg.getType());
setArgFlags(OrigArg, Idx + 1, DL, F);
splitToValueTypes(OrigArg, SplitArgs, DL, MRI,
[&](ArrayRef<unsigned> Regs) {
MIRBuilder.buildMerge(VRegs[Idx], Regs);
});
Idx++;
}
MachineBasicBlock &MBB = MIRBuilder.getMBB();
if (!MBB.empty())
MIRBuilder.setInstr(*MBB.begin());
FormalArgHandler Handler(MIRBuilder, MRI, CC_X86, DL);
if (!handleAssignments(MIRBuilder, SplitArgs, Handler))
return false;
// Move back to the end of the basic block.
MIRBuilder.setMBB(MBB);
return true;
}
| lgpl-2.1 |
tintin304/chipKIT32-MAX | hardware/pic32/libraries/MRF24G/utility/wf_eint_stub.c | 9 | 8623 | /*******************************************************************************
MRF24WG External Interrupt Stub Functions
Summary: Functions to control MRF24WG External Interrupt.
*******************************************************************************/
/* MRF24WG0M Universal Driver
*
* Copyright (c) 2012-2013, Microchip <www.microchip.com>
* Contact Microchip for the latest version.
*
* This program is free software; distributed under the terms of BSD
* license:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name(s) of the above-listed copyright holder(s) 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.
*/
//==============================================================================
// INCLUDES
//==============================================================================
// board-specific includes
#include <NetworkProfile.x>
#include "./ud_inc/shared/wf_universal_driver.h"
/*****************************************************************************
Function:
void WF_EintInit(void);
Summary:
Configure host processor external interrupt. This line is asserted low by
MRF24WG.
Description:
Called by Universal Driver during initialization.
Parameters:
None
Returns:
None
Remarks:
Should not be called directly from application code.
*****************************************************************************/
void WF_EintInit(void)
{
WIFI_IECxCLR = WIFI_INT_MASK; // disable INT1 interrupt
// configure INT1 pin
WF_INT_IO = 1; // set the level of I/O pin high to deassert interrupt (no pullup on board)
WF_INT_TRIS = 1; // configure pin as an input
WIFI_INT_EDGE = 0; // falling edge triggered
// ensure the interrupt is cleared
WIFI_IFSxCLR = WIFI_INT_MASK; // clear INT1IF bit (clears any pending interrupt)
// set INT1 interrupt priority and subpriority fields (INT1IP and INT1IS fields)
// IPC1CLR = 0xFF000000; // first clear priority and subpriority fields
// IPC1SET = 0x0C000000; // set INT1 priority=3, subpriority=0
WIFI_IPC_IP = WF_IPL; // set priority=3
WIFI_IPC_IS = WF_SUB_IPL; // sub priority=0
// enable the interrupt
WIFI_IECxSET = WIFI_INT_MASK; // enable INT1
}
/*****************************************************************************
Function:
void WF_EintEnable(void);
Summary:
Enables the MRF24WG external interrupt
Description:
Called by Universal Driver during normal operations to enable the MRF24WG
external interrupt.
Note: When using level-triggered interrupts it is possible that host MCU
could miss a falling edge; this can occur because during normal
operations as the Universal Driver disables the external interrupt for
short periods. If the MRF24WG asserts the interrupt line while the
interrupt is disabled the falling edge won't be detected. So, a
check must be made to determine if an interrupt is pending; if so, the
interrupt must be forced.
This is not an issue for level-triggered interrupts.
Parameters:
None
Returns:
None
Remarks:
Should not be called directly from application code.
*****************************************************************************/
void WF_EintEnable(void)
{
// PIC32 uses level-triggered interrupts, so it is possible the Universal Driver
// may have temporarily disabled the external interrupt, and then missed the
// falling edge when the MRF24WG asserted the interrupt line. The code below
// checks for this condition and forces the interrupt if needed.
// if interrupt line is low, then PIC32 may have missed the falling edge
// while the interrupt was disabled.
if ( WF_INT_IO == 0 )
{
// Need to force the interrupt for two reasons:
// 1) there is an event that needs to be serviced
// 2) MRF24WG won't generate another falling edge until the interrupt
// is processed.
WIFI_IFSxSET = WIFI_INT_MASK; // this will force the INT1 interrupt as soon as we
// we enabled it below.
}
/* enable the external interrupt */
WIFI_IECxSET = WIFI_INT_MASK;
}
/*****************************************************************************
Function:
void WF_EintDisable(void);
Summary:
Disables the MRF24WG external interrupt
Description:
Called by Universal Driver during normal operations to disable the MRF24WG
external interrupt.
Parameters:
None
Returns:
None
Remarks:
Should not be called directly from application code.
*****************************************************************************/
void WF_EintDisable(void)
{
WIFI_IECxCLR = WIFI_INT_MASK;
}
/*****************************************************************************
Function:
bool WF_isEintDisabled(void);
Summary:
Determines if the external interrupt is disabled
Description:
Called by Universal Driver during normal operations to check if the current
state of the external interrupt is disabled.
Parameters:
None
Returns:
True if interrupt is disabled, else False
Remarks:
Should not be called directly from application code.
*****************************************************************************/
bool WF_isEintDisabled(void)
{
return (WIFI_INT_IE == 0);
}
/*****************************************************************************
Function:
bool WF_isEintPending(void);
Summary:
Determines if the external interrupt is pending.
Description:
Called by Universal Driver during normal operations to check if an external
interrupt is pending.
Parameters:
None
Returns:
True if interrupt is pending, else False
Remarks:
Should not be called directly from application code.
*****************************************************************************/
bool WF_isEintPending(void)
{
// if interrupt line is low, but interrupt request has not occurred
return(((WF_INT_IO == 0) && (WIFI_INT_IF == 0)));
}
/*****************************************************************************
Function:
void _WFInterrupt(void);
Summary:
MRF24WG external interrupt handler
Description:
This interrupt handler should:
1) ensure the interrupt is disabled upon exit (Universal Driver will reenable it)
1) clear the interrupt
2) call WFEintHandler()
Parameters:
None
Returns:
None
Remarks:
None
*****************************************************************************/
#if defined(__PIC32MZXX__)
void __attribute((interrupt(WF_IPL_ISR), at_vector(WF_INT_VEC), nomips16)) _WFInterrupt(void)
#else
void __attribute((interrupt(WF_IPL_ISR), vector(WF_INT_VEC), nomips16)) _WFInterrupt(void)
#endif
{
// clear EINT
WIFI_IFSxCLR = WIFI_INT_MASK; // clear the interrupt
WIFI_IECxCLR = WIFI_INT_MASK; // disable external interrupt
WF_EintHandler(); // call Univeral Driver handler function
}
| lgpl-2.1 |
davidlt/root | core/zip/src/gzwrite.c | 1042 | 14602 | /* gzwrite.c -- zlib functions for writing gzip files
* Copyright (C) 2004, 2005, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "gzguts.h"
/* Local functions */
local int gz_init OF((gz_statep));
local int gz_comp OF((gz_statep, int));
local int gz_zero OF((gz_statep, z_off64_t));
/* Initialize state for writing a gzip file. Mark initialization by setting
state->size to non-zero. Return -1 on failure or 0 on success. */
local int gz_init(state)
gz_statep state;
{
int ret;
z_streamp strm = &(state->strm);
/* allocate input and output buffers */
state->in = malloc(state->want);
state->out = malloc(state->want);
if (state->in == NULL || state->out == NULL) {
if (state->out != NULL)
free(state->out);
if (state->in != NULL)
free(state->in);
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
/* allocate deflate memory, set up for gzip compression */
strm->zalloc = Z_NULL;
strm->zfree = Z_NULL;
strm->opaque = Z_NULL;
ret = deflateInit2(strm, state->level, Z_DEFLATED,
15 + 16, 8, state->strategy);
if (ret != Z_OK) {
free(state->in);
gz_error(state, Z_MEM_ERROR, "out of memory");
return -1;
}
/* mark state as initialized */
state->size = state->want;
/* initialize write buffer */
strm->avail_out = state->size;
strm->next_out = state->out;
state->next = strm->next_out;
return 0;
}
/* Compress whatever is at avail_in and next_in and write to the output file.
Return -1 if there is an error writing to the output file, otherwise 0.
flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH,
then the deflate() state is reset to start a new gzip stream. */
local int gz_comp(state, flush)
gz_statep state;
int flush;
{
int ret, got;
unsigned have;
z_streamp strm = &(state->strm);
/* allocate memory if this is the first time through */
if (state->size == 0 && gz_init(state) == -1)
return -1;
/* run deflate() on provided input until it produces no more output */
ret = Z_OK;
do {
/* write out current buffer contents if full, or if flushing, but if
doing Z_FINISH then don't write until we get to Z_STREAM_END */
if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
(flush != Z_FINISH || ret == Z_STREAM_END))) {
have = (unsigned)(strm->next_out - state->next);
if (have && ((got = write(state->fd, state->next, have)) < 0 ||
(unsigned)got != have)) {
gz_error(state, Z_ERRNO, zstrerror());
return -1;
}
if (strm->avail_out == 0) {
strm->avail_out = state->size;
strm->next_out = state->out;
}
state->next = strm->next_out;
}
/* compress */
have = strm->avail_out;
ret = deflate(strm, flush);
if (ret == Z_STREAM_ERROR) {
gz_error(state, Z_STREAM_ERROR,
"internal error: deflate stream corrupt");
return -1;
}
have -= strm->avail_out;
} while (have);
/* if that completed a deflate stream, allow another to start */
if (flush == Z_FINISH)
deflateReset(strm);
/* all done, no errors */
return 0;
}
/* Compress len zeros to output. Return -1 on error, 0 on success. */
local int gz_zero(state, len)
gz_statep state;
z_off64_t len;
{
int first;
unsigned n;
z_streamp strm = &(state->strm);
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return -1;
/* compress len zeros (len guaranteed > 0) */
first = 1;
while (len) {
n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
(unsigned)len : state->size;
if (first) {
memset(state->in, 0, n);
first = 0;
}
strm->avail_in = n;
strm->next_in = state->in;
state->pos += n;
if (gz_comp(state, Z_NO_FLUSH) == -1)
return -1;
len -= n;
}
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzwrite(file, buf, len)
gzFile file;
voidpc buf;
unsigned len;
{
unsigned put = len;
unsigned n;
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return 0;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return 0;
/* since an int is returned, make sure len fits in one, otherwise return
with an error (this avoids the flaw in the interface) */
if ((int)len < 0) {
gz_error(state, Z_BUF_ERROR, "requested length does not fit in int");
return 0;
}
/* if len is zero, avoid unnecessary operations */
if (len == 0)
return 0;
/* allocate memory if this is the first time through */
if (state->size == 0 && gz_init(state) == -1)
return 0;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return 0;
}
/* for small len, copy to input buffer, otherwise compress directly */
if (len < state->size) {
/* copy to input buffer, compress when full */
do {
if (strm->avail_in == 0)
strm->next_in = state->in;
n = state->size - strm->avail_in;
if (n > len)
n = len;
memcpy(strm->next_in + strm->avail_in, buf, n);
strm->avail_in += n;
state->pos += n;
buf = (char *)buf + n;
len -= n;
if (len && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
} while (len);
}
else {
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
/* directly compress user buffer to file */
strm->avail_in = len;
strm->next_in = (voidp)buf;
state->pos += len;
if (gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
}
/* input was all buffered or compressed (put will fit in int) */
return (int)put;
}
/* -- see zlib.h -- */
int ZEXPORT gzputc(file, c)
gzFile file;
int c;
{
unsigned char buf[1];
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return -1;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return -1;
}
/* try writing to input buffer for speed (state->size == 0 if buffer not
initialized) */
if (strm->avail_in < state->size) {
if (strm->avail_in == 0)
strm->next_in = state->in;
strm->next_in[strm->avail_in++] = c;
state->pos++;
return c;
}
/* no room in buffer or not initialized, use gz_write() */
buf[0] = c;
if (gzwrite(file, buf, 1) != 1)
return -1;
return c;
}
/* -- see zlib.h -- */
int ZEXPORT gzputs(file, str)
gzFile file;
const char *str;
{
int ret;
unsigned len;
/* write string */
len = (unsigned)strlen(str);
ret = gzwrite(file, str, len);
return ret == 0 && len != 0 ? -1 : ret;
}
#ifdef STDC
#include <stdarg.h>
/* -- see zlib.h -- */
int ZEXPORTVA gzprintf (gzFile file, const char *format, ...)
{
int size, len;
gz_statep state;
z_streamp strm;
va_list va;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return 0;
/* make sure we have some buffer space */
if (state->size == 0 && gz_init(state) == -1)
return 0;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return 0;
}
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
/* do the printf() into the input buffer, put length in len */
size = (int)(state->size);
state->in[size - 1] = 0;
va_start(va, format);
#ifdef NO_vsnprintf
# ifdef HAS_vsprintf_void
(void)vsprintf(state->in, format, va);
va_end(va);
for (len = 0; len < size; len++)
if (state->in[len] == 0) break;
# else
len = vsprintf(state->in, format, va);
va_end(va);
# endif
#else
# ifdef HAS_vsnprintf_void
(void)vsnprintf(state->in, size, format, va);
va_end(va);
len = strlen(state->in);
# else
len = vsnprintf((char *)(state->in), size, format, va);
va_end(va);
# endif
#endif
/* check that printf() results fit in buffer */
if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
return 0;
/* update buffer and position, defer compression until needed */
strm->avail_in = (unsigned)len;
strm->next_in = state->in;
state->pos += len;
return len;
}
#else /* !STDC */
/* -- see zlib.h -- */
int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
gzFile file;
const char *format;
int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
{
int size, len;
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return 0;
/* make sure we have some buffer space */
if (state->size == 0 && gz_init(state) == -1)
return 0;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return 0;
}
/* consume whatever's left in the input buffer */
if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
return 0;
/* do the printf() into the input buffer, put length in len */
size = (int)(state->size);
state->in[size - 1] = 0;
#ifdef NO_snprintf
# ifdef HAS_sprintf_void
sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
for (len = 0; len < size; len++)
if (state->in[len] == 0) break;
# else
len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
# endif
#else
# ifdef HAS_snprintf_void
snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
len = strlen(state->in);
# else
len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
# endif
#endif
/* check that printf() results fit in buffer */
if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
return 0;
/* update buffer and position, defer compression until needed */
strm->avail_in = (unsigned)len;
strm->next_in = state->in;
state->pos += len;
return len;
}
#endif
/* -- see zlib.h -- */
int ZEXPORT gzflush(file, flush)
gzFile file;
int flush;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return Z_STREAM_ERROR;
/* check flush parameter */
if (flush < 0 || flush > Z_FINISH)
return Z_STREAM_ERROR;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return -1;
}
/* compress remaining data with requested flush */
gz_comp(state, flush);
return state->err;
}
/* -- see zlib.h -- */
int ZEXPORT gzsetparams(file, level, strategy)
gzFile file;
int level;
int strategy;
{
gz_statep state;
z_streamp strm;
/* get internal structure */
if (file == NULL)
return Z_STREAM_ERROR;
state = (gz_statep)file;
strm = &(state->strm);
/* check that we're writing and that there's no error */
if (state->mode != GZ_WRITE || state->err != Z_OK)
return Z_STREAM_ERROR;
/* if no change is requested, then do nothing */
if (level == state->level && strategy == state->strategy)
return Z_OK;
/* check for seek request */
if (state->seek) {
state->seek = 0;
if (gz_zero(state, state->skip) == -1)
return -1;
}
/* change compression parameters for subsequent input */
if (state->size) {
/* flush previous input with previous parameters before changing */
if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1)
return state->err;
deflateParams(strm, level, strategy);
}
state->level = level;
state->strategy = strategy;
return Z_OK;
}
/* -- see zlib.h -- */
int ZEXPORT gzclose_w(file)
gzFile file;
{
int ret = 0;
gz_statep state;
/* get internal structure */
if (file == NULL)
return Z_STREAM_ERROR;
state = (gz_statep)file;
/* check that we're writing */
if (state->mode != GZ_WRITE)
return Z_STREAM_ERROR;
/* check for seek request */
if (state->seek) {
state->seek = 0;
ret += gz_zero(state, state->skip);
}
/* flush, free memory, and close file */
ret += gz_comp(state, Z_FINISH);
(void)deflateEnd(&(state->strm));
free(state->out);
free(state->in);
gz_error(state, Z_OK, NULL);
free(state->path);
ret += close(state->fd);
free(state);
return ret ? Z_ERRNO : Z_OK;
}
| lgpl-2.1 |
eric100lin/Qt-4.8.6 | src/3rdparty/webkit/Source/WebCore/editing/qt/SmartReplaceQt.cpp | 58 | 3258 | /*
* Copyright (C) 2010 Robert Hogan <robert@roberthogan.net>. All rights reserved.
* Copyright (C) 2007,2008,2009 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "SmartReplace.h"
namespace WebCore {
bool isCharacterSmartReplaceExempt(UChar32 c, bool isPreviousCharacter)
{
QChar d(c);
if (d.isSpace())
return true;
if (!isPreviousCharacter && d.isPunct())
return true;
if ((c >= 0x1100 && c <= (0x1100 + 256)) // Hangul Jamo (0x1100 - 0x11FF)
|| (c >= 0x2E80 && c <= (0x2E80 + 352)) // CJK & Kangxi Radicals (0x2E80 - 0x2FDF)
|| (c >= 0x2FF0 && c <= (0x2FF0 + 464)) // Ideograph Deseriptions, CJK Symbols, Hiragana, Katakana, Bopomofo, Hangul Compatibility Jamo, Kanbun, & Bopomofo Ext (0x2FF0 - 0x31BF)
|| (c >= 0x3200 && c <= (0x3200 + 29392)) // Enclosed CJK, CJK Ideographs (Uni Han & Ext A), & Yi (0x3200 - 0xA4CF)
|| (c >= 0xAC00 && c <= (0xAC00 + 11183)) // Hangul Syllables (0xAC00 - 0xD7AF)
|| (c >= 0xF900 && c <= (0xF900 + 352)) // CJK Compatibility Ideographs (0xF900 - 0xFA5F)
|| (c >= 0xFE30 && c <= (0xFE30 + 32)) // CJK Compatibility From (0xFE30 - 0xFE4F)
|| (c >= 0xFF00 && c <= (0xFF00 + 240)) // Half/Full Width Form (0xFF00 - 0xFFEF)
|| (c >= 0x20000 && c <= (0x20000 + 0xA6D7)) // CJK Ideograph Exntension B
|| (c >= 0x2F800 && c <= (0x2F800 + 0x021E))) // CJK Compatibility Ideographs (0x2F800 - 0x2FA1D)
return true;
const char prev[] = "([\"\'#$/-`{\0";
const char next[] = ")].,;:?\'!\"%*-/}\0";
const char* str = (isPreviousCharacter) ? prev : next;
for (int i = 0; i < strlen(str); ++i) {
if (str[i] == c)
return true;
}
return false;
}
}
| lgpl-2.1 |
radekp/sdl-qtmoko | src/video/fbcon/SDL_fbevents.c | 67 | 32336 | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
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
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* Handle the event stream, converting console events into SDL events */
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
/* For parsing /proc */
#include <dirent.h>
#include <ctype.h>
#include <linux/vt.h>
#include <linux/kd.h>
#include <linux/keyboard.h>
#include "SDL_timer.h"
#include "SDL_mutex.h"
#include "../SDL_sysvideo.h"
#include "../../events/SDL_sysevents.h"
#include "../../events/SDL_events_c.h"
#include "SDL_fbvideo.h"
#include "SDL_fbevents_c.h"
#include "SDL_fbkeys.h"
#include "SDL_fbelo.h"
#ifndef GPM_NODE_FIFO
#define GPM_NODE_FIFO "/dev/gpmdata"
#endif
/*#define DEBUG_KEYBOARD*/
/*#define DEBUG_MOUSE*/
/* The translation tables from a console scancode to a SDL keysym */
#define NUM_VGAKEYMAPS (1<<KG_CAPSSHIFT)
static Uint16 vga_keymap[NUM_VGAKEYMAPS][NR_KEYS];
static SDLKey keymap[128];
static Uint16 keymap_temp[128]; /* only used at startup */
static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym);
/* Ugh, we have to duplicate the kernel's keysym mapping code...
Oh, it's not so bad. :-)
FIXME: Add keyboard LED handling code
*/
static void FB_vgainitkeymaps(int fd)
{
struct kbentry entry;
int map, i;
/* Don't do anything if we are passed a closed keyboard */
if ( fd < 0 ) {
return;
}
/* Load all the keysym mappings */
for ( map=0; map<NUM_VGAKEYMAPS; ++map ) {
SDL_memset(vga_keymap[map], 0, NR_KEYS*sizeof(Uint16));
for ( i=0; i<NR_KEYS; ++i ) {
entry.kb_table = map;
entry.kb_index = i;
if ( ioctl(fd, KDGKBENT, &entry) == 0 ) {
/* fill keytemp. This replaces SDL_fbkeys.h */
if ( (map == 0) && (i<128) ) {
keymap_temp[i] = entry.kb_value;
}
/* The "Enter" key is a special case */
if ( entry.kb_value == K_ENTER ) {
entry.kb_value = K(KT_ASCII,13);
}
/* Handle numpad specially as well */
if ( KTYP(entry.kb_value) == KT_PAD ) {
switch ( entry.kb_value ) {
case K_P0:
case K_P1:
case K_P2:
case K_P3:
case K_P4:
case K_P5:
case K_P6:
case K_P7:
case K_P8:
case K_P9:
vga_keymap[map][i]=entry.kb_value;
vga_keymap[map][i]+= '0';
break;
case K_PPLUS:
vga_keymap[map][i]=K(KT_ASCII,'+');
break;
case K_PMINUS:
vga_keymap[map][i]=K(KT_ASCII,'-');
break;
case K_PSTAR:
vga_keymap[map][i]=K(KT_ASCII,'*');
break;
case K_PSLASH:
vga_keymap[map][i]=K(KT_ASCII,'/');
break;
case K_PENTER:
vga_keymap[map][i]=K(KT_ASCII,'\r');
break;
case K_PCOMMA:
vga_keymap[map][i]=K(KT_ASCII,',');
break;
case K_PDOT:
vga_keymap[map][i]=K(KT_ASCII,'.');
break;
default:
break;
}
}
/* Do the normal key translation */
if ( (KTYP(entry.kb_value) == KT_LATIN) ||
(KTYP(entry.kb_value) == KT_ASCII) ||
(KTYP(entry.kb_value) == KT_LETTER) ) {
vga_keymap[map][i] = entry.kb_value;
}
}
}
}
}
int FB_InGraphicsMode(_THIS)
{
return((keyboard_fd >= 0) && (saved_kbd_mode >= 0));
}
int FB_EnterGraphicsMode(_THIS)
{
struct termios keyboard_termios;
/* Set medium-raw keyboard mode */
if ( (keyboard_fd >= 0) && !FB_InGraphicsMode(this) ) {
/* Switch to the correct virtual terminal */
if ( current_vt > 0 ) {
struct vt_stat vtstate;
if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) {
saved_vt = vtstate.v_active;
}
if ( ioctl(keyboard_fd, VT_ACTIVATE, current_vt) == 0 ) {
ioctl(keyboard_fd, VT_WAITACTIVE, current_vt);
}
}
/* Set the terminal input mode */
if ( tcgetattr(keyboard_fd, &saved_kbd_termios) < 0 ) {
SDL_SetError("Unable to get terminal attributes");
if ( keyboard_fd > 0 ) {
close(keyboard_fd);
}
keyboard_fd = -1;
return(-1);
}
if ( ioctl(keyboard_fd, KDGKBMODE, &saved_kbd_mode) < 0 ) {
SDL_SetError("Unable to get current keyboard mode");
if ( keyboard_fd > 0 ) {
close(keyboard_fd);
}
keyboard_fd = -1;
return(-1);
}
keyboard_termios = saved_kbd_termios;
keyboard_termios.c_lflag &= ~(ICANON | ECHO | ISIG);
keyboard_termios.c_iflag &= ~(ISTRIP | IGNCR | ICRNL | INLCR | IXOFF | IXON);
keyboard_termios.c_cc[VMIN] = 0;
keyboard_termios.c_cc[VTIME] = 0;
if (tcsetattr(keyboard_fd, TCSAFLUSH, &keyboard_termios) < 0) {
FB_CloseKeyboard(this);
SDL_SetError("Unable to set terminal attributes");
return(-1);
}
/* This will fail if we aren't root or this isn't our tty */
if ( ioctl(keyboard_fd, KDSKBMODE, K_MEDIUMRAW) < 0 ) {
FB_CloseKeyboard(this);
SDL_SetError("Unable to set keyboard in raw mode");
return(-1);
}
if ( ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS) < 0 ) {
FB_CloseKeyboard(this);
SDL_SetError("Unable to set keyboard in graphics mode");
return(-1);
}
/* Prevent switching the virtual terminal */
ioctl(keyboard_fd, VT_LOCKSWITCH, 1);
}
return(keyboard_fd);
}
void FB_LeaveGraphicsMode(_THIS)
{
if ( FB_InGraphicsMode(this) ) {
ioctl(keyboard_fd, KDSETMODE, KD_TEXT);
ioctl(keyboard_fd, KDSKBMODE, saved_kbd_mode);
tcsetattr(keyboard_fd, TCSAFLUSH, &saved_kbd_termios);
saved_kbd_mode = -1;
/* Head back over to the original virtual terminal */
ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1);
if ( saved_vt > 0 ) {
ioctl(keyboard_fd, VT_ACTIVATE, saved_vt);
}
}
}
void FB_CloseKeyboard(_THIS)
{
if ( keyboard_fd >= 0 ) {
FB_LeaveGraphicsMode(this);
if ( keyboard_fd > 0 ) {
close(keyboard_fd);
}
}
keyboard_fd = -1;
}
int FB_OpenKeyboard(_THIS)
{
/* Open only if not already opened */
if ( keyboard_fd < 0 ) {
static const char * const tty0[] = { "/dev/tty0", "/dev/vc/0", NULL };
static const char * const vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL };
int i, tty0_fd;
/* Try to query for a free virtual terminal */
tty0_fd = -1;
for ( i=0; tty0[i] && (tty0_fd < 0); ++i ) {
tty0_fd = open(tty0[i], O_WRONLY, 0);
}
if ( tty0_fd < 0 ) {
tty0_fd = dup(0); /* Maybe stdin is a VT? */
}
ioctl(tty0_fd, VT_OPENQRY, ¤t_vt);
close(tty0_fd);
if ( (geteuid() == 0) && (current_vt > 0) ) {
for ( i=0; vcs[i] && (keyboard_fd < 0); ++i ) {
char vtpath[12];
SDL_snprintf(vtpath, SDL_arraysize(vtpath), vcs[i], current_vt);
keyboard_fd = open(vtpath, O_RDWR, 0);
#ifdef DEBUG_KEYBOARD
fprintf(stderr, "vtpath = %s, fd = %d\n",
vtpath, keyboard_fd);
#endif /* DEBUG_KEYBOARD */
/* This needs to be our controlling tty
so that the kernel ioctl() calls work
*/
if ( keyboard_fd >= 0 ) {
tty0_fd = open("/dev/tty", O_RDWR, 0);
if ( tty0_fd >= 0 ) {
ioctl(tty0_fd, TIOCNOTTY, 0);
close(tty0_fd);
}
}
}
}
if ( keyboard_fd < 0 ) {
/* Last resort, maybe our tty is a usable VT */
struct vt_stat vtstate;
keyboard_fd = open("/dev/tty", O_RDWR);
if ( ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0 ) {
current_vt = vtstate.v_active;
} else {
current_vt = 0;
}
}
#ifdef DEBUG_KEYBOARD
fprintf(stderr, "Current VT: %d\n", current_vt);
#endif
saved_kbd_mode = -1;
/* Make sure that our input is a console terminal */
{ int dummy;
if ( ioctl(keyboard_fd, KDGKBMODE, &dummy) < 0 ) {
close(keyboard_fd);
keyboard_fd = -1;
SDL_SetError("Unable to open a console terminal");
}
}
/* Set up keymap */
FB_vgainitkeymaps(keyboard_fd);
}
return(keyboard_fd);
}
static enum {
MOUSE_NONE = -1,
MOUSE_MSC, /* Note: GPM uses the MSC protocol */
MOUSE_PS2,
MOUSE_IMPS2,
MOUSE_MS,
MOUSE_BM,
MOUSE_ELO,
MOUSE_TSLIB,
NUM_MOUSE_DRVS
} mouse_drv = MOUSE_NONE;
void FB_CloseMouse(_THIS)
{
#if SDL_INPUT_TSLIB
if (ts_dev != NULL) {
ts_close(ts_dev);
ts_dev = NULL;
mouse_fd = -1;
}
#endif /* SDL_INPUT_TSLIB */
if ( mouse_fd > 0 ) {
close(mouse_fd);
}
mouse_fd = -1;
}
/* Returns processes listed in /proc with the desired name */
static int find_pid(DIR *proc, const char *wanted_name)
{
struct dirent *entry;
int pid;
/* First scan proc for the gpm process */
pid = 0;
while ( (pid == 0) && ((entry=readdir(proc)) != NULL) ) {
if ( isdigit(entry->d_name[0]) ) {
FILE *status;
char path[PATH_MAX];
char name[PATH_MAX];
SDL_snprintf(path, SDL_arraysize(path), "/proc/%s/status", entry->d_name);
status=fopen(path, "r");
if ( status ) {
name[0] = '\0';
fscanf(status, "Name: %s", name);
if ( SDL_strcmp(name, wanted_name) == 0 ) {
pid = SDL_atoi(entry->d_name);
}
fclose(status);
}
}
}
return pid;
}
/* Returns true if /dev/gpmdata is being written to by gpm */
static int gpm_available(char *proto, size_t protolen)
{
int available;
DIR *proc;
int pid;
int cmdline, len, arglen;
char path[PATH_MAX];
char args[PATH_MAX], *arg;
/* Don't bother looking if the fifo isn't there */
#ifdef DEBUG_MOUSE
fprintf(stderr,"testing gpm\n");
#endif
if ( access(GPM_NODE_FIFO, F_OK) < 0 ) {
return(0);
}
available = 0;
proc = opendir("/proc");
if ( proc ) {
char raw_proto[10] = { '\0' };
char repeat_proto[10] = { '\0' };
while ( !available && (pid=find_pid(proc, "gpm")) > 0 ) {
SDL_snprintf(path, SDL_arraysize(path), "/proc/%d/cmdline", pid);
cmdline = open(path, O_RDONLY, 0);
if ( cmdline >= 0 ) {
len = read(cmdline, args, sizeof(args));
arg = args;
while ( len > 0 ) {
arglen = SDL_strlen(arg)+1;
#ifdef DEBUG_MOUSE
fprintf(stderr,"gpm arg %s len %d\n",arg,arglen);
#endif
if ( SDL_strcmp(arg, "-t") == 0) {
/* protocol string, keep it for later */
char *t, *s;
t = arg + arglen;
s = SDL_strchr(t, ' ');
if (s) *s = 0;
SDL_strlcpy(raw_proto, t, SDL_arraysize(raw_proto));
if (s) *s = ' ';
}
if ( SDL_strncmp(arg, "-R", 2) == 0 ) {
char *t, *s;
available = 1;
t = arg + 2;
s = SDL_strchr(t, ' ');
if (s) *s = 0;
SDL_strlcpy(repeat_proto, t, SDL_arraysize(repeat_proto));
if (s) *s = ' ';
}
len -= arglen;
arg += arglen;
}
close(cmdline);
}
}
closedir(proc);
if ( available ) {
if ( SDL_strcmp(repeat_proto, "raw") == 0 ) {
SDL_strlcpy(proto, raw_proto, protolen);
} else if ( *repeat_proto ) {
SDL_strlcpy(proto, repeat_proto, protolen);
} else {
SDL_strlcpy(proto, "msc", protolen);
}
}
}
return available;
}
/* rcg06112001 Set up IMPS/2 mode, if possible. This gives
* us access to the mousewheel, etc. Returns zero if
* writes to device failed, but you still need to query the
* device to see which mode it's actually in.
*/
static int set_imps2_mode(int fd)
{
/* If you wanted to control the mouse mode (and we do :) ) ...
Set IMPS/2 protocol:
{0xf3,200,0xf3,100,0xf3,80}
Reset mouse device:
{0xFF}
*/
Uint8 set_imps2[] = {0xf3, 200, 0xf3, 100, 0xf3, 80};
/*Uint8 reset = 0xff;*/
fd_set fdset;
struct timeval tv;
int retval = 0;
if ( write(fd, &set_imps2, sizeof(set_imps2)) == sizeof(set_imps2) ) {
/* Don't reset it, that'll clear IMPS/2 mode on some mice
if (write(fd, &reset, sizeof (reset)) == sizeof (reset) ) {
retval = 1;
}
*/
}
/* Get rid of any chatter from the above */
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
tv.tv_sec = 0;
tv.tv_usec = 0;
while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) {
char temp[32];
read(fd, temp, sizeof(temp));
}
return retval;
}
/* Returns true if the mouse uses the IMPS/2 protocol */
static int detect_imps2(int fd)
{
int imps2;
imps2 = 0;
if ( SDL_getenv("SDL_MOUSEDEV_IMPS2") ) {
imps2 = 1;
}
if ( ! imps2 ) {
Uint8 query_ps2 = 0xF2;
fd_set fdset;
struct timeval tv;
/* Get rid of any mouse motion noise */
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
tv.tv_sec = 0;
tv.tv_usec = 0;
while ( select(fd+1, &fdset, 0, 0, &tv) > 0 ) {
char temp[32];
read(fd, temp, sizeof(temp));
}
/* Query for the type of mouse protocol */
if ( write(fd, &query_ps2, sizeof (query_ps2)) == sizeof (query_ps2)) {
Uint8 ch = 0;
/* Get the mouse protocol response */
do {
FD_ZERO(&fdset);
FD_SET(fd, &fdset);
tv.tv_sec = 1;
tv.tv_usec = 0;
if ( select(fd+1, &fdset, 0, 0, &tv) < 1 ) {
break;
}
} while ( (read(fd, &ch, sizeof (ch)) == sizeof (ch)) &&
((ch == 0xFA) || (ch == 0xAA)) );
/* Experimental values (Logitech wheelmouse) */
#ifdef DEBUG_MOUSE
fprintf(stderr, "Last mouse mode: 0x%x\n", ch);
#endif
if ( (ch == 3) || (ch == 4) ) {
imps2 = 1;
}
}
}
return imps2;
}
int FB_OpenMouse(_THIS)
{
int i;
const char *mousedev;
const char *mousedrv;
mousedrv = SDL_getenv("SDL_MOUSEDRV");
mousedev = SDL_getenv("SDL_MOUSEDEV");
mouse_fd = -1;
#if SDL_INPUT_TSLIB
if ( mousedrv && (SDL_strcmp(mousedrv, "TSLIB") == 0) ) {
if (mousedev == NULL) mousedev = SDL_getenv("TSLIB_TSDEVICE");
if (mousedev != NULL) {
ts_dev = ts_open(mousedev, 1);
if ((ts_dev != NULL) && (ts_config(ts_dev) >= 0)) {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using tslib touchscreen\n");
#endif
mouse_drv = MOUSE_TSLIB;
mouse_fd = ts_fd(ts_dev);
return mouse_fd;
}
}
mouse_drv = MOUSE_NONE;
return mouse_fd;
}
#endif /* SDL_INPUT_TSLIB */
/* ELO TOUCHSCREEN SUPPORT */
if ( mousedrv && (SDL_strcmp(mousedrv, "ELO") == 0) ) {
mouse_fd = open(mousedev, O_RDWR);
if ( mouse_fd >= 0 ) {
if(eloInitController(mouse_fd)) {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using ELO touchscreen\n");
#endif
mouse_drv = MOUSE_ELO;
}
}
else if ( mouse_fd < 0 ) {
mouse_drv = MOUSE_NONE;
}
return(mouse_fd);
}
/* STD MICE */
if ( mousedev == NULL ) {
/* FIXME someday... allow multiple mice in this driver */
static const char *ps2mice[] = {
"/dev/input/mice", "/dev/usbmouse", "/dev/psaux", NULL
};
/* First try to use GPM in repeater mode */
if ( mouse_fd < 0 ) {
char proto[10];
if ( gpm_available(proto, SDL_arraysize(proto)) ) {
mouse_fd = open(GPM_NODE_FIFO, O_RDONLY, 0);
if ( mouse_fd >= 0 ) {
if ( SDL_strcmp(proto, "msc") == 0 ) {
mouse_drv = MOUSE_MSC;
} else if ( SDL_strcmp(proto, "ps2") == 0 ) {
mouse_drv = MOUSE_PS2;
} else if ( SDL_strcmp(proto, "imps2") == 0 ) {
mouse_drv = MOUSE_IMPS2;
} else if ( SDL_strcmp(proto, "ms") == 0 ||
SDL_strcmp(proto, "bare") == 0 ) {
mouse_drv = MOUSE_MS;
} else if ( SDL_strcmp(proto, "bm") == 0 ) {
mouse_drv = MOUSE_BM;
} else {
/* Unknown protocol... */
#ifdef DEBUG_MOUSE
fprintf(stderr, "GPM mouse using unknown protocol = %s\n", proto);
#endif
close(mouse_fd);
mouse_fd = -1;
}
}
#ifdef DEBUG_MOUSE
if ( mouse_fd >= 0 ) {
fprintf(stderr, "Using GPM mouse, protocol = %s\n", proto);
}
#endif /* DEBUG_MOUSE */
}
}
/* Now try to use a modern PS/2 mouse */
for ( i=0; (mouse_fd < 0) && ps2mice[i]; ++i ) {
mouse_fd = open(ps2mice[i], O_RDWR, 0);
if (mouse_fd < 0) {
mouse_fd = open(ps2mice[i], O_RDONLY, 0);
}
if (mouse_fd >= 0) {
/* rcg06112001 Attempt to set IMPS/2 mode */
set_imps2_mode(mouse_fd);
if (detect_imps2(mouse_fd)) {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using IMPS2 mouse\n");
#endif
mouse_drv = MOUSE_IMPS2;
} else {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using PS2 mouse\n");
#endif
mouse_drv = MOUSE_PS2;
}
}
}
/* Next try to use a PPC ADB port mouse */
if ( mouse_fd < 0 ) {
mouse_fd = open("/dev/adbmouse", O_RDONLY, 0);
if ( mouse_fd >= 0 ) {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using ADB mouse\n");
#endif
mouse_drv = MOUSE_BM;
}
}
}
/* Default to a serial Microsoft mouse */
if ( mouse_fd < 0 ) {
if ( mousedev == NULL ) {
mousedev = "/dev/mouse";
}
mouse_fd = open(mousedev, O_RDONLY, 0);
if ( mouse_fd >= 0 ) {
struct termios mouse_termios;
/* Set the sampling speed to 1200 baud */
tcgetattr(mouse_fd, &mouse_termios);
mouse_termios.c_iflag = IGNBRK | IGNPAR;
mouse_termios.c_oflag = 0;
mouse_termios.c_lflag = 0;
mouse_termios.c_line = 0;
mouse_termios.c_cc[VTIME] = 0;
mouse_termios.c_cc[VMIN] = 1;
mouse_termios.c_cflag = CREAD | CLOCAL | HUPCL;
mouse_termios.c_cflag |= CS8;
mouse_termios.c_cflag |= B1200;
tcsetattr(mouse_fd, TCSAFLUSH, &mouse_termios);
if ( mousedrv && (SDL_strcmp(mousedrv, "PS2") == 0) ) {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using (user specified) PS2 mouse on %s\n", mousedev);
#endif
mouse_drv = MOUSE_PS2;
} else {
#ifdef DEBUG_MOUSE
fprintf(stderr, "Using (default) MS mouse on %s\n", mousedev);
#endif
mouse_drv = MOUSE_MS;
}
}
}
if ( mouse_fd < 0 ) {
mouse_drv = MOUSE_NONE;
}
return(mouse_fd);
}
static int posted = 0;
void FB_vgamousecallback(int button, int relative, int dx, int dy)
{
int button_1, button_3;
int button_state;
int state_changed;
int i;
Uint8 state;
if ( dx || dy ) {
posted += SDL_PrivateMouseMotion(0, relative, dx, dy);
}
/* Swap button 1 and 3 */
button_1 = (button & 0x04) >> 2;
button_3 = (button & 0x01) << 2;
button &= ~0x05;
button |= (button_1|button_3);
/* See what changed */
button_state = SDL_GetMouseState(NULL, NULL);
state_changed = button_state ^ button;
for ( i=0; i<8; ++i ) {
if ( state_changed & (1<<i) ) {
if ( button & (1<<i) ) {
state = SDL_PRESSED;
} else {
state = SDL_RELEASED;
}
posted += SDL_PrivateMouseButton(state, i+1, 0, 0);
}
}
}
/* Handle input from tslib */
#if SDL_INPUT_TSLIB
static void handle_tslib(_THIS)
{
struct ts_sample sample;
int button;
while (ts_read(ts_dev, &sample, 1) > 0) {
button = (sample.pressure > 0) ? 1 : 0;
button <<= 2; /* must report it as button 3 */
FB_vgamousecallback(button, 0, sample.x, sample.y);
}
return;
}
#endif /* SDL_INPUT_TSLIB */
/* For now, use MSC, PS/2, and MS protocols
Driver adapted from the SVGAlib mouse driver code (taken from gpm, etc.)
*/
static void handle_mouse(_THIS)
{
static int start = 0;
static unsigned char mousebuf[BUFSIZ];
static int relative = 1;
int i, nread;
int button = 0;
int dx = 0, dy = 0;
int packetsize = 0;
int realx, realy;
/* Figure out the mouse packet size */
switch (mouse_drv) {
case MOUSE_NONE:
/* Ack! */
read(mouse_fd, mousebuf, BUFSIZ);
return;
case MOUSE_MSC:
packetsize = 5;
break;
case MOUSE_IMPS2:
packetsize = 4;
break;
case MOUSE_PS2:
case MOUSE_MS:
case MOUSE_BM:
packetsize = 3;
break;
case MOUSE_ELO:
/* try to read the next packet */
if(eloReadPosition(this, mouse_fd, &dx, &dy, &button, &realx, &realy)) {
button = (button & 0x01) << 2;
FB_vgamousecallback(button, 0, dx, dy);
}
return; /* nothing left to do */
case MOUSE_TSLIB:
#if SDL_INPUT_TSLIB
handle_tslib(this);
#endif
return; /* nothing left to do */
default:
/* Uh oh.. */
packetsize = 0;
break;
}
/* Special handling for the quite sensitive ELO controller */
if (mouse_drv == MOUSE_ELO) {
}
/* Read as many packets as possible */
nread = read(mouse_fd, &mousebuf[start], BUFSIZ-start);
if ( nread < 0 ) {
return;
}
nread += start;
#ifdef DEBUG_MOUSE
fprintf(stderr, "Read %d bytes from mouse, start = %d\n", nread, start);
#endif
for ( i=0; i<(nread-(packetsize-1)); i += packetsize ) {
switch (mouse_drv) {
case MOUSE_NONE:
break;
case MOUSE_MSC:
/* MSC protocol has 0x80 in high byte */
if ( (mousebuf[i] & 0xF8) != 0x80 ) {
/* Go to next byte */
i -= (packetsize-1);
continue;
}
/* Get current mouse state */
button = (~mousebuf[i]) & 0x07;
dx = (signed char)(mousebuf[i+1]) +
(signed char)(mousebuf[i+3]);
dy = -((signed char)(mousebuf[i+2]) +
(signed char)(mousebuf[i+4]));
break;
case MOUSE_PS2:
/* PS/2 protocol has nothing in high byte */
if ( (mousebuf[i] & 0xC0) != 0 ) {
/* Go to next byte */
i -= (packetsize-1);
continue;
}
/* Get current mouse state */
button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/
(mousebuf[i] & 0x02) >> 1 | /*Right*/
(mousebuf[i] & 0x01) << 2; /*Left*/
dx = (mousebuf[i] & 0x10) ?
mousebuf[i+1] - 256 : mousebuf[i+1];
dy = (mousebuf[i] & 0x20) ?
-(mousebuf[i+2] - 256) : -mousebuf[i+2];
break;
case MOUSE_IMPS2:
/* Get current mouse state */
button = (mousebuf[i] & 0x04) >> 1 | /*Middle*/
(mousebuf[i] & 0x02) >> 1 | /*Right*/
(mousebuf[i] & 0x01) << 2 | /*Left*/
(mousebuf[i] & 0x40) >> 3 | /* 4 */
(mousebuf[i] & 0x80) >> 3; /* 5 */
dx = (mousebuf[i] & 0x10) ?
mousebuf[i+1] - 256 : mousebuf[i+1];
dy = (mousebuf[i] & 0x20) ?
-(mousebuf[i+2] - 256) : -mousebuf[i+2];
switch (mousebuf[i+3]&0x0F) {
case 0x0E: /* DX = +1 */
case 0x02: /* DX = -1 */
break;
case 0x0F: /* DY = +1 (map button 4) */
FB_vgamousecallback(button | (1<<3),
1, 0, 0);
break;
case 0x01: /* DY = -1 (map button 5) */
FB_vgamousecallback(button | (1<<4),
1, 0, 0);
break;
}
break;
case MOUSE_MS:
/* Microsoft protocol has 0x40 in high byte */
if ( (mousebuf[i] & 0x40) != 0x40 ) {
/* Go to next byte */
i -= (packetsize-1);
continue;
}
/* Get current mouse state */
button = ((mousebuf[i] & 0x20) >> 3) |
((mousebuf[i] & 0x10) >> 4);
dx = (signed char)(((mousebuf[i] & 0x03) << 6) |
(mousebuf[i + 1] & 0x3F));
dy = (signed char)(((mousebuf[i] & 0x0C) << 4) |
(mousebuf[i + 2] & 0x3F));
break;
case MOUSE_BM:
/* BusMouse protocol has 0xF8 in high byte */
if ( (mousebuf[i] & 0xF8) != 0x80 ) {
/* Go to next byte */
i -= (packetsize-1);
continue;
}
/* Get current mouse state */
button = (~mousebuf[i]) & 0x07;
dx = (signed char)mousebuf[i+1];
dy = -(signed char)mousebuf[i+2];
break;
default:
/* Uh oh.. */
dx = 0;
dy = 0;
break;
}
FB_vgamousecallback(button, relative, dx, dy);
}
if ( i < nread ) {
SDL_memcpy(mousebuf, &mousebuf[i], (nread-i));
start = (nread-i);
} else {
start = 0;
}
return;
}
/* Handle switching to another VC, returns when our VC is back */
static void switch_vt_prep(_THIS)
{
SDL_Surface *screen = SDL_VideoSurface;
SDL_PrivateAppActive(0, (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS));
/* Save the contents of the screen, and go to text mode */
wait_idle(this);
screen_arealen = ((screen->h + (2*this->offset_y)) * screen->pitch);
screen_contents = (Uint8 *)SDL_malloc(screen_arealen);
if ( screen_contents ) {
SDL_memcpy(screen_contents, screen->pixels, screen_arealen);
}
FB_SavePaletteTo(this, 256, screen_palette);
ioctl(console_fd, FBIOGET_VSCREENINFO, &screen_vinfo);
ioctl(keyboard_fd, KDSETMODE, KD_TEXT);
ioctl(keyboard_fd, VT_UNLOCKSWITCH, 1);
}
static void switch_vt_done(_THIS)
{
SDL_Surface *screen = SDL_VideoSurface;
/* Restore graphics mode and the contents of the screen */
ioctl(keyboard_fd, VT_LOCKSWITCH, 1);
ioctl(keyboard_fd, KDSETMODE, KD_GRAPHICS);
ioctl(console_fd, FBIOPUT_VSCREENINFO, &screen_vinfo);
FB_RestorePaletteFrom(this, 256, screen_palette);
if ( screen_contents ) {
SDL_memcpy(screen->pixels, screen_contents, screen_arealen);
SDL_free(screen_contents);
screen_contents = NULL;
}
/* Get updates to the shadow surface while switched away */
if ( SDL_ShadowSurface ) {
SDL_UpdateRect(SDL_ShadowSurface, 0, 0, 0, 0);
}
SDL_PrivateAppActive(1, (SDL_APPACTIVE|SDL_APPINPUTFOCUS|SDL_APPMOUSEFOCUS));
}
static void switch_vt(_THIS, unsigned short which)
{
struct vt_stat vtstate;
/* Figure out whether or not we're switching to a new console */
if ( (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) < 0) ||
(which == vtstate.v_active) ) {
return;
}
/* New console, switch to it */
SDL_mutexP(hw_lock);
switch_vt_prep(this);
if ( ioctl(keyboard_fd, VT_ACTIVATE, which) == 0 ) {
ioctl(keyboard_fd, VT_WAITACTIVE, which);
switched_away = 1;
} else {
switch_vt_done(this);
}
SDL_mutexV(hw_lock);
}
static void handle_keyboard(_THIS)
{
unsigned char keybuf[BUFSIZ];
int i, nread;
int pressed;
int scancode;
SDL_keysym keysym;
nread = read(keyboard_fd, keybuf, BUFSIZ);
for ( i=0; i<nread; ++i ) {
scancode = keybuf[i] & 0x7F;
if ( keybuf[i] & 0x80 ) {
pressed = SDL_RELEASED;
} else {
pressed = SDL_PRESSED;
}
TranslateKey(scancode, &keysym);
/* Handle Ctrl-Alt-FN for vt switch */
switch (keysym.sym) {
case SDLK_F1:
case SDLK_F2:
case SDLK_F3:
case SDLK_F4:
case SDLK_F5:
case SDLK_F6:
case SDLK_F7:
case SDLK_F8:
case SDLK_F9:
case SDLK_F10:
case SDLK_F11:
case SDLK_F12:
if ( (SDL_GetModState() & KMOD_CTRL) &&
(SDL_GetModState() & KMOD_ALT) ) {
if ( pressed ) {
switch_vt(this, (keysym.sym-SDLK_F1)+1);
}
break;
}
/* Fall through to normal processing */
default:
posted += SDL_PrivateKeyboard(pressed, &keysym);
break;
}
}
}
void FB_PumpEvents(_THIS)
{
fd_set fdset;
int max_fd;
static struct timeval zero;
do {
if ( switched_away ) {
struct vt_stat vtstate;
SDL_mutexP(hw_lock);
if ( (ioctl(keyboard_fd, VT_GETSTATE, &vtstate) == 0) &&
vtstate.v_active == current_vt ) {
switched_away = 0;
switch_vt_done(this);
}
SDL_mutexV(hw_lock);
}
posted = 0;
FD_ZERO(&fdset);
max_fd = 0;
if ( keyboard_fd >= 0 ) {
FD_SET(keyboard_fd, &fdset);
if ( max_fd < keyboard_fd ) {
max_fd = keyboard_fd;
}
}
if ( mouse_fd >= 0 ) {
FD_SET(mouse_fd, &fdset);
if ( max_fd < mouse_fd ) {
max_fd = mouse_fd;
}
}
if ( select(max_fd+1, &fdset, NULL, NULL, &zero) > 0 ) {
if ( keyboard_fd >= 0 ) {
if ( FD_ISSET(keyboard_fd, &fdset) ) {
handle_keyboard(this);
}
}
if ( mouse_fd >= 0 ) {
if ( FD_ISSET(mouse_fd, &fdset) ) {
handle_mouse(this);
}
}
}
} while ( posted );
}
void FB_InitOSKeymap(_THIS)
{
int i;
/* Initialize the Linux key translation table */
/* First get the ascii keys and others not well handled */
for (i=0; i<SDL_arraysize(keymap); ++i) {
switch(i) {
/* These aren't handled by the x86 kernel keymapping (?) */
case SCANCODE_PRINTSCREEN:
keymap[i] = SDLK_PRINT;
break;
case SCANCODE_BREAK:
keymap[i] = SDLK_BREAK;
break;
case SCANCODE_BREAK_ALTERNATIVE:
keymap[i] = SDLK_PAUSE;
break;
case SCANCODE_LEFTSHIFT:
keymap[i] = SDLK_LSHIFT;
break;
case SCANCODE_RIGHTSHIFT:
keymap[i] = SDLK_RSHIFT;
break;
case SCANCODE_LEFTCONTROL:
keymap[i] = SDLK_LCTRL;
break;
case SCANCODE_RIGHTCONTROL:
keymap[i] = SDLK_RCTRL;
break;
case SCANCODE_RIGHTWIN:
keymap[i] = SDLK_RSUPER;
break;
case SCANCODE_LEFTWIN:
keymap[i] = SDLK_LSUPER;
break;
case SCANCODE_LEFTALT:
keymap[i] = SDLK_LALT;
break;
case SCANCODE_RIGHTALT:
keymap[i] = SDLK_RALT;
break;
case 127:
keymap[i] = SDLK_MENU;
break;
/* this should take care of all standard ascii keys */
default:
keymap[i] = KVAL(vga_keymap[0][i]);
break;
}
}
for (i=0; i<SDL_arraysize(keymap); ++i) {
switch(keymap_temp[i]) {
case K_F1: keymap[i] = SDLK_F1; break;
case K_F2: keymap[i] = SDLK_F2; break;
case K_F3: keymap[i] = SDLK_F3; break;
case K_F4: keymap[i] = SDLK_F4; break;
case K_F5: keymap[i] = SDLK_F5; break;
case K_F6: keymap[i] = SDLK_F6; break;
case K_F7: keymap[i] = SDLK_F7; break;
case K_F8: keymap[i] = SDLK_F8; break;
case K_F9: keymap[i] = SDLK_F9; break;
case K_F10: keymap[i] = SDLK_F10; break;
case K_F11: keymap[i] = SDLK_F11; break;
case K_F12: keymap[i] = SDLK_F12; break;
case K_DOWN: keymap[i] = SDLK_DOWN; break;
case K_LEFT: keymap[i] = SDLK_LEFT; break;
case K_RIGHT: keymap[i] = SDLK_RIGHT; break;
case K_UP: keymap[i] = SDLK_UP; break;
case K_P0: keymap[i] = SDLK_KP0; break;
case K_P1: keymap[i] = SDLK_KP1; break;
case K_P2: keymap[i] = SDLK_KP2; break;
case K_P3: keymap[i] = SDLK_KP3; break;
case K_P4: keymap[i] = SDLK_KP4; break;
case K_P5: keymap[i] = SDLK_KP5; break;
case K_P6: keymap[i] = SDLK_KP6; break;
case K_P7: keymap[i] = SDLK_KP7; break;
case K_P8: keymap[i] = SDLK_KP8; break;
case K_P9: keymap[i] = SDLK_KP9; break;
case K_PPLUS: keymap[i] = SDLK_KP_PLUS; break;
case K_PMINUS: keymap[i] = SDLK_KP_MINUS; break;
case K_PSTAR: keymap[i] = SDLK_KP_MULTIPLY; break;
case K_PSLASH: keymap[i] = SDLK_KP_DIVIDE; break;
case K_PENTER: keymap[i] = SDLK_KP_ENTER; break;
case K_PDOT: keymap[i] = SDLK_KP_PERIOD; break;
case K_SHIFT: if ( keymap[i] != SDLK_RSHIFT )
keymap[i] = SDLK_LSHIFT;
break;
case K_SHIFTL: keymap[i] = SDLK_LSHIFT; break;
case K_SHIFTR: keymap[i] = SDLK_RSHIFT; break;
case K_CTRL: if ( keymap[i] != SDLK_RCTRL )
keymap[i] = SDLK_LCTRL;
break;
case K_CTRLL: keymap[i] = SDLK_LCTRL; break;
case K_CTRLR: keymap[i] = SDLK_RCTRL; break;
case K_ALT: keymap[i] = SDLK_LALT; break;
case K_ALTGR: keymap[i] = SDLK_RALT; break;
case K_INSERT: keymap[i] = SDLK_INSERT; break;
case K_REMOVE: keymap[i] = SDLK_DELETE; break;
case K_PGUP: keymap[i] = SDLK_PAGEUP; break;
case K_PGDN: keymap[i] = SDLK_PAGEDOWN; break;
case K_FIND: keymap[i] = SDLK_HOME; break;
case K_SELECT: keymap[i] = SDLK_END; break;
case K_NUM: keymap[i] = SDLK_NUMLOCK; break;
case K_CAPS: keymap[i] = SDLK_CAPSLOCK; break;
case K_F13: keymap[i] = SDLK_PRINT; break;
case K_HOLD: keymap[i] = SDLK_SCROLLOCK; break;
case K_PAUSE: keymap[i] = SDLK_PAUSE; break;
case 127: keymap[i] = SDLK_BACKSPACE; break;
default: break;
}
}
}
static SDL_keysym *TranslateKey(int scancode, SDL_keysym *keysym)
{
/* Set the keysym information */
keysym->scancode = scancode;
keysym->sym = keymap[scancode];
keysym->mod = KMOD_NONE;
/* If UNICODE is on, get the UNICODE value for the key */
keysym->unicode = 0;
if ( SDL_TranslateUNICODE ) {
int map;
SDLMod modstate;
modstate = SDL_GetModState();
map = 0;
if ( modstate & KMOD_SHIFT ) {
map |= (1<<KG_SHIFT);
}
if ( modstate & KMOD_CTRL ) {
map |= (1<<KG_CTRL);
}
if ( modstate & KMOD_LALT ) {
map |= (1<<KG_ALT);
}
if ( modstate & KMOD_RALT ) {
map |= (1<<KG_ALTGR);
}
if ( KTYP(vga_keymap[map][scancode]) == KT_LETTER ) {
if ( modstate & KMOD_CAPS ) {
map ^= (1<<KG_SHIFT);
}
}
if ( KTYP(vga_keymap[map][scancode]) == KT_PAD ) {
if ( modstate & KMOD_NUM ) {
keysym->unicode=KVAL(vga_keymap[map][scancode]);
}
} else {
keysym->unicode = KVAL(vga_keymap[map][scancode]);
}
}
return(keysym);
}
| lgpl-2.1 |
labatrockwell/libwebsockets | win32port/zlib/trees.c | 76 | 46486 | /* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-2010 Jean-loup Gailly
* detect_data_type() function provided freely by Cosmin Truta, 2006
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/*
* ALGORITHM
*
* The "deflation" process uses several Huffman trees. The more
* common source values are represented by shorter bit sequences.
*
* Each code tree is stored in a compressed form which is itself
* a Huffman encoding of the lengths of all the code strings (in
* ascending order by source values). The actual code strings are
* reconstructed from the lengths in the inflate process, as described
* in the deflate specification.
*
* REFERENCES
*
* Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
* Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
*
* Storer, James A.
* Data Compression: Methods and Theory, pp. 49-50.
* Computer Science Press, 1988. ISBN 0-7167-8156-5.
*
* Sedgewick, R.
* Algorithms, p290.
* Addison-Wesley, 1983. ISBN 0-201-06672-6.
*/
/* @(#) $Id$ */
/* #define GEN_TREES_H */
#include "deflate.h"
#ifdef DEBUG
# include <ctype.h>
#endif
/* ===========================================================================
* Constants
*/
#define MAX_BL_BITS 7
/* Bit length codes must not exceed MAX_BL_BITS bits */
#define END_BLOCK 256
/* end of block literal code */
#define REP_3_6 16
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
#define REPZ_3_10 17
/* repeat a zero length 3-10 times (3 bits of repeat count) */
#define REPZ_11_138 18
/* repeat a zero length 11-138 times (7 bits of repeat count) */
local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
= {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
local const int extra_dbits[D_CODES] /* extra bits for each distance code */
= {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
= {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
local const uch bl_order[BL_CODES]
= {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
#define Buf_size (8 * 2*sizeof(char))
/* Number of bits used within bi_buf. (bi_buf might be implemented on
* more than 16 bits on some systems.)
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
#define DIST_CODE_LEN 512 /* see definition of array dist_code below */
#if defined(GEN_TREES_H) || !defined(STDC)
/* non ANSI compilers may not accept trees.h */
local ct_data static_ltree[L_CODES+2];
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
local ct_data static_dtree[D_CODES];
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
uch _dist_code[DIST_CODE_LEN];
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
uch _length_code[MAX_MATCH-MIN_MATCH+1];
/* length code for each normalized match length (0 == MIN_MATCH) */
local int base_length[LENGTH_CODES];
/* First normalized length for each code (0 = MIN_MATCH) */
local int base_dist[D_CODES];
/* First normalized distance for each code (0 = distance of 1) */
#else
# include "trees.h"
#endif /* GEN_TREES_H */
struct static_tree_desc_s {
const ct_data *static_tree; /* static tree or NULL */
const intf *extra_bits; /* extra bits for each code or NULL */
int extra_base; /* base index for extra_bits */
int elems; /* max number of elements in the tree */
int max_length; /* max bit length for the codes */
};
local static_tree_desc static_l_desc =
{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
local static_tree_desc static_d_desc =
{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
local static_tree_desc static_bl_desc =
{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
/* ===========================================================================
* Local (static) routines in this file.
*/
local void tr_static_init OF((void));
local void init_block OF((deflate_state *s));
local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
local void build_tree OF((deflate_state *s, tree_desc *desc));
local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
local int build_bl_tree OF((deflate_state *s));
local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
int blcodes));
local void compress_block OF((deflate_state *s, ct_data *ltree,
ct_data *dtree));
local int detect_data_type OF((deflate_state *s));
local unsigned bi_reverse OF((unsigned value, int length));
local void bi_windup OF((deflate_state *s));
local void bi_flush OF((deflate_state *s));
local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
int header));
#ifdef GEN_TREES_H
local void gen_trees_header OF((void));
#endif
#ifndef DEBUG
# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
/* Send a code of the given tree. c and tree must not have side effects */
#else /* DEBUG */
# define send_code(s, c, tree) \
{ if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
send_bits(s, tree[c].Code, tree[c].Len); }
#endif
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
#define put_short(s, w) { \
put_byte(s, (uch)((w) & 0xff)); \
put_byte(s, (uch)((ush)(w) >> 8)); \
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
#ifdef DEBUG
local void send_bits OF((deflate_state *s, int value, int length));
local void send_bits(s, value, length)
deflate_state *s;
int value; /* value to send */
int length; /* number of bits */
{
Tracevv((stderr," l %2d v %4x ", length, value));
Assert(length > 0 && length <= 15, "invalid length");
s->bits_sent += (ulg)length;
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if (s->bi_valid > (int)Buf_size - length) {
s->bi_buf |= (ush)value << s->bi_valid;
put_short(s, s->bi_buf);
s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
s->bi_valid += length - Buf_size;
} else {
s->bi_buf |= (ush)value << s->bi_valid;
s->bi_valid += length;
}
}
#else /* !DEBUG */
#define send_bits(s, value, length) \
{ int len = length;\
if (s->bi_valid > (int)Buf_size - len) {\
int val = value;\
s->bi_buf |= (ush)val << s->bi_valid;\
put_short(s, s->bi_buf);\
s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
s->bi_valid += len - Buf_size;\
} else {\
s->bi_buf |= (ush)(value) << s->bi_valid;\
s->bi_valid += len;\
}\
}
#endif /* DEBUG */
/* the arguments must not have side effects */
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
local void tr_static_init()
{
#if defined(GEN_TREES_H) || !defined(STDC)
static int static_init_done = 0;
int n; /* iterates over tree elements */
int bits; /* bit counter */
int length; /* length value */
int code; /* code value */
int dist; /* distance index */
ush bl_count[MAX_BITS+1];
/* number of codes at each bit length for an optimal tree */
if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = (uch)code;
}
}
Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = (uch)code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for ( ; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = (uch)code;
}
}
Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
n = 0;
while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n].Len = 5;
static_dtree[n].Code = bi_reverse((unsigned)n, 5);
}
static_init_done = 1;
# ifdef GEN_TREES_H
gen_trees_header();
# endif
#endif /* defined(GEN_TREES_H) || !defined(STDC) */
}
/* ===========================================================================
* Genererate the file trees.h describing the static trees.
*/
#ifdef GEN_TREES_H
# ifndef DEBUG
# include <stdio.h>
# endif
# define SEPARATOR(i, last, width) \
((i) == (last)? "\n};\n\n" : \
((i) % (width) == (width)-1 ? ",\n" : ", "))
void gen_trees_header()
{
FILE *header = fopen("trees.h", "w");
int i;
Assert (header != NULL, "Can't open trees.h");
fprintf(header,
"/* header created automatically with -DGEN_TREES_H */\n\n");
fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
for (i = 0; i < L_CODES+2; i++) {
fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
}
fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
}
fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
for (i = 0; i < DIST_CODE_LEN; i++) {
fprintf(header, "%2u%s", _dist_code[i],
SEPARATOR(i, DIST_CODE_LEN-1, 20));
}
fprintf(header,
"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
fprintf(header, "%2u%s", _length_code[i],
SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
}
fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
for (i = 0; i < LENGTH_CODES; i++) {
fprintf(header, "%1u%s", base_length[i],
SEPARATOR(i, LENGTH_CODES-1, 20));
}
fprintf(header, "local const int base_dist[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) {
fprintf(header, "%5u%s", base_dist[i],
SEPARATOR(i, D_CODES-1, 10));
}
fclose(header);
}
#endif /* GEN_TREES_H */
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
void ZLIB_INTERNAL _tr_init(s)
deflate_state *s;
{
tr_static_init();
s->l_desc.dyn_tree = s->dyn_ltree;
s->l_desc.stat_desc = &static_l_desc;
s->d_desc.dyn_tree = s->dyn_dtree;
s->d_desc.stat_desc = &static_d_desc;
s->bl_desc.dyn_tree = s->bl_tree;
s->bl_desc.stat_desc = &static_bl_desc;
s->bi_buf = 0;
s->bi_valid = 0;
s->last_eob_len = 8; /* enough lookahead for inflate */
#ifdef DEBUG
s->compressed_len = 0L;
s->bits_sent = 0L;
#endif
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Initialize a new block.
*/
local void init_block(s)
deflate_state *s;
{
int n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
s->dyn_ltree[END_BLOCK].Freq = 1;
s->opt_len = s->static_len = 0L;
s->last_lit = s->matches = 0;
}
#define SMALLEST 1
/* Index within the heap array of least frequent node in the Huffman tree */
/* ===========================================================================
* Remove the smallest element from the heap and recreate the heap with
* one less element. Updates heap and heap_len.
*/
#define pqremove(s, tree, top) \
{\
top = s->heap[SMALLEST]; \
s->heap[SMALLEST] = s->heap[s->heap_len--]; \
pqdownheap(s, tree, SMALLEST); \
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
#define smaller(tree, n, m, depth) \
(tree[n].Freq < tree[m].Freq || \
(tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
local void pqdownheap(s, tree, k)
deflate_state *s;
ct_data *tree; /* the tree to restore */
int k; /* node to move down */
{
int v = s->heap[k];
int j = k << 1; /* left son of k */
while (j <= s->heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s->heap_len &&
smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s->heap[j], s->depth)) break;
/* Exchange v with the smallest son */
s->heap[k] = s->heap[j]; k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s->heap[k] = v;
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
local void gen_bitlen(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
int max_code = desc->max_code;
const ct_data *stree = desc->stat_desc->static_tree;
const intf *extra = desc->stat_desc->extra_bits;
int base = desc->stat_desc->extra_base;
int max_length = desc->stat_desc->max_length;
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int xbits; /* extra bits */
ush f; /* frequency */
int overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
n = s->heap[h];
bits = tree[tree[n].Dad].Len + 1;
if (bits > max_length) bits = max_length, overflow++;
tree[n].Len = (ush)bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) continue; /* not a leaf node */
s->bl_count[bits]++;
xbits = 0;
if (n >= base) xbits = extra[n-base];
f = tree[n].Freq;
s->opt_len += (ulg)f * (bits + xbits);
if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
}
if (overflow == 0) return;
Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s->bl_count[bits] == 0) bits--;
s->bl_count[bits]--; /* move one leaf down the tree */
s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
s->bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits != 0; bits--) {
n = s->bl_count[bits];
while (n != 0) {
m = s->heap[--h];
if (m > max_code) continue;
if ((unsigned) tree[m].Len != (unsigned) bits) {
Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s->opt_len += ((long)bits - (long)tree[m].Len)
*(long)tree[m].Freq;
tree[m].Len = (ush)bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
local void gen_codes (tree, max_code, bl_count)
ct_data *tree; /* the tree to decorate */
int max_code; /* largest code with non zero frequency */
ushf *bl_count; /* number of codes at each bit length */
{
ush next_code[MAX_BITS+1]; /* next code value for each bit length */
ush code = 0; /* running code value */
int bits; /* bit index */
int n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
"inconsistent bit counts");
Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n].Len;
if (len == 0) continue;
/* Now reverse the bits */
tree[n].Code = bi_reverse(next_code[len]++, len);
Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
local void build_tree(s, desc)
deflate_state *s;
tree_desc *desc; /* the tree descriptor */
{
ct_data *tree = desc->dyn_tree;
const ct_data *stree = desc->stat_desc->static_tree;
int elems = desc->stat_desc->elems;
int n, m; /* iterate over heap elements */
int max_code = -1; /* largest code with non zero frequency */
int node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s->heap_len = 0, s->heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n].Freq != 0) {
s->heap[++(s->heap_len)] = max_code = n;
s->depth[n] = 0;
} else {
tree[n].Len = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s->heap_len < 2) {
node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
tree[node].Freq = 1;
s->depth[node] = 0;
s->opt_len--; if (stree) s->static_len -= stree[node].Len;
/* node is 0 or 1 so it does not have extra bits */
}
desc->max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
pqremove(s, tree, n); /* n = node of least frequency */
m = s->heap[SMALLEST]; /* m = node of next least frequency */
s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
s->heap[--(s->heap_max)] = m;
/* Create a new node father of n and m */
tree[node].Freq = tree[n].Freq + tree[m].Freq;
s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
s->depth[n] : s->depth[m]) + 1);
tree[n].Dad = tree[m].Dad = (ush)node;
#ifdef DUMP_BL_TREE
if (tree == s->bl_tree) {
fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
}
#endif
/* and insert the new node in the heap */
s->heap[SMALLEST] = node++;
pqdownheap(s, tree, SMALLEST);
} while (s->heap_len >= 2);
s->heap[--(s->heap_max)] = s->heap[SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, (tree_desc *)desc);
/* The field len is now set, we can generate the bit codes */
gen_codes ((ct_data *)tree, max_code, s->bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
local void scan_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
if (nextlen == 0) max_count = 138, min_count = 3;
tree[max_code+1].Len = (ush)0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
s->bl_tree[curlen].Freq += count;
} else if (curlen != 0) {
if (curlen != prevlen) s->bl_tree[curlen].Freq++;
s->bl_tree[REP_3_6].Freq++;
} else if (count <= 10) {
s->bl_tree[REPZ_3_10].Freq++;
} else {
s->bl_tree[REPZ_11_138].Freq++;
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
local void send_tree (s, tree, max_code)
deflate_state *s;
ct_data *tree; /* the tree to be scanned */
int max_code; /* and its largest code of non zero frequency */
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
int curlen; /* length of current code */
int nextlen = tree[0].Len; /* length of next code */
int count = 0; /* repeat count of the current code */
int max_count = 7; /* max repeat count */
int min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen == 0) max_count = 138, min_count = 3;
for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[n+1].Len;
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(s, curlen, s->bl_tree); count--;
}
Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
}
count = 0; prevlen = curlen;
if (nextlen == 0) {
max_count = 138, min_count = 3;
} else if (curlen == nextlen) {
max_count = 6, min_count = 3;
} else {
max_count = 7, min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
local int build_bl_tree(s)
deflate_state *s;
{
int max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, (tree_desc *)(&(s->bl_desc)));
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
s->opt_len += 3*(max_blindex+1) + 5+5+4;
Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
local void send_all_trees(s, lcodes, dcodes, blcodes)
deflate_state *s;
int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
int rank; /* index in bl_order */
Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
"too many codes");
Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
}
Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Send a stored block
*/
void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
deflate_state *s;
charf *buf; /* input block */
ulg stored_len; /* length of input block */
int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */
#ifdef DEBUG
s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
s->compressed_len += (stored_len + 4) << 3;
#endif
copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
* The current inflate code requires 9 bits of lookahead. If the
* last two codes for the previous block (real code plus EOB) were coded
* on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
* the last real code. In this case we send two empty static blocks instead
* of one. (There are no problems if the previous block is stored or fixed.)
* To simplify the code, we assume the worst case of last real code encoded
* on one bit only.
*/
void ZLIB_INTERNAL _tr_align(s)
deflate_state *s;
{
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
#endif
bi_flush(s);
/* Of the 10 bits for the empty block, we have already sent
* (10 - bi_valid) bits. The lookahead for the last real code (before
* the EOB of the previous block) was thus at least one plus the length
* of the EOB plus what we have just sent of the empty static block.
*/
if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
#ifdef DEBUG
s->compressed_len += 10L;
#endif
bi_flush(s);
}
s->last_eob_len = 7;
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
deflate_state *s;
charf *buf; /* input block, or NULL if too old */
ulg stored_len; /* length of input block */
int last; /* one if this is the last block for a file */
{
ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
int max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) {
/* Check if the file is binary or text */
if (s->strm->data_type == Z_UNKNOWN)
s->strm->data_type = detect_data_type(s);
/* Construct the literal and distance trees */
build_tree(s, (tree_desc *)(&(s->l_desc)));
Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
build_tree(s, (tree_desc *)(&(s->d_desc)));
Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s->opt_len+3+7)>>3;
static_lenb = (s->static_len+3+7)>>3;
Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
s->last_lit));
if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
} else {
Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
#ifdef FORCE_STORED
if (buf != (char*)0) { /* force stored block */
#else
if (stored_len+4 <= opt_lenb && buf != (char*)0) {
/* 4: two words for the lengths */
#endif
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
#ifdef FORCE_STATIC
} else if (static_lenb >= 0) { /* force static trees */
#else
} else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
#endif
send_bits(s, (STATIC_TREES<<1)+last, 3);
compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->static_len;
#endif
} else {
send_bits(s, (DYN_TREES<<1)+last, 3);
send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
max_blindex+1);
compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
#ifdef DEBUG
s->compressed_len += 3 + s->opt_len;
#endif
}
Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
#ifdef DEBUG
s->compressed_len += 7; /* align on byte boundary */
#endif
}
Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
int ZLIB_INTERNAL _tr_tally (s, dist, lc)
deflate_state *s;
unsigned dist; /* distance of matched string */
unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
s->d_buf[s->last_lit] = (ush)dist;
s->l_buf[s->last_lit++] = (uch)lc;
if (dist == 0) {
/* lc is the unmatched char */
s->dyn_ltree[lc].Freq++;
} else {
s->matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
Assert((ush)dist < (ush)MAX_DIST(s) &&
(ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
(ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
s->dyn_dtree[d_code(dist)].Freq++;
}
#ifdef TRUNCATE_BLOCK
/* Try to guess if it is profitable to stop the current block here */
if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
/* Compute an upper bound for the compressed length */
ulg out_length = (ulg)s->last_lit*8L;
ulg in_length = (ulg)((long)s->strstart - s->block_start);
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += (ulg)s->dyn_dtree[dcode].Freq *
(5L+extra_dbits[dcode]);
}
out_length >>= 3;
Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
s->last_lit, in_length, out_length,
100L - out_length*100L/in_length));
if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
}
#endif
return (s->last_lit == s->lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
local void compress_block(s, ltree, dtree)
deflate_state *s;
ct_data *ltree; /* literal tree */
ct_data *dtree; /* distance tree */
{
unsigned dist; /* distance of matched string */
int lc; /* match length or unmatched char (if dist == 0) */
unsigned lx = 0; /* running index in l_buf */
unsigned code; /* the code to send */
int extra; /* number of extra bits to send */
if (s->last_lit != 0) do {
dist = s->d_buf[lx];
lc = s->l_buf[lx++];
if (dist == 0) {
send_code(s, lc, ltree); /* send a literal byte */
Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra != 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra != 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
"pendingBuf overflow");
} while (lx < s->last_lit);
send_code(s, END_BLOCK, ltree);
s->last_eob_len = ltree[END_BLOCK].Len;
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
local int detect_data_type(s)
deflate_state *s;
{
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
unsigned long black_mask = 0xf3ffc07fUL;
int n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>= 1)
if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
return Z_BINARY;
/* Check for textual ("white-listed") bytes. */
if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
|| s->dyn_ltree[13].Freq != 0)
return Z_TEXT;
for (n = 32; n < LITERALS; n++)
if (s->dyn_ltree[n].Freq != 0)
return Z_TEXT;
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
local unsigned bi_reverse(code, len)
unsigned code; /* the value to invert */
int len; /* its bit length */
{
register unsigned res = 0;
do {
res |= code & 1;
code >>= 1, res <<= 1;
} while (--len > 0);
return res >> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
local void bi_flush(s)
deflate_state *s;
{
if (s->bi_valid == 16) {
put_short(s, s->bi_buf);
s->bi_buf = 0;
s->bi_valid = 0;
} else if (s->bi_valid >= 8) {
put_byte(s, (Byte)s->bi_buf);
s->bi_buf >>= 8;
s->bi_valid -= 8;
}
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
local void bi_windup(s)
deflate_state *s;
{
if (s->bi_valid > 8) {
put_short(s, s->bi_buf);
} else if (s->bi_valid > 0) {
put_byte(s, (Byte)s->bi_buf);
}
s->bi_buf = 0;
s->bi_valid = 0;
#ifdef DEBUG
s->bits_sent = (s->bits_sent+7) & ~7;
#endif
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
local void copy_block(s, buf, len, header)
deflate_state *s;
charf *buf; /* the input data */
unsigned len; /* its length */
int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
s->last_eob_len = 8; /* enough lookahead for inflate */
if (header) {
put_short(s, (ush)len);
put_short(s, (ush)~len);
#ifdef DEBUG
s->bits_sent += 2*16;
#endif
}
#ifdef DEBUG
s->bits_sent += (ulg)len<<3;
#endif
while (len--) {
put_byte(s, *buf++);
}
}
| lgpl-2.1 |
jhgorse/gmog | M4/wxWidgets-3.0.2/src/msw/combobox.cpp | 122 | 22176 | /////////////////////////////////////////////////////////////////////////////
// Name: src/msw/combobox.cpp
// Purpose: wxComboBox class
// Author: Julian Smart
// Modified by:
// Created: 01/02/97
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_COMBOBOX
#include "wx/combobox.h"
#ifndef WX_PRECOMP
#include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
#include "wx/settings.h"
#include "wx/log.h"
// for wxEVT_TEXT_ENTER
#include "wx/textctrl.h"
#include "wx/app.h"
#include "wx/brush.h"
#endif
#include "wx/clipbrd.h"
#include "wx/wupdlock.h"
#include "wx/msw/private.h"
#if wxUSE_UXTHEME
#include "wx/msw/uxtheme.h"
#endif
#if wxUSE_TOOLTIPS
#include "wx/tooltip.h"
#endif // wxUSE_TOOLTIPS
// ----------------------------------------------------------------------------
// wxWin macros
// ----------------------------------------------------------------------------
BEGIN_EVENT_TABLE(wxComboBox, wxControl)
EVT_MENU(wxID_CUT, wxComboBox::OnCut)
EVT_MENU(wxID_COPY, wxComboBox::OnCopy)
EVT_MENU(wxID_PASTE, wxComboBox::OnPaste)
EVT_MENU(wxID_UNDO, wxComboBox::OnUndo)
EVT_MENU(wxID_REDO, wxComboBox::OnRedo)
EVT_MENU(wxID_CLEAR, wxComboBox::OnDelete)
EVT_MENU(wxID_SELECTALL, wxComboBox::OnSelectAll)
EVT_UPDATE_UI(wxID_CUT, wxComboBox::OnUpdateCut)
EVT_UPDATE_UI(wxID_COPY, wxComboBox::OnUpdateCopy)
EVT_UPDATE_UI(wxID_PASTE, wxComboBox::OnUpdatePaste)
EVT_UPDATE_UI(wxID_UNDO, wxComboBox::OnUpdateUndo)
EVT_UPDATE_UI(wxID_REDO, wxComboBox::OnUpdateRedo)
EVT_UPDATE_UI(wxID_CLEAR, wxComboBox::OnUpdateDelete)
EVT_UPDATE_UI(wxID_SELECTALL, wxComboBox::OnUpdateSelectAll)
END_EVENT_TABLE()
// ----------------------------------------------------------------------------
// function prototypes
// ----------------------------------------------------------------------------
LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
// ---------------------------------------------------------------------------
// global vars
// ---------------------------------------------------------------------------
// the pointer to standard radio button wnd proc
static WNDPROC gs_wndprocEdit = (WNDPROC)NULL;
// ============================================================================
// implementation
// ============================================================================
namespace
{
// Check if the given message should be forwarded from the edit control which
// is part of the combobox to wxComboBox itself. All messages generating the
// events that the code using wxComboBox could be interested in must be
// forwarded.
bool ShouldForwardFromEditToCombo(UINT message)
{
switch ( message )
{
case WM_KEYUP:
case WM_KEYDOWN:
case WM_CHAR:
case WM_SYSCHAR:
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_SETFOCUS:
case WM_KILLFOCUS:
case WM_CUT:
case WM_COPY:
case WM_PASTE:
return true;
}
return false;
}
} // anonymous namespace
// ----------------------------------------------------------------------------
// wnd proc for subclassed edit control
// ----------------------------------------------------------------------------
LRESULT APIENTRY _EXPORT wxComboEditWndProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
HWND hwndCombo = ::GetParent(hWnd);
wxWindow *win = wxFindWinFromHandle((WXHWND)hwndCombo);
if ( ShouldForwardFromEditToCombo(message) )
{
wxComboBox *combo = wxDynamicCast(win, wxComboBox);
if ( !combo )
{
// we can get WM_KILLFOCUS while our parent is already half
// destroyed and hence doesn't look like a combobx any
// longer, check for it to avoid bogus assert failures
if ( !win->IsBeingDeleted() )
{
wxFAIL_MSG( wxT("should have combo as parent") );
}
}
else if ( combo->MSWProcessEditMsg(message, wParam, lParam) )
{
// handled by parent
return 0;
}
}
else if ( message == WM_GETDLGCODE )
{
wxCHECK_MSG( win, 0, wxT("should have a parent") );
if ( win->GetWindowStyle() & wxTE_PROCESS_ENTER )
{
// need to return a custom dlg code or we'll never get it
return DLGC_WANTMESSAGE;
}
}
return ::CallWindowProc(CASTWNDPROC gs_wndprocEdit, hWnd, message, wParam, lParam);
}
// ----------------------------------------------------------------------------
// wxComboBox callbacks
// ----------------------------------------------------------------------------
WXLRESULT wxComboBox::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam)
{
// TODO: handle WM_CTLCOLOR messages from our EDIT control to be able to
// set its colour correctly (to be the same as our own one)
switch ( nMsg )
{
case WM_SIZE:
// wxStaticBox can generate this message, when modifying the control's style.
// This causes the content of the combobox to be selected, for some reason.
case WM_STYLECHANGED:
{
// combobox selection sometimes spontaneously changes when its
// size changes, restore it to the old value if necessary
if ( !GetEditHWNDIfAvailable() )
break;
long fromOld, toOld;
GetSelection(&fromOld, &toOld);
// if an editable combobox has a not empty text not from the
// list, it tries to autocomplete it from the list when it is
// resized, but we don't want this to happen as it doesn't seem
// to make any sense, so we forcefully restore the old text
wxString textOld;
if ( !HasFlag(wxCB_READONLY) && GetCurrentSelection() == -1 )
textOld = GetValue();
// eliminate flickering during following hacks
wxWindowUpdateLocker lock(this);
WXLRESULT result = wxChoice::MSWWindowProc(nMsg, wParam, lParam);
if ( !textOld.empty() && GetValue() != textOld )
SetLabel(textOld);
long fromNew, toNew;
GetSelection(&fromNew, &toNew);
if ( fromOld != fromNew || toOld != toNew )
{
SetSelection(fromOld, toOld);
}
return result;
}
}
return wxChoice::MSWWindowProc(nMsg, wParam, lParam);
}
bool wxComboBox::MSWProcessEditMsg(WXUINT msg, WXWPARAM wParam, WXLPARAM lParam)
{
switch ( msg )
{
case WM_CHAR:
// for compatibility with wxTextCtrl, generate a special message
// when Enter is pressed
switch ( wParam )
{
case VK_RETURN:
{
if (SendMessage(GetHwnd(), CB_GETDROPPEDSTATE, 0, 0))
return false;
wxCommandEvent event(wxEVT_TEXT_ENTER, m_windowId);
const int sel = GetSelection();
event.SetInt(sel);
event.SetString(GetValue());
InitCommandEventWithItems(event, sel);
if ( ProcessCommand(event) )
{
// don't let the event through to the native control
// because it doesn't need it and may generate an annoying
// beep if it gets it
return true;
}
}
break;
case VK_TAB:
// If we have wxTE_PROCESS_ENTER style, we get all char
// events, including those for TAB which are usually used
// for keyboard navigation, but we should not process them
// unless we also have wxTE_PROCESS_TAB style.
if ( !HasFlag(wxTE_PROCESS_TAB) )
{
int flags = 0;
if ( !wxIsShiftDown() )
flags |= wxNavigationKeyEvent::IsForward;
if ( wxIsCtrlDown() )
flags |= wxNavigationKeyEvent::WinChange;
if ( Navigate(flags) )
return true;
}
break;
}
}
if ( ShouldForwardFromEditToCombo(msg) )
{
// For all the messages forward from the edit control the
// result is not used.
WXLRESULT result;
return MSWHandleMessage(&result, msg, wParam, lParam);
}
return false;
}
bool wxComboBox::MSWCommand(WXUINT param, WXWORD id)
{
int sel = -1;
wxString value;
switch ( param )
{
case CBN_DROPDOWN:
// remember the last selection, just as wxChoice does
m_lastAcceptedSelection = GetCurrentSelection();
{
wxCommandEvent event(wxEVT_COMBOBOX_DROPDOWN, GetId());
event.SetEventObject(this);
ProcessCommand(event);
}
break;
case CBN_CLOSEUP:
// Do the same thing as in wxChoice but using different event type.
if ( m_pendingSelection != wxID_NONE )
{
SendSelectionChangedEvent(wxEVT_COMBOBOX);
m_pendingSelection = wxID_NONE;
}
{
wxCommandEvent event(wxEVT_COMBOBOX_CLOSEUP, GetId());
event.SetEventObject(this);
ProcessCommand(event);
}
break;
case CBN_SELENDOK:
#ifndef __SMARTPHONE__
// we need to reset this to prevent the selection from being undone
// by wxChoice, see wxChoice::MSWCommand() and comments there
m_lastAcceptedSelection = wxID_NONE;
#endif
// set these variables so that they could be also fixed in
// CBN_EDITCHANGE below
sel = GetSelection();
value = GetStringSelection();
// this string is going to become the new combobox value soon but
// we need it to be done right now, otherwise the event handler
// could get a wrong value when it calls our GetValue()
::SetWindowText(GetHwnd(), value.t_str());
SendSelectionChangedEvent(wxEVT_COMBOBOX);
// fall through: for compatibility with wxGTK, also send the text
// update event when the selection changes (this also seems more
// logical as the text does change)
case CBN_EDITCHANGE:
if ( m_allowTextEvents )
{
wxCommandEvent event(wxEVT_TEXT, GetId());
// if sel != -1, value was already initialized above
if ( sel == -1 )
{
value = wxGetWindowText(GetHwnd());
}
event.SetString(value);
InitCommandEventWithItems(event, sel);
ProcessCommand(event);
}
break;
default:
return wxChoice::MSWCommand(param, id);
}
// skip wxChoice version as it would generate its own events for
// CBN_SELENDOK and also interfere with our handling of CBN_DROPDOWN
return true;
}
bool wxComboBox::MSWShouldPreProcessMessage(WXMSG *pMsg)
{
// prevent command accelerators from stealing editing
// hotkeys when we have the focus
if (wxIsCtrlDown())
{
WPARAM vkey = pMsg->wParam;
switch (vkey)
{
case 'C':
case 'V':
case 'X':
case VK_INSERT:
case VK_DELETE:
case VK_HOME:
case VK_END:
return false;
}
}
return wxChoice::MSWShouldPreProcessMessage(pMsg);
}
WXHWND wxComboBox::GetEditHWNDIfAvailable() const
{
// FIXME-VC6: Only VC6 needs this guard, see WINVER definition in
// include/wx/msw/wrapwin.h
#if defined(WINVER) && WINVER >= 0x0500
WinStruct<COMBOBOXINFO> info;
if ( MSWGetComboBoxInfo(&info) )
return info.hwndItem;
#endif // WINVER >= 0x0500
if (HasFlag(wxCB_SIMPLE))
{
POINT pt;
pt.x = pt.y = 4;
return (WXHWND) ::ChildWindowFromPoint(GetHwnd(), pt);
}
// notice that a slightly safer alternative could be to use FindWindowEx()
// but it's not available under WinCE so just take the first child for now
// to keep one version of the code for all platforms and fix it later if
// problems are discovered
// we assume that the only child of the combobox is the edit window
return (WXHWND)::GetWindow(GetHwnd(), GW_CHILD);
}
WXHWND wxComboBox::GetEditHWND() const
{
// this function should not be called for wxCB_READONLY controls, it is
// the callers responsibility to check this
wxASSERT_MSG( !HasFlag(wxCB_READONLY),
wxT("read-only combobox doesn't have any edit control") );
WXHWND hWndEdit = GetEditHWNDIfAvailable();
wxASSERT_MSG( hWndEdit, wxT("combobox without edit control?") );
return hWndEdit;
}
wxWindow *wxComboBox::GetEditableWindow()
{
wxASSERT_MSG( !HasFlag(wxCB_READONLY),
wxT("read-only combobox doesn't have any edit control") );
return this;
}
// ----------------------------------------------------------------------------
// wxComboBox creation
// ----------------------------------------------------------------------------
bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
const wxString& value,
const wxPoint& pos,
const wxSize& size,
int n, const wxString choices[],
long style,
const wxValidator& validator,
const wxString& name)
{
// pretend that wxComboBox is hidden while it is positioned and resized and
// show it only right before leaving this method because otherwise there is
// some noticeable flicker while the control rearranges itself
m_isShown = false;
if ( !CreateAndInit(parent, id, pos, size, n, choices, style,
validator, name) )
return false;
// we shouldn't call SetValue() for an empty string because this would
// (correctly) result in an assert with a read only combobox and is useless
// for the other ones anyhow
if ( !value.empty() )
SetValue(value);
// a (not read only) combobox is, in fact, 2 controls: the combobox itself
// and an edit control inside it and if we want to catch events from this
// edit control, we must subclass it as well
if ( !(style & wxCB_READONLY) )
{
gs_wndprocEdit = wxSetWindowProc((HWND)GetEditHWND(), wxComboEditWndProc);
}
// and finally, show the control
Show(true);
return true;
}
bool wxComboBox::Create(wxWindow *parent, wxWindowID id,
const wxString& value,
const wxPoint& pos,
const wxSize& size,
const wxArrayString& choices,
long style,
const wxValidator& validator,
const wxString& name)
{
wxCArrayString chs(choices);
return Create(parent, id, value, pos, size, chs.GetCount(),
chs.GetStrings(), style, validator, name);
}
WXDWORD wxComboBox::MSWGetStyle(long style, WXDWORD *exstyle) const
{
// we never have an external border
WXDWORD msStyle = wxChoice::MSWGetStyle
(
(style & ~wxBORDER_MASK) | wxBORDER_NONE, exstyle
);
// usually WS_TABSTOP is added by wxControl::MSWGetStyle() but as we're
// created hidden (see Create() above), it is not done for us but we still
// want to have this style
msStyle |= WS_TABSTOP;
// remove the style always added by wxChoice
msStyle &= ~CBS_DROPDOWNLIST;
if ( style & wxCB_READONLY )
msStyle |= CBS_DROPDOWNLIST;
#ifndef __WXWINCE__
else if ( style & wxCB_SIMPLE )
msStyle |= CBS_SIMPLE; // A list (shown always) and edit control
#endif
else
msStyle |= CBS_DROPDOWN;
// there is no reason to not always use CBS_AUTOHSCROLL, so do use it
msStyle |= CBS_AUTOHSCROLL;
// NB: we used to also add CBS_NOINTEGRALHEIGHT here but why?
return msStyle;
}
// ----------------------------------------------------------------------------
// wxComboBox text control-like methods
// ----------------------------------------------------------------------------
wxString wxComboBox::GetValue() const
{
return HasFlag(wxCB_READONLY) ? GetStringSelection()
: wxTextEntry::GetValue();
}
void wxComboBox::SetValue(const wxString& value)
{
if ( HasFlag(wxCB_READONLY) )
SetStringSelection(value);
else
wxTextEntry::SetValue(value);
}
void wxComboBox::Clear()
{
wxChoice::Clear();
if ( !HasFlag(wxCB_READONLY) )
wxTextEntry::Clear();
}
bool wxComboBox::ContainsHWND(WXHWND hWnd) const
{
return hWnd == GetEditHWNDIfAvailable();
}
void wxComboBox::GetSelection(long *from, long *to) const
{
if ( !HasFlag(wxCB_READONLY) )
{
wxTextEntry::GetSelection(from, to);
}
else // text selection doesn't make sense for read only comboboxes
{
if ( from )
*from = -1;
if ( to )
*to = -1;
}
}
bool wxComboBox::IsEditable() const
{
return !HasFlag(wxCB_READONLY) && wxTextEntry::IsEditable();
}
// ----------------------------------------------------------------------------
// standard event handling
// ----------------------------------------------------------------------------
void wxComboBox::OnCut(wxCommandEvent& WXUNUSED(event))
{
Cut();
}
void wxComboBox::OnCopy(wxCommandEvent& WXUNUSED(event))
{
Copy();
}
void wxComboBox::OnPaste(wxCommandEvent& WXUNUSED(event))
{
Paste();
}
void wxComboBox::OnUndo(wxCommandEvent& WXUNUSED(event))
{
Undo();
}
void wxComboBox::OnRedo(wxCommandEvent& WXUNUSED(event))
{
Redo();
}
void wxComboBox::OnDelete(wxCommandEvent& WXUNUSED(event))
{
RemoveSelection();
}
void wxComboBox::OnSelectAll(wxCommandEvent& WXUNUSED(event))
{
SelectAll();
}
void wxComboBox::OnUpdateCut(wxUpdateUIEvent& event)
{
event.Enable( CanCut() );
}
void wxComboBox::OnUpdateCopy(wxUpdateUIEvent& event)
{
event.Enable( CanCopy() );
}
void wxComboBox::OnUpdatePaste(wxUpdateUIEvent& event)
{
event.Enable( CanPaste() );
}
void wxComboBox::OnUpdateUndo(wxUpdateUIEvent& event)
{
event.Enable( IsEditable() && CanUndo() );
}
void wxComboBox::OnUpdateRedo(wxUpdateUIEvent& event)
{
event.Enable( IsEditable() && CanRedo() );
}
void wxComboBox::OnUpdateDelete(wxUpdateUIEvent& event)
{
event.Enable(IsEditable() && HasSelection());
}
void wxComboBox::OnUpdateSelectAll(wxUpdateUIEvent& event)
{
event.Enable(IsEditable() && !wxTextEntry::IsEmpty());
}
#if wxUSE_TOOLTIPS
void wxComboBox::DoSetToolTip(wxToolTip *tip)
{
wxChoice::DoSetToolTip(tip);
if ( tip && !HasFlag(wxCB_READONLY) )
tip->AddOtherWindow(GetEditHWND());
}
#endif // wxUSE_TOOLTIPS
#if wxUSE_UXTHEME
bool wxComboBox::SetHint(const wxString& hintOrig)
{
wxString hint(hintOrig);
if ( wxUxThemeEngine::GetIfActive() )
{
// under XP (but not Vista) there is a bug in cue banners
// implementation for combobox edit control: the first character is
// partially chopped off, so prepend a space to make it fully visible
hint.insert(0, " ");
}
return wxTextEntry::SetHint(hint);
}
#endif // wxUSE_UXTHEME
wxSize wxComboBox::DoGetSizeFromTextSize(int xlen, int ylen) const
{
wxSize tsize( wxChoice::DoGetSizeFromTextSize(xlen, ylen) );
if ( !HasFlag(wxCB_READONLY) )
{
// Add the margins we have previously set
wxPoint marg( GetMargins() );
marg.x = wxMax(0, marg.x);
marg.y = wxMax(0, marg.y);
tsize.IncBy( marg );
}
return tsize;
}
wxWindow *wxComboBox::MSWFindItem(long id, WXHWND hWnd) const
{
// The base class version considers that any window with the same ID as
// this one must be this window itself, but this is not the case for the
// comboboxes where the native control seems to always use the ID of 1000
// for the popup listbox that it creates -- and this ID may be the same as
// our own one. So we must explicitly check the HWND value too here and
// avoid eating the events from the listbox as otherwise it is rendered
// inoperative, see #15647.
if ( id == GetId() && hWnd && hWnd != GetHWND() )
{
// Must be the case described above.
return NULL;
}
return wxChoice::MSWFindItem(id, hWnd);
}
#endif // wxUSE_COMBOBOX
| lgpl-2.1 |
brammittendorff/PF_RING | linux-3.16.7-ckt9/drivers/net/wireless/mwifiex/11h.c | 125 | 3615 | /*
* Marvell Wireless LAN device driver: 802.11h
*
* Copyright (C) 2013, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. 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 "main.h"
#include "fw.h"
/* This function appends 11h info to a buffer while joining an
* infrastructure BSS
*/
static void
mwifiex_11h_process_infra_join(struct mwifiex_private *priv, u8 **buffer,
struct mwifiex_bssdescriptor *bss_desc)
{
struct mwifiex_ie_types_header *ie_header;
struct mwifiex_ie_types_pwr_capability *cap;
struct mwifiex_ie_types_local_pwr_constraint *constraint;
struct ieee80211_supported_band *sband;
u8 radio_type;
int i;
if (!buffer || !(*buffer))
return;
radio_type = mwifiex_band_to_radio_type((u8) bss_desc->bss_band);
sband = priv->wdev->wiphy->bands[radio_type];
cap = (struct mwifiex_ie_types_pwr_capability *)*buffer;
cap->header.type = cpu_to_le16(WLAN_EID_PWR_CAPABILITY);
cap->header.len = cpu_to_le16(2);
cap->min_pwr = 0;
cap->max_pwr = 0;
*buffer += sizeof(*cap);
constraint = (struct mwifiex_ie_types_local_pwr_constraint *)*buffer;
constraint->header.type = cpu_to_le16(WLAN_EID_PWR_CONSTRAINT);
constraint->header.len = cpu_to_le16(2);
constraint->chan = bss_desc->channel;
constraint->constraint = bss_desc->local_constraint;
*buffer += sizeof(*constraint);
ie_header = (struct mwifiex_ie_types_header *)*buffer;
ie_header->type = cpu_to_le16(TLV_TYPE_PASSTHROUGH);
ie_header->len = cpu_to_le16(2 * sband->n_channels + 2);
*buffer += sizeof(*ie_header);
*(*buffer)++ = WLAN_EID_SUPPORTED_CHANNELS;
*(*buffer)++ = 2 * sband->n_channels;
for (i = 0; i < sband->n_channels; i++) {
*(*buffer)++ = ieee80211_frequency_to_channel(
sband->channels[i].center_freq);
*(*buffer)++ = 1; /* one channel in the subband */
}
}
/* Enable or disable the 11h extensions in the firmware */
static int mwifiex_11h_activate(struct mwifiex_private *priv, bool flag)
{
u32 enable = flag;
return mwifiex_send_cmd(priv, HostCmd_CMD_802_11_SNMP_MIB,
HostCmd_ACT_GEN_SET, DOT11H_I, &enable, true);
}
/* This functions processes TLV buffer for a pending BSS Join command.
*
* Activate 11h functionality in the firmware if the spectrum management
* capability bit is found in the network we are joining. Also, necessary
* TLVs are set based on requested network's 11h capability.
*/
void mwifiex_11h_process_join(struct mwifiex_private *priv, u8 **buffer,
struct mwifiex_bssdescriptor *bss_desc)
{
if (bss_desc->sensed_11h) {
/* Activate 11h functions in firmware, turns on capability
* bit
*/
mwifiex_11h_activate(priv, true);
bss_desc->cap_info_bitmap |= WLAN_CAPABILITY_SPECTRUM_MGMT;
mwifiex_11h_process_infra_join(priv, buffer, bss_desc);
} else {
/* Deactivate 11h functions in the firmware */
mwifiex_11h_activate(priv, false);
bss_desc->cap_info_bitmap &= ~WLAN_CAPABILITY_SPECTRUM_MGMT;
}
}
| lgpl-2.1 |
ForestNymph/Arduino_sources | hardware/arduino/sam/system/CMSIS/CMSIS/DSP_Lib/Examples/arm_convolution_example/system_ARMCM3.c | 1946 | 2412 | /**************************************************************************//**
* @file system_ARMCM3.c
* @brief CMSIS Cortex-M3 Device System Source File
* for CM3 Device Series
* @version V1.05
* @date 26. July 2011
*
* @note
* Copyright (C) 2010-2011 ARM Limited. All rights reserved.
*
* @par
* ARM Limited (ARM) is supplying this software for use with Cortex-M
* processor based microcontrollers. This file can be freely distributed
* within development tools that are supporting such ARM based processors.
*
* @par
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
******************************************************************************/
#include "ARMCM3.h"
/*----------------------------------------------------------------------------
Define clocks
*----------------------------------------------------------------------------*/
#define __HSI ( 8000000UL)
#define __XTAL (12000000UL) /* Oscillator frequency */
#define __SYSTEM_CLOCK (4*__XTAL)
/*----------------------------------------------------------------------------
Clock Variable definitions
*----------------------------------------------------------------------------*/
uint32_t SystemCoreClock = __SYSTEM_CLOCK;/*!< System Clock Frequency (Core Clock)*/
/*----------------------------------------------------------------------------
Clock functions
*----------------------------------------------------------------------------*/
void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */
{
SystemCoreClock = __SYSTEM_CLOCK;
}
/**
* Initialize the system
*
* @param none
* @return none
*
* @brief Setup the microcontroller system.
* Initialize the System.
*/
void SystemInit (void)
{
SystemCoreClock = __SYSTEM_CLOCK;
#ifdef __USE_GPIO
ARM_GPIO0->DATA[0].WORD = 0;
ARM_GPIO0->IE = 0;
ARM_GPIO0->DIR = 0xff83;
ARM_GPIO1->DATA[0].WORD = 0;
ARM_GPIO1->IE = 0;
ARM_GPIO1->DIR = 0;
ARM_GPIO2->DATA[0].WORD = 0;
ARM_GPIO2->IE = 0;
ARM_GPIO2->DIR = 0;
#endif
}
| lgpl-2.1 |
PaulStoffregen/Arduino-1.6.4-Teensyduino | hardware/arduino/sam/system/libsam/source/usart.c | 155 | 11846 | /* ----------------------------------------------------------------------------
* SAM Software Package License
* ----------------------------------------------------------------------------
* Copyright (c) 2011-2012, Atmel Corporation
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following condition is met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: 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
* 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.
* ----------------------------------------------------------------------------
*/
/** \addtogroup usart_module Working with USART
* The USART driver provides the interface to configure and use the USART peripheral.\n
*
* The USART supports several kinds of comminication modes such as full-duplex asynchronous/
* synchronous serial commnunication,RS485 with driver control signal,ISO7816,SPI and Test modes.
*
* To start a USART transfer with \ref AT91SAM3S_PDC "PDC" support, the user could follow these steps:
* <ul>
* <li> Configure USART with expected mode and baudrate(see \ref USART_Configure), which could be done by:
* -# Resetting and disabling transmitter and receiver by setting US_CR(Control Register). </li>
* -# Conifguring the USART in a specific mode by setting USART_MODE bits in US_MR(Mode Register) </li>
* -# Setting baudrate which is different from mode to mode.
</li>
* <li> Enable transmitter or receiver respectively by set US_CR_TXEN or US_CR_RXEN in US_CR.</li>
* <li> Read from or write to the peripheral with \ref USART_ReadBuffer or \ref USART_WriteBuffer.
These operations could be done by polling or interruption. </li>
* <li> For polling, check the status bit US_CSR_ENDRX/US_CSR_RXBUFF (READ) or US_CSR_ENDTX/
US_CSR_TXBUFE (WRITE). </li>
* <li> For interruption,"enable" the status bit through US_IER and
realize the hanler with USARTx_IrqHandler according to IRQ vector
table which is defined in board_cstartup_<toolchain>.c
To enable the interruption of USART,it should be configured with priority and enabled first through
NVIC .</li>
* </ul>
*
* For more accurate information, please look at the USART section of the
* Datasheet.
*
* Related files :\n
* \ref usart.c\n
* \ref usart.h\n
*/
/**
* \file
*
* Implementation of USART (Universal Synchronous Asynchronous Receiver Transmitter)
* controller.
*
*/
/*------------------------------------------------------------------------------
* Headers
*------------------------------------------------------------------------------*/
#include "chip.h"
#include <assert.h>
#include <string.h>
/*----------------------------------------------------------------------------
* Local definitions
*----------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------
* Exported functions
*------------------------------------------------------------------------------*/
/**
* \brief Configures an USART peripheral with the specified parameters.
*
*
* \param usart Pointer to the USART peripheral to configure.
* \param mode Desired value for the USART mode register (see the datasheet).
* \param baudrate Baudrate at which the USART should operate (in Hz).
* \param masterClock Frequency of the system master clock (in Hz).
*/
void USART_Configure(Usart *usart,
uint32_t mode,
uint32_t baudrate,
uint32_t masterClock)
{
/* Reset and disable receiver & transmitter*/
usart->US_CR = US_CR_RSTRX | US_CR_RSTTX
| US_CR_RXDIS | US_CR_TXDIS;
/* Configure mode*/
usart->US_MR = mode;
/* Configure baudrate*/
/* Asynchronous, no oversampling*/
if ( ((mode & US_MR_SYNC) == 0) && ((mode & US_MR_OVER) == 0) )
{
usart->US_BRGR = (masterClock / baudrate) / 16;
}
if( ((mode & US_MR_USART_MODE_SPI_MASTER) == US_MR_USART_MODE_SPI_MASTER)
|| ((mode & US_MR_SYNC) == US_MR_SYNC))
{
if( (mode & US_MR_USCLKS_Msk) == US_MR_USCLKS_MCK)
{
usart->US_BRGR = masterClock / baudrate;
}
else
{
if ( (mode & US_MR_USCLKS_DIV) == US_MR_USCLKS_DIV)
{
usart->US_BRGR = masterClock / baudrate / 8;
}
}
}
/* TODO other modes*/
}
/**
* \brief Enables or disables the transmitter of an USART peripheral.
*
*
* \param usart Pointer to an USART peripheral
* \param enabled If true, the transmitter is enabled; otherwise it is
* disabled.
*/
void USART_SetTransmitterEnabled(Usart *usart, uint8_t enabled)
{
if (enabled) {
usart->US_CR = US_CR_TXEN;
}
else {
usart->US_CR = US_CR_TXDIS;
}
}
/**
* \brief Enables or disables the receiver of an USART peripheral
*
*
* \param usart Pointer to an USART peripheral
* \param enabled If true, the receiver is enabled; otherwise it is disabled.
*/
void USART_SetReceiverEnabled(Usart *usart,
uint8_t enabled)
{
if (enabled) {
usart->US_CR = US_CR_RXEN;
}
else {
usart->US_CR = US_CR_RXDIS;
}
}
/**
* \brief Sends one packet of data through the specified USART peripheral. This
* function operates synchronously, so it only returns when the data has been
* actually sent.
*
*
* \param usart Pointer to an USART peripheral.
* \param data Data to send including 9nth bit and sync field if necessary (in
* the same format as the US_THR register in the datasheet).
* \param timeOut Time out value (0 = no timeout).
*/
void USART_Write(
Usart *usart,
uint16_t data,
volatile uint32_t timeOut)
{
if (timeOut == 0) {
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0);
}
else {
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0) {
if (timeOut == 0) {
// TRACE_ERROR("USART_Write: Timed out.\n\r");
return;
}
timeOut--;
}
}
usart->US_THR = data;
}
/**
* \brief Sends the contents of a data buffer through the specified USART peripheral.
* This function returns immediately (1 if the buffer has been queued, 0
* otherwise); poll the ENDTX and TXBUFE bits of the USART status register
* to check for the transfer completion.
*
* \param usart Pointer to an USART peripheral.
* \param buffer Pointer to the data buffer to send.
* \param size Size of the data buffer (in bytes).
*/
uint8_t USART_WriteBuffer(
Usart *usart,
void *buffer,
uint32_t size)
{
/* Check if the first PDC bank is free*/
if ((usart->US_TCR == 0) && (usart->US_TNCR == 0)) {
usart->US_TPR = (uint32_t) buffer;
usart->US_TCR = size;
usart->US_PTCR = US_PTCR_TXTEN;
return 1;
}
/* Check if the second PDC bank is free*/
else if (usart->US_TNCR == 0) {
usart->US_TNPR = (uint32_t) buffer;
usart->US_TNCR = size;
return 1;
}
else {
return 0;
}
}
/**
* \brief Reads and return a packet of data on the specified USART peripheral. This
* function operates asynchronously, so it waits until some data has been
* received.
*
* \param usart Pointer to an USART peripheral.
* \param timeOut Time out value (0 -> no timeout).
*/
uint16_t USART_Read(
Usart *usart,
volatile uint32_t timeOut)
{
if (timeOut == 0) {
while ((usart->US_CSR & US_CSR_RXRDY) == 0);
}
else {
while ((usart->US_CSR & US_CSR_RXRDY) == 0) {
if (timeOut == 0) {
// TRACE_ERROR( "USART_Read: Timed out.\n\r" ) ;
return 0;
}
timeOut--;
}
}
return usart->US_RHR;
}
/**
* \brief Reads data from an USART peripheral, filling the provided buffer until it
* becomes full. This function returns immediately with 1 if the buffer has
* been queued for transmission; otherwise 0.
*
* \param usart Pointer to an USART peripheral.
* \param buffer Pointer to the buffer where the received data will be stored.
* \param size Size of the data buffer (in bytes).
*/
uint8_t USART_ReadBuffer(Usart *usart,
void *buffer,
uint32_t size)
{
/* Check if the first PDC bank is free*/
if ((usart->US_RCR == 0) && (usart->US_RNCR == 0)) {
usart->US_RPR = (uint32_t) buffer;
usart->US_RCR = size;
usart->US_PTCR = US_PTCR_RXTEN;
return 1;
}
/* Check if the second PDC bank is free*/
else if (usart->US_RNCR == 0) {
usart->US_RNPR = (uint32_t) buffer;
usart->US_RNCR = size;
return 1;
}
else {
return 0;
}
}
/**
* \brief Returns 1 if some data has been received and can be read from an USART;
* otherwise returns 0.
*
* \param usart Pointer to an Usart instance.
*/
uint8_t USART_IsDataAvailable(Usart *usart)
{
if ((usart->US_CSR & US_CSR_RXRDY) != 0) {
return 1;
}
else {
return 0;
}
}
/**
* \brief Sets the filter value for the IRDA demodulator.
*
* \param pUsart Pointer to an Usart instance.
* \param filter Filter value.
*/
void USART_SetIrdaFilter(Usart *pUsart, uint8_t filter)
{
assert( pUsart != NULL ) ;
pUsart->US_IF = filter;
}
/**
* \brief Sends one packet of data through the specified USART peripheral. This
* function operates synchronously, so it only returns when the data has been
* actually sent.
*
* \param usart Pointer to an USART peripheral.
* \param c Character to send
*/
void USART_PutChar(
Usart *usart,
uint8_t c)
{
/* Wait for the transmitter to be ready*/
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0);
/* Send character*/
usart->US_THR = c;
/* Wait for the transfer to complete*/
while ((usart->US_CSR & US_CSR_TXEMPTY) == 0);
}
/**
* \brief Return 1 if a character can be read in USART
*/
uint32_t USART_IsRxReady(Usart *usart)
{
return (usart->US_CSR & US_CSR_RXRDY);
}
/**
* \brief Get present status
*/
uint32_t USART_GetStatus(Usart *usart)
{
return usart->US_CSR;
}
/**
* \brief Enable interrupt
*/
void USART_EnableIt(Usart *usart,uint32_t mode)
{
usart->US_IER = mode;
}
/**
* \brief Disable interrupt
*/
void USART_DisableIt(Usart *usart,uint32_t mode)
{
usart->US_IDR = mode;
}
/**
* \brief Reads and returns a character from the USART.
*
* \note This function is synchronous (i.e. uses polling).
* \param usart Pointer to an USART peripheral.
* \return Character received.
*/
uint8_t USART_GetChar(Usart *usart)
{
while ((usart->US_CSR & US_CSR_RXRDY) == 0);
return usart->US_RHR;
}
| lgpl-2.1 |
pnlnum/pnl | src/liblapack/dhsein.c | 1 | 14883 | /* dhsein.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "pnl/pnl_f2c.h"
/* Table of constant values */
static int c_false = FALSE;
static int c_true = TRUE;
int dhsein_(char *side, char *eigsrc, char *initv, int *
select, int *n, double *h__, int *ldh, double *wr,
double *wi, double *vl, int *ldvl, double *vr,
int *ldvr, int *mm, int *m, double *work, int *
ifaill, int *ifailr, int *info)
{
/* System generated locals */
int h_dim1, h_offset, vl_dim1, vl_offset, vr_dim1, vr_offset, i__1,
i__2;
double d__1, d__2;
/* Local variables */
int i__, k, kl, kr, kln, ksi;
double wki;
int ksr;
double ulp, wkr, eps3;
int pair;
double unfl;
extern int lsame_(char *, char *);
int iinfo;
int leftv, bothv;
double hnorm;
extern double dlamch_(char *);
extern int dlaein_(int *, int *, int *,
double *, int *, double *, double *, double *,
double *, double *, int *, double *, double *
, double *, double *, int *);
extern double dlanhs_(char *, int *, double *, int *,
double *);
extern int xerbla_(char *, int *);
double bignum;
int noinit;
int ldwork;
int rightv, fromqr;
double smlnum;
/* -- LAPACK routine (version 3.2) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2006 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* DHSEIN uses inverse iteration to find specified right and/or left */
/* eigenvectors of a float upper Hessenberg matrix H. */
/* The right eigenvector x and the left eigenvector y of the matrix H */
/* corresponding to an eigenvalue w are defined by: */
/* H * x = w * x, y**h * H = w * y**h */
/* where y**h denotes the conjugate transpose of the vector y. */
/* Arguments */
/* ========= */
/* SIDE (input) CHARACTER*1 */
/* = 'R': compute right eigenvectors only; */
/* = 'L': compute left eigenvectors only; */
/* = 'B': compute both right and left eigenvectors. */
/* EIGSRC (input) CHARACTER*1 */
/* Specifies the source of eigenvalues supplied in (WR,WI): */
/* = 'Q': the eigenvalues were found using DHSEQR; thus, if */
/* H has zero subdiagonal elements, and so is */
/* block-triangular, then the j-th eigenvalue can be */
/* assumed to be an eigenvalue of the block containing */
/* the j-th row/column. This property allows DHSEIN to */
/* perform inverse iteration on just one diagonal block. */
/* = 'N': no assumptions are made on the correspondence */
/* between eigenvalues and diagonal blocks. In this */
/* case, DHSEIN must always perform inverse iteration */
/* using the whole matrix H. */
/* INITV (input) CHARACTER*1 */
/* = 'N': no initial vectors are supplied; */
/* = 'U': user-supplied initial vectors are stored in the arrays */
/* VL and/or VR. */
/* SELECT (input/output) LOGICAL array, dimension (N) */
/* Specifies the eigenvectors to be computed. To select the */
/* float eigenvector corresponding to a float eigenvalue WR(j), */
/* SELECT(j) must be set to .TRUE.. To select the complex */
/* eigenvector corresponding to a complex eigenvalue */
/* (WR(j),WI(j)), with complex conjugate (WR(j+1),WI(j+1)), */
/* either SELECT(j) or SELECT(j+1) or both must be set to */
/* .TRUE.; then on exit SELECT(j) is .TRUE. and SELECT(j+1) is */
/* .FALSE.. */
/* N (input) INTEGER */
/* The order of the matrix H. N >= 0. */
/* H (input) DOUBLE PRECISION array, dimension (LDH,N) */
/* The upper Hessenberg matrix H. */
/* LDH (input) INTEGER */
/* The leading dimension of the array H. LDH >= MAX(1,N). */
/* WR (input/output) DOUBLE PRECISION array, dimension (N) */
/* WI (input) DOUBLE PRECISION array, dimension (N) */
/* On entry, the float and imaginary parts of the eigenvalues of */
/* H; a complex conjugate pair of eigenvalues must be stored in */
/* consecutive elements of WR and WI. */
/* On exit, WR may have been altered since close eigenvalues */
/* are perturbed slightly in searching for independent */
/* eigenvectors. */
/* VL (input/output) DOUBLE PRECISION array, dimension (LDVL,MM) */
/* On entry, if INITV = 'U' and SIDE = 'L' or 'B', VL must */
/* contain starting vectors for the inverse iteration for the */
/* left eigenvectors; the starting vector for each eigenvector */
/* must be in the same column(s) in which the eigenvector will */
/* be stored. */
/* On exit, if SIDE = 'L' or 'B', the left eigenvectors */
/* specified by SELECT will be stored consecutively in the */
/* columns of VL, in the same order as their eigenvalues. A */
/* complex eigenvector corresponding to a complex eigenvalue is */
/* stored in two consecutive columns, the first holding the float */
/* part and the second the imaginary part. */
/* If SIDE = 'R', VL is not referenced. */
/* LDVL (input) INTEGER */
/* The leading dimension of the array VL. */
/* LDVL >= MAX(1,N) if SIDE = 'L' or 'B'; LDVL >= 1 otherwise. */
/* VR (input/output) DOUBLE PRECISION array, dimension (LDVR,MM) */
/* On entry, if INITV = 'U' and SIDE = 'R' or 'B', VR must */
/* contain starting vectors for the inverse iteration for the */
/* right eigenvectors; the starting vector for each eigenvector */
/* must be in the same column(s) in which the eigenvector will */
/* be stored. */
/* On exit, if SIDE = 'R' or 'B', the right eigenvectors */
/* specified by SELECT will be stored consecutively in the */
/* columns of VR, in the same order as their eigenvalues. A */
/* complex eigenvector corresponding to a complex eigenvalue is */
/* stored in two consecutive columns, the first holding the float */
/* part and the second the imaginary part. */
/* If SIDE = 'L', VR is not referenced. */
/* LDVR (input) INTEGER */
/* The leading dimension of the array VR. */
/* LDVR >= MAX(1,N) if SIDE = 'R' or 'B'; LDVR >= 1 otherwise. */
/* MM (input) INTEGER */
/* The number of columns in the arrays VL and/or VR. MM >= M. */
/* M (output) INTEGER */
/* The number of columns in the arrays VL and/or VR required to */
/* store the eigenvectors; each selected float eigenvector */
/* occupies one column and each selected complex eigenvector */
/* occupies two columns. */
/* WORK (workspace) DOUBLE PRECISION array, dimension ((N+2)*N) */
/* IFAILL (output) INTEGER array, dimension (MM) */
/* If SIDE = 'L' or 'B', IFAILL(i) = j > 0 if the left */
/* eigenvector in the i-th column of VL (corresponding to the */
/* eigenvalue w(j)) failed to converge; IFAILL(i) = 0 if the */
/* eigenvector converged satisfactorily. If the i-th and (i+1)th */
/* columns of VL hold a complex eigenvector, then IFAILL(i) and */
/* IFAILL(i+1) are set to the same value. */
/* If SIDE = 'R', IFAILL is not referenced. */
/* IFAILR (output) INTEGER array, dimension (MM) */
/* If SIDE = 'R' or 'B', IFAILR(i) = j > 0 if the right */
/* eigenvector in the i-th column of VR (corresponding to the */
/* eigenvalue w(j)) failed to converge; IFAILR(i) = 0 if the */
/* eigenvector converged satisfactorily. If the i-th and (i+1)th */
/* columns of VR hold a complex eigenvector, then IFAILR(i) and */
/* IFAILR(i+1) are set to the same value. */
/* If SIDE = 'L', IFAILR is not referenced. */
/* INFO (output) INTEGER */
/* = 0: successful exit */
/* < 0: if INFO = -i, the i-th argument had an illegal value */
/* > 0: if INFO = i, i is the number of eigenvectors which */
/* failed to converge; see IFAILL and IFAILR for further */
/* details. */
/* Further Details */
/* =============== */
/* Each eigenvector is normalized so that the element of largest */
/* magnitude has magnitude 1; here the magnitude of a complex number */
/* (x,y) is taken to be |x|+|y|. */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Executable Statements .. */
/* Decode and test the input parameters. */
/* Parameter adjustments */
--select;
h_dim1 = *ldh;
h_offset = 1 + h_dim1;
h__ -= h_offset;
--wr;
--wi;
vl_dim1 = *ldvl;
vl_offset = 1 + vl_dim1;
vl -= vl_offset;
vr_dim1 = *ldvr;
vr_offset = 1 + vr_dim1;
vr -= vr_offset;
--work;
--ifaill;
--ifailr;
/* Function Body */
bothv = lsame_(side, "B");
rightv = lsame_(side, "R") || bothv;
leftv = lsame_(side, "L") || bothv;
fromqr = lsame_(eigsrc, "Q");
noinit = lsame_(initv, "N");
/* Set M to the number of columns required to store the selected */
/* eigenvectors, and standardize the array SELECT. */
*m = 0;
pair = FALSE;
i__1 = *n;
for (k = 1; k <= i__1; ++k) {
if (pair) {
pair = FALSE;
select[k] = FALSE;
} else {
if (wi[k] == 0.) {
if (select[k]) {
++(*m);
}
} else {
pair = TRUE;
if (select[k] || select[k + 1]) {
select[k] = TRUE;
*m += 2;
}
}
}
/* L10: */
}
*info = 0;
if (! rightv && ! leftv) {
*info = -1;
} else if (! fromqr && ! lsame_(eigsrc, "N")) {
*info = -2;
} else if (! noinit && ! lsame_(initv, "U")) {
*info = -3;
} else if (*n < 0) {
*info = -5;
} else if (*ldh < MAX(1,*n)) {
*info = -7;
} else if (*ldvl < 1 || leftv && *ldvl < *n) {
*info = -11;
} else if (*ldvr < 1 || rightv && *ldvr < *n) {
*info = -13;
} else if (*mm < *m) {
*info = -14;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DHSEIN", &i__1);
return 0;
}
/* Quick return if possible. */
if (*n == 0) {
return 0;
}
/* Set machine-dependent constants. */
unfl = dlamch_("Safe minimum");
ulp = dlamch_("Precision");
smlnum = unfl * (*n / ulp);
bignum = (1. - ulp) / smlnum;
ldwork = *n + 1;
kl = 1;
kln = 0;
if (fromqr) {
kr = 0;
} else {
kr = *n;
}
ksr = 1;
i__1 = *n;
for (k = 1; k <= i__1; ++k) {
if (select[k]) {
/* Compute eigenvector(s) corresponding to W(K). */
if (fromqr) {
/* If affiliation of eigenvalues is known, check whether */
/* the matrix splits. */
/* Determine KL and KR such that 1 <= KL <= K <= KR <= N */
/* and H(KL,KL-1) and H(KR+1,KR) are zero (or KL = 1 or */
/* KR = N). */
/* Then inverse iteration can be performed with the */
/* submatrix H(KL:N,KL:N) for a left eigenvector, and with */
/* the submatrix H(1:KR,1:KR) for a right eigenvector. */
i__2 = kl + 1;
for (i__ = k; i__ >= i__2; --i__) {
if (h__[i__ + (i__ - 1) * h_dim1] == 0.) {
goto L30;
}
/* L20: */
}
L30:
kl = i__;
if (k > kr) {
i__2 = *n - 1;
for (i__ = k; i__ <= i__2; ++i__) {
if (h__[i__ + 1 + i__ * h_dim1] == 0.) {
goto L50;
}
/* L40: */
}
L50:
kr = i__;
}
}
if (kl != kln) {
kln = kl;
/* Compute infinity-norm of submatrix H(KL:KR,KL:KR) if it */
/* has not ben computed before. */
i__2 = kr - kl + 1;
hnorm = dlanhs_("I", &i__2, &h__[kl + kl * h_dim1], ldh, &
work[1]);
if (hnorm > 0.) {
eps3 = hnorm * ulp;
} else {
eps3 = smlnum;
}
}
/* Perturb eigenvalue if it is close to any previous */
/* selected eigenvalues affiliated to the submatrix */
/* H(KL:KR,KL:KR). Close roots are modified by EPS3. */
wkr = wr[k];
wki = wi[k];
L60:
i__2 = kl;
for (i__ = k - 1; i__ >= i__2; --i__) {
if (select[i__] && (d__1 = wr[i__] - wkr, ABS(d__1)) + (d__2 =
wi[i__] - wki, ABS(d__2)) < eps3) {
wkr += eps3;
goto L60;
}
/* L70: */
}
wr[k] = wkr;
pair = wki != 0.;
if (pair) {
ksi = ksr + 1;
} else {
ksi = ksr;
}
if (leftv) {
/* Compute left eigenvector. */
i__2 = *n - kl + 1;
dlaein_(&c_false, &noinit, &i__2, &h__[kl + kl * h_dim1], ldh,
&wkr, &wki, &vl[kl + ksr * vl_dim1], &vl[kl + ksi *
vl_dim1], &work[1], &ldwork, &work[*n * *n + *n + 1],
&eps3, &smlnum, &bignum, &iinfo);
if (iinfo > 0) {
if (pair) {
*info += 2;
} else {
++(*info);
}
ifaill[ksr] = k;
ifaill[ksi] = k;
} else {
ifaill[ksr] = 0;
ifaill[ksi] = 0;
}
i__2 = kl - 1;
for (i__ = 1; i__ <= i__2; ++i__) {
vl[i__ + ksr * vl_dim1] = 0.;
/* L80: */
}
if (pair) {
i__2 = kl - 1;
for (i__ = 1; i__ <= i__2; ++i__) {
vl[i__ + ksi * vl_dim1] = 0.;
/* L90: */
}
}
}
if (rightv) {
/* Compute right eigenvector. */
dlaein_(&c_true, &noinit, &kr, &h__[h_offset], ldh, &wkr, &
wki, &vr[ksr * vr_dim1 + 1], &vr[ksi * vr_dim1 + 1], &
work[1], &ldwork, &work[*n * *n + *n + 1], &eps3, &
smlnum, &bignum, &iinfo);
if (iinfo > 0) {
if (pair) {
*info += 2;
} else {
++(*info);
}
ifailr[ksr] = k;
ifailr[ksi] = k;
} else {
ifailr[ksr] = 0;
ifailr[ksi] = 0;
}
i__2 = *n;
for (i__ = kr + 1; i__ <= i__2; ++i__) {
vr[i__ + ksr * vr_dim1] = 0.;
/* L100: */
}
if (pair) {
i__2 = *n;
for (i__ = kr + 1; i__ <= i__2; ++i__) {
vr[i__ + ksi * vr_dim1] = 0.;
/* L110: */
}
}
}
if (pair) {
ksr += 2;
} else {
++ksr;
}
}
/* L120: */
}
return 0;
/* End of DHSEIN */
} /* dhsein_ */
| lgpl-3.0 |
pcolby/libqtaws | src/iot/deletethingresponse.cpp | 1 | 4007 | /*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "deletethingresponse.h"
#include "deletethingresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace IoT {
/*!
* \class QtAws::IoT::DeleteThingResponse
* \brief The DeleteThingResponse class provides an interace for IoT DeleteThing responses.
*
* \inmodule QtAwsIoT
*
* <fullname>AWS IoT</fullname>
*
* AWS IoT provides secure, bi-directional communication between Internet-connected devices (such as sensors, actuators,
* embedded devices, or smart appliances) and the AWS cloud. You can discover your custom IoT-Data endpoint to communicate
* with, configure rules for data processing and integration with other services, organize resources associated with each
* device (Registry), configure logging, and create and manage policies and credentials to authenticate
*
* devices>
*
* The service endpoints that expose this API are listed in <a
* href="https://docs.aws.amazon.com/general/latest/gr/iot-core.html">AWS IoT Core Endpoints and Quotas</a>. You must use
* the endpoint for the region that has the resources you want to
*
* access>
*
* The service name used by <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">AWS Signature
* Version 4</a> to sign the request is:
*
* <i>execute-api</i>>
*
* For more information about how AWS IoT works, see the <a
* href="https://docs.aws.amazon.com/iot/latest/developerguide/aws-iot-how-it-works.html">Developer
*
* Guide</a>>
*
* For information about how to use the credentials provider for AWS IoT, see <a
* href="https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html">Authorizing Direct Calls to AWS
*
* \sa IoTClient::deleteThing
*/
/*!
* Constructs a DeleteThingResponse object for \a reply to \a request, with parent \a parent.
*/
DeleteThingResponse::DeleteThingResponse(
const DeleteThingRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: IoTResponse(new DeleteThingResponsePrivate(this), parent)
{
setRequest(new DeleteThingRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const DeleteThingRequest * DeleteThingResponse::request() const
{
Q_D(const DeleteThingResponse);
return static_cast<const DeleteThingRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful IoT DeleteThing \a response.
*/
void DeleteThingResponse::parseSuccess(QIODevice &response)
{
//Q_D(DeleteThingResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::IoT::DeleteThingResponsePrivate
* \brief The DeleteThingResponsePrivate class provides private implementation for DeleteThingResponse.
* \internal
*
* \inmodule QtAwsIoT
*/
/*!
* Constructs a DeleteThingResponsePrivate object with public implementation \a q.
*/
DeleteThingResponsePrivate::DeleteThingResponsePrivate(
DeleteThingResponse * const q) : IoTResponsePrivate(q)
{
}
/*!
* Parses a IoT DeleteThing response element from \a xml.
*/
void DeleteThingResponsePrivate::parseDeleteThingResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("DeleteThingResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace IoT
} // namespace QtAws
| lgpl-3.0 |
alesegdia/qt3d | src/render/frontend/qfrontface.cpp | 2 | 2940 | /****************************************************************************
**
** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB).
** Copyright (C) 2015 The Qt Company Ltd and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** 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 http://www.qt.io/terms-conditions. For further
** information use the contact form at http://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.LGPLv3 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.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 later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfrontface.h"
#include "qrenderstate_p.h"
#include <private/qnode_p.h>
#include <Qt3DCore/qscenepropertychange.h>
QT_BEGIN_NAMESPACE
namespace Qt3D {
class QFrontFacePrivate : public QRenderStatePrivate
{
public:
QFrontFacePrivate()
: QRenderStatePrivate(QRenderState::FrontFace)
, m_direction(QFrontFace::ClockWise)
{
}
Q_DECLARE_PUBLIC(QFrontFace)
QFrontFace::FaceDir m_direction;
};
QFrontFace::QFrontFace(QNode *parent)
: QRenderState(*new QFrontFacePrivate, parent)
{
}
QFrontFace::~QFrontFace()
{
QNode::cleanup();
}
void QFrontFace::copy(const QNode *ref)
{
QRenderState::copy(ref);
const QFrontFace *refState = static_cast<const QFrontFace*>(ref);
d_func()->m_direction = refState->d_func()->m_direction;
}
QFrontFace::FaceDir QFrontFace::direction() const
{
Q_D(const QFrontFace);
return d->m_direction;
}
void QFrontFace::setDirection(QFrontFace::FaceDir direction)
{
Q_D(QFrontFace);
if (d->m_direction != direction) {
d->m_direction = direction;
emit directionChanged();
}
}
} // Qt3D
QT_END_NAMESPACE
| lgpl-3.0 |
raphaelrpl/terrama2 | src/terrama2/core/data-model/DataManager.cpp | 4 | 12611 | /*
Copyright (C) 2007 National Institute For Space Research (INPE) - Brazil.
This file is part of TerraMA2 - a free and open source computational
platform for analysis, monitoring, and alert of geo-environmental extremes.
TerraMA2 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.
TerraMA2 is distributed in the hope that 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 TerraMA2. See LICENSE. If not, write to
TerraMA2 Team at <terrama2-team@dpi.inpe.br>.
*/
/*!
\file terrama2/core/DataManager.hpp
\brief Manages metadata about data providers and its datasets.
\author Gilberto Ribeiro de Queiroz
\author Jano Simas
\author Paulo R. M. Oliveira
\author Vinicius Campanha
*/
// TerraMA2
#include "DataManager.hpp"
#include "DataProvider.hpp"
#include "DataSeries.hpp"
#include "DataSet.hpp"
#include "../Exception.hpp"
#include "../Typedef.hpp"
// TerraMA2 Logger
#include "../utility/Logger.hpp"
#include "../utility/JSonUtils.hpp"
// STL
#include <algorithm>
#include <memory>
//Qt
#include <QJsonArray>
#include <QString>
// TerraLib
#include <terralib/dataaccess/datasource/DataSourceTransactor.h>
std::unique_lock<std::recursive_mutex> terrama2::core::DataManager::getLock()
{
std::unique_lock<std::recursive_mutex> lock(mtx_);
return lock;
}
void terrama2::core::DataManager::add(DataProviderPtr provider)
{
// Inside a block so the lock is released before emitting the signal
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
if(provider->name.empty())
{
QString errMsg = QObject::tr("Can not add a data provider with empty name.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
if(provider->id == terrama2::core::InvalidId())
{
QString errMsg = QObject::tr("Can not add a data provider with an invalid id.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
providers_.emplace(provider->id, provider);
}
emit dataProviderAdded(provider);
}
void terrama2::core::DataManager::add(DataSeriesPtr dataseries)
{
// Inside a block so the lock is released before emitting the signal
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
if(dataseries->name.empty())
{
QString errMsg = QObject::tr("Can not add a data series with empty name.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
if(dataseries->id == terrama2::core::InvalidId())
{
QString errMsg = QObject::tr("Can not add a data series with invalid identifier.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
try
{
providers_.at(dataseries->dataProviderId);
}
catch (const std::out_of_range&)
{
QString errMsg = QObject::tr("Can not add a dataseries with a non-registered data provider: %1.").arg(dataseries->dataProviderId);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
try
{
dataseries_.at(dataseries->id);
QString errMsg = QObject::tr("DataSeries already registered.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
catch (const std::out_of_range&)
{
//Expected behavior
}
dataseries_.emplace(dataseries->id, dataseries);
}
emit dataSeriesAdded(dataseries);
}
void terrama2::core::DataManager::update(terrama2::core::DataProviderPtr provider)
{
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
blockSignals(true);
removeDataProvider(provider->id, true);
add(provider);
blockSignals(false);
}
emit dataProviderUpdated(provider);
}
void terrama2::core::DataManager::add(terrama2::core::LegendPtr legend)
{
// Inside a block so the lock is released before emitting the signal
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
if(legend->name.empty())
{
QString errMsg = QObject::tr("Can not add a legend with empty name.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
if(legend->id == terrama2::core::InvalidId())
{
QString errMsg = QObject::tr("Can not add a legend with invalid identifier.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
try
{
legends_.at(legend->id);
QString errMsg = QObject::tr("Legend already registered.");
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
catch (const std::out_of_range&)
{
//Expected behavior
}
legends_.emplace(legend->id, legend);
}
}
void terrama2::core::DataManager::update(terrama2::core::LegendPtr legend)
{
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
blockSignals(true);
removeLegend(legend->id);
add(legend);
blockSignals(false);
}
}
bool terrama2::core::DataManager::hasLegend(LegendId id) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = legends_.find(id);
return it != legends_.cend();
}
void terrama2::core::DataManager::removeLegend(const LegendId id)
{
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
auto itPr = legends_.find(id);
if(itPr == legends_.end())
{
QString errMsg = QObject::tr("Could not find a legend with the given id: %1.").arg(id);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
legends_.erase(itPr);
}
}
terrama2::core::LegendPtr terrama2::core::DataManager::findLegend(const LegendId id) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = legends_.find(id);
if(it == legends_.cend())
{
QString errMsg = QObject::tr("Could not find a legend with the given id: %1.").arg(id);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
return it->second;
}
void terrama2::core::DataManager::update(terrama2::core::DataSeriesPtr dataseries, const bool /*shallowSave*/)
{
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
blockSignals(true);
removeDataSeries(dataseries->id);
add(dataseries);
blockSignals(false);
}
emit dataSeriesUpdated(dataseries);
}
void terrama2::core::DataManager::removeDataProvider(const DataProviderId id, const bool shallowRemove)
{
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
auto itPr = providers_.find(id);
if(itPr == providers_.end())
{
QString errMsg = QObject::tr("Could not find a data provider with the given id: %1.").arg(id);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
providers_.erase(itPr);
if(!shallowRemove)
{
for(const auto& pair : dataseries_)
{
const auto& dataseries = pair.second;
if(dataseries->dataProviderId == id)
removeDataSeries(dataseries->id);
}
}
}
emit dataProviderRemoved(id);
}
void terrama2::core::DataManager::removeDataSeries(const DataSeriesId id)
{
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = dataseries_.find(id);
if(it == dataseries_.end())
{
QString errMsg = QObject::tr("Could not find a data series with the given id: %1.").arg(id);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
dataseries_.erase(it);
}
emit dataSeriesRemoved(id);
}
terrama2::core::DataProviderPtr terrama2::core::DataManager::findDataProvider(const std::string& name) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = std::find_if(providers_.cbegin(), providers_.cend(), [name](std::pair<DataProviderId, DataProviderPtr> provider) { return provider.second->name == name; });
if(it == providers_.cend())
{
QString errMsg = QObject::tr("Could not find a data provider with the given name: %1.").arg(QString::fromStdString(name));
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
return it->second;
}
bool terrama2::core::DataManager::hasDataProvider(DataProviderId id) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = providers_.find(id);
return it != providers_.cend();
}
terrama2::core::DataProviderPtr terrama2::core::DataManager::findDataProvider(const DataProviderId id) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = providers_.find(id);
if(it == providers_.cend())
{
QString errMsg = QObject::tr("Could not find a data provider with the given id: %1.").arg(id);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
return it->second;
}
bool terrama2::core::DataManager::hasDataSeries(DataSeriesId id) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = dataseries_.find(id);
return it != dataseries_.cend();
}
terrama2::core::DataSeriesPtr terrama2::core::DataManager::findDataSeries(const std::string& name) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
//TODO: create a map name->id to fasten the cases where this function is called to many times?
const auto& it = std::find_if(dataseries_.cbegin(), dataseries_.cend(), [name] (std::pair<DataSeriesId, DataSeriesPtr> series)
{ return series.second->name == name; });
if(it == dataseries_.cend())
{
QString errMsg = QObject::tr("Could not find a data series with the given name: %1.").arg(QString::fromStdString(name));
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
return it->second;
}
terrama2::core::DataSeriesPtr terrama2::core::DataManager::findDataSeries(const DataSeriesId id) const
{
std::lock_guard<std::recursive_mutex> lock(mtx_);
const auto& it = dataseries_.find(id);
if(it == dataseries_.cend())
{
QString errMsg = QObject::tr("Could not find a data series with the given id: %1.").arg(id);
TERRAMA2_LOG_ERROR() << errMsg;
throw terrama2::InvalidArgumentException() << ErrorDescription(errMsg);
}
return it->second;
}
terrama2::core::DataManager::DataManager()
{
qRegisterMetaType<DataProviderPtr>("DataProviderPtr");
qRegisterMetaType<DataSeriesPtr>("DataSeriesPtr");
qRegisterMetaType<uint32_t>("uint32_t");
}
void terrama2::core::DataManager::addJSon(const QJsonObject& obj)
{
auto dataProviders = obj["DataProviders"].toArray();
for(auto json : dataProviders)
{
auto dataPtr = terrama2::core::fromDataProviderJson(json.toObject());
if(hasDataProvider(dataPtr->id))
update(dataPtr);
else
add(dataPtr);
}
auto dataSeries = obj["DataSeries"].toArray();
for(auto json : dataSeries)
{
auto dataPtr = terrama2::core::fromDataSeriesJson(json.toObject());
if(hasDataSeries(dataPtr->id))
update(dataPtr);
else
add(dataPtr);
}
auto legends = obj["Legends"].toArray();
for(auto json : legends)
{
auto dataPtr = terrama2::core::fromRiskJson(json.toObject());
if(hasLegend(dataPtr->id))
update(dataPtr);
else
add(dataPtr);
}
}
void terrama2::core::DataManager::removeJSon(const QJsonObject& obj)
{
auto dataSeries = obj["DataSeries"].toArray();
for(auto json : dataSeries)
{
auto dataId = json.toInt();
removeDataSeries(dataId);
}
auto dataProviders = obj["DataProviders"].toArray();
for(auto json : dataProviders)
{
auto dataId = json.toInt();
removeDataProvider(dataId);
}
}
void terrama2::core::DataManager::validateJSon(const QJsonObject& /*obj*/)
{
// should be override by subclass.
}
| lgpl-3.0 |
Zhongqilong/kbengine | kbe/src/server/cellapp/updatables.cpp | 24 | 2058 | /*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2016 KBEngine.
KBEngine 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.
KBEngine is distributed in the hope that 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 KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#include "updatables.h"
#include "helper/profile.h"
namespace KBEngine{
//-------------------------------------------------------------------------------------
Updatables::Updatables()
{
}
//-------------------------------------------------------------------------------------
Updatables::~Updatables()
{
}
//-------------------------------------------------------------------------------------
bool Updatables::add(Updatable* updatable)
{
static uint32 idx = 1;
objects_[idx] = updatable;
// ¼Ç¼´æ´¢Î»ÖÃ
updatable->removeIdx = idx++;
return true;
}
//-------------------------------------------------------------------------------------
bool Updatables::remove(Updatable* updatable)
{
objects_.erase(updatable->removeIdx);
updatable->removeIdx = -1;
return true;
}
//-------------------------------------------------------------------------------------
void Updatables::update()
{
AUTO_SCOPED_PROFILE("callUpdates");
std::map<uint32, Updatable*>::iterator iter = objects_.begin();
for(; iter != objects_.end(); )
{
if(!iter->second->update())
{
objects_.erase(iter++);
}
else
{
++iter;
}
}
}
//-------------------------------------------------------------------------------------
}
| lgpl-3.0 |
zhukaixy/kbengine | kbe/src/lib/dependencies/openssl/crypto/asn1/asn1_par.c | 52 | 11718 | /* crypto/asn1/asn1_par.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/asn1.h>
static int asn1_print_info(BIO *bp, int tag, int xclass,int constructed,
int indent);
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
int offset, int depth, int indent, int dump);
static int asn1_print_info(BIO *bp, int tag, int xclass, int constructed,
int indent)
{
static const char fmt[]="%-18s";
static const char fmt2[]="%2d %-15s";
char str[128];
const char *p,*p2=NULL;
if (constructed & V_ASN1_CONSTRUCTED)
p="cons: ";
else
p="prim: ";
if (BIO_write(bp,p,6) < 6) goto err;
BIO_indent(bp,indent,128);
p=str;
if ((xclass & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
BIO_snprintf(str,sizeof str,"priv [ %d ] ",tag);
else if ((xclass & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
BIO_snprintf(str,sizeof str,"cont [ %d ]",tag);
else if ((xclass & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
BIO_snprintf(str,sizeof str,"appl [ %d ]",tag);
else if (tag > 30)
BIO_snprintf(str,sizeof str,"<ASN1 %d>",tag);
else
p = ASN1_tag2str(tag);
if (p2 != NULL)
{
if (BIO_printf(bp,fmt2,tag,p2) <= 0) goto err;
}
else
{
if (BIO_printf(bp,fmt,p) <= 0) goto err;
}
return(1);
err:
return(0);
}
int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent)
{
return(asn1_parse2(bp,&pp,len,0,0,indent,0));
}
int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent, int dump)
{
return(asn1_parse2(bp,&pp,len,0,0,indent,dump));
}
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length, int offset,
int depth, int indent, int dump)
{
const unsigned char *p,*ep,*tot,*op,*opp;
long len;
int tag,xclass,ret=0;
int nl,hl,j,r;
ASN1_OBJECT *o=NULL;
ASN1_OCTET_STRING *os=NULL;
/* ASN1_BMPSTRING *bmp=NULL;*/
int dump_indent;
#if 0
dump_indent = indent;
#else
dump_indent = 6; /* Because we know BIO_dump_indent() */
#endif
p= *pp;
tot=p+length;
op=p-1;
while ((p < tot) && (op < p))
{
op=p;
j=ASN1_get_object(&p,&len,&tag,&xclass,length);
#ifdef LINT
j=j;
#endif
if (j & 0x80)
{
if (BIO_write(bp,"Error in encoding\n",18) <= 0)
goto end;
ret=0;
goto end;
}
hl=(p-op);
length-=hl;
/* if j == 0x21 it is a constructed indefinite length object */
if (BIO_printf(bp,"%5ld:",(long)offset+(long)(op- *pp))
<= 0) goto end;
if (j != (V_ASN1_CONSTRUCTED | 1))
{
if (BIO_printf(bp,"d=%-2d hl=%ld l=%4ld ",
depth,(long)hl,len) <= 0)
goto end;
}
else
{
if (BIO_printf(bp,"d=%-2d hl=%ld l=inf ",
depth,(long)hl) <= 0)
goto end;
}
if (!asn1_print_info(bp,tag,xclass,j,(indent)?depth:0))
goto end;
if (j & V_ASN1_CONSTRUCTED)
{
ep=p+len;
if (BIO_write(bp,"\n",1) <= 0) goto end;
if (len > length)
{
BIO_printf(bp,
"length is greater than %ld\n",length);
ret=0;
goto end;
}
if ((j == 0x21) && (len == 0))
{
for (;;)
{
r=asn1_parse2(bp,&p,(long)(tot-p),
offset+(p - *pp),depth+1,
indent,dump);
if (r == 0) { ret=0; goto end; }
if ((r == 2) || (p >= tot)) break;
}
}
else
while (p < ep)
{
r=asn1_parse2(bp,&p,(long)len,
offset+(p - *pp),depth+1,
indent,dump);
if (r == 0) { ret=0; goto end; }
}
}
else if (xclass != 0)
{
p+=len;
if (BIO_write(bp,"\n",1) <= 0) goto end;
}
else
{
nl=0;
if ( (tag == V_ASN1_PRINTABLESTRING) ||
(tag == V_ASN1_T61STRING) ||
(tag == V_ASN1_IA5STRING) ||
(tag == V_ASN1_VISIBLESTRING) ||
(tag == V_ASN1_UTCTIME) ||
(tag == V_ASN1_GENERALIZEDTIME))
{
if (BIO_write(bp,":",1) <= 0) goto end;
if ((len > 0) &&
BIO_write(bp,(const char *)p,(int)len)
!= (int)len)
goto end;
}
else if (tag == V_ASN1_OBJECT)
{
opp=op;
if (d2i_ASN1_OBJECT(&o,&opp,len+hl) != NULL)
{
if (BIO_write(bp,":",1) <= 0) goto end;
i2a_ASN1_OBJECT(bp,o);
}
else
{
if (BIO_write(bp,":BAD OBJECT",11) <= 0)
goto end;
}
}
else if (tag == V_ASN1_BOOLEAN)
{
int ii;
opp=op;
ii=d2i_ASN1_BOOLEAN(NULL,&opp,len+hl);
if (ii < 0)
{
if (BIO_write(bp,"Bad boolean\n",12))
goto end;
}
BIO_printf(bp,":%d",ii);
}
else if (tag == V_ASN1_BMPSTRING)
{
/* do the BMP thang */
}
else if (tag == V_ASN1_OCTET_STRING)
{
int i,printable=1;
opp=op;
os=d2i_ASN1_OCTET_STRING(NULL,&opp,len+hl);
if (os != NULL && os->length > 0)
{
opp = os->data;
/* testing whether the octet string is
* printable */
for (i=0; i<os->length; i++)
{
if (( (opp[i] < ' ') &&
(opp[i] != '\n') &&
(opp[i] != '\r') &&
(opp[i] != '\t')) ||
(opp[i] > '~'))
{
printable=0;
break;
}
}
if (printable)
/* printable string */
{
if (BIO_write(bp,":",1) <= 0)
goto end;
if (BIO_write(bp,(const char *)opp,
os->length) <= 0)
goto end;
}
else if (!dump)
/* not printable => print octet string
* as hex dump */
{
if (BIO_write(bp,"[HEX DUMP]:",11) <= 0)
goto end;
for (i=0; i<os->length; i++)
{
if (BIO_printf(bp,"%02X"
, opp[i]) <= 0)
goto end;
}
}
else
/* print the normal dump */
{
if (!nl)
{
if (BIO_write(bp,"\n",1) <= 0)
goto end;
}
if (BIO_dump_indent(bp,
(const char *)opp,
((dump == -1 || dump >
os->length)?os->length:dump),
dump_indent) <= 0)
goto end;
nl=1;
}
}
if (os != NULL)
{
M_ASN1_OCTET_STRING_free(os);
os=NULL;
}
}
else if (tag == V_ASN1_INTEGER)
{
ASN1_INTEGER *bs;
int i;
opp=op;
bs=d2i_ASN1_INTEGER(NULL,&opp,len+hl);
if (bs != NULL)
{
if (BIO_write(bp,":",1) <= 0) goto end;
if (bs->type == V_ASN1_NEG_INTEGER)
if (BIO_write(bp,"-",1) <= 0)
goto end;
for (i=0; i<bs->length; i++)
{
if (BIO_printf(bp,"%02X",
bs->data[i]) <= 0)
goto end;
}
if (bs->length == 0)
{
if (BIO_write(bp,"00",2) <= 0)
goto end;
}
}
else
{
if (BIO_write(bp,"BAD INTEGER",11) <= 0)
goto end;
}
M_ASN1_INTEGER_free(bs);
}
else if (tag == V_ASN1_ENUMERATED)
{
ASN1_ENUMERATED *bs;
int i;
opp=op;
bs=d2i_ASN1_ENUMERATED(NULL,&opp,len+hl);
if (bs != NULL)
{
if (BIO_write(bp,":",1) <= 0) goto end;
if (bs->type == V_ASN1_NEG_ENUMERATED)
if (BIO_write(bp,"-",1) <= 0)
goto end;
for (i=0; i<bs->length; i++)
{
if (BIO_printf(bp,"%02X",
bs->data[i]) <= 0)
goto end;
}
if (bs->length == 0)
{
if (BIO_write(bp,"00",2) <= 0)
goto end;
}
}
else
{
if (BIO_write(bp,"BAD ENUMERATED",11) <= 0)
goto end;
}
M_ASN1_ENUMERATED_free(bs);
}
else if (len > 0 && dump)
{
if (!nl)
{
if (BIO_write(bp,"\n",1) <= 0)
goto end;
}
if (BIO_dump_indent(bp,(const char *)p,
((dump == -1 || dump > len)?len:dump),
dump_indent) <= 0)
goto end;
nl=1;
}
if (!nl)
{
if (BIO_write(bp,"\n",1) <= 0) goto end;
}
p+=len;
if ((tag == V_ASN1_EOC) && (xclass == 0))
{
ret=2; /* End of sequence */
goto end;
}
}
length-=len;
}
ret=1;
end:
if (o != NULL) ASN1_OBJECT_free(o);
if (os != NULL) M_ASN1_OCTET_STRING_free(os);
*pp=p;
return(ret);
}
const char *ASN1_tag2str(int tag)
{
static const char *tag2str[] = {
"EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING", /* 0-4 */
"NULL", "OBJECT", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL", /* 5-9 */
"ENUMERATED", "<ASN1 11>", "UTF8STRING", "<ASN1 13>", /* 10-13 */
"<ASN1 14>", "<ASN1 15>", "SEQUENCE", "SET", /* 15-17 */
"NUMERICSTRING", "PRINTABLESTRING", "T61STRING", /* 18-20 */
"VIDEOTEXSTRING", "IA5STRING", "UTCTIME","GENERALIZEDTIME", /* 21-24 */
"GRAPHICSTRING", "VISIBLESTRING", "GENERALSTRING", /* 25-27 */
"UNIVERSALSTRING", "<ASN1 29>", "BMPSTRING" /* 28-30 */
};
if((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
tag &= ~0x100;
if(tag < 0 || tag > 30) return "(unknown)";
return tag2str[tag];
}
| lgpl-3.0 |
0jpq0/kbengine | kbe/src/lib/python/Modules/_ctypes/libffi/testsuite/libffi.call/float1.c | 664 | 1114 | /* Area: ffi_call
Purpose: Check return value double.
Limitations: none.
PR: none.
Originator: From the original ffitest.c */
/* { dg-do run } */
#include "ffitest.h"
#include "float.h"
typedef union
{
double d;
unsigned char c[sizeof (double)];
} value_type;
#define CANARY 0xba
static double dblit(float f)
{
return f/3.0;
}
int main (void)
{
ffi_cif cif;
ffi_type *args[MAX_ARGS];
void *values[MAX_ARGS];
float f;
value_type result[2];
unsigned int i;
args[0] = &ffi_type_float;
values[0] = &f;
/* Initialize the cif */
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1,
&ffi_type_double, args) == FFI_OK);
f = 3.14159;
/* Put a canary in the return array. This is a regression test for
a buffer overrun. */
memset(result[1].c, CANARY, sizeof (double));
ffi_call(&cif, FFI_FN(dblit), &result[0].d, values);
/* These are not always the same!! Check for a reasonable delta */
CHECK(result[0].d - dblit(f) < DBL_EPSILON);
/* Check the canary. */
for (i = 0; i < sizeof (double); ++i)
CHECK(result[1].c[i] == CANARY);
exit(0);
}
| lgpl-3.0 |
caspervranken/BachelorThesis_Pirotte_Vranken | world/CShapeEllipsoid.cpp | 1 | 20430 | //==============================================================================
/*
Software License Agreement (BSD License)
Copyright (c) 2003-2016, CHAI3D.
(www.chai3d.org)
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 CHAI3D nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
\author <http://www.chai3d.org>
\author Francois Conti
\version 3.2.0 $Rev: 2164 $
*/
//==============================================================================
//------------------------------------------------------------------------------
#include "world/CShapeEllipsoid.h"
//------------------------------------------------------------------------------
#include "shaders/CShaderProgram.h"
//------------------------------------------------------------------------------
#ifdef C_USE_OPENGL
#ifdef MACOSX
#include "OpenGL/glu.h"
#else
#include "GL/glu.h"
#endif
#endif
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
namespace chai3d {
//------------------------------------------------------------------------------
//==============================================================================
/*!
Constructor of cShapeEllipsoid.
\param a_radiusX Radius of ellipsoid along __x__axis.
\param a_radiusY Radius of ellipsoid along __y__axis.
\param a_radiusZ Radius of ellipsoid along __z__axis.
\param a_material Material property to be applied to object.
*/
//==============================================================================
cShapeEllipsoid::cShapeEllipsoid(const double& a_radiusX,
const double& a_radiusY,
const double& a_radiusZ,
cMaterialPtr a_material)
{
// initialize radii of ellipsoid
m_radiusX = fabs(a_radiusX);
m_radiusY = fabs(a_radiusY);
m_radiusZ = fabs(a_radiusZ);
// set material properties
if (a_material == nullptr)
{
m_material = cMaterial::create();
m_material->setShininess(100);
m_material->setWhite();
}
else
{
m_material = a_material;
}
// allocate a new OpenGL quadric object for rendering
#ifdef C_USE_OPENGL
m_quadric = gluNewQuadric();
#else
m_quadric = NULL;
#endif
};
//==============================================================================
/*!
Destructor of cShapeEllipsoid.
*/
//==============================================================================.
cShapeEllipsoid::~cShapeEllipsoid()
{
// deallocate OpenGL quadric object used for rendering
#ifdef C_USE_OPENGL
gluDeleteQuadric(m_quadric);
#endif
}
//==============================================================================
/*!
This method creates a copy of itself.
\param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared.
\param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared.
\param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared.
\param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared.
\return Pointer to new object.
*/
//==============================================================================
cShapeEllipsoid* cShapeEllipsoid::copy(const bool a_duplicateMaterialData,
const bool a_duplicateTextureData,
const bool a_duplicateMeshData,
const bool a_buildCollisionDetector)
{
// enable display list
m_useDisplayList = true;
// create new instance
cShapeEllipsoid* obj = new cShapeEllipsoid(m_radiusX, m_radiusY, m_radiusZ);
// copy properties of cShapeSphere
copyShapeEllipsoidProperties(obj,
a_duplicateMaterialData,
a_duplicateTextureData,
a_duplicateMeshData,
a_buildCollisionDetector);
// return
return (obj);
}
//==============================================================================
/*!
This method copies all properties of this multi-mesh to another.
\param a_obj Destination object where properties are copied to.
\param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared.
\param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared.
\param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared.
\param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared.
*/
//==============================================================================
void cShapeEllipsoid::copyShapeEllipsoidProperties(cShapeEllipsoid* a_obj,
const bool a_duplicateMaterialData,
const bool a_duplicateTextureData,
const bool a_duplicateMeshData,
const bool a_buildCollisionDetector)
{
// copy properties of cGenericObject
copyGenericObjectProperties(a_obj,
a_duplicateMaterialData,
a_duplicateTextureData,
a_duplicateMeshData,
a_buildCollisionDetector);
// copy properties of cShapeSphere
a_obj->m_radiusX = m_radiusX;
a_obj->m_radiusY = m_radiusY;
a_obj->m_radiusZ = m_radiusZ;
}
//==============================================================================
/*!
This method sets the radis of the ellipsoid along the __x__,
__y__, and __z__ axes.
\param a_radiusX Radius of ellipsoid along __x__axis.
\param a_radiusY Radius of ellipsoid along __y__axis.
\param a_radiusZ Radius of ellipsoid along __z__axis.
*/
//==============================================================================
void cShapeEllipsoid::setRadii(const double& a_radiusX, const double& a_radiusY, const double& a_radiusZ)
{
// set new radii
m_radiusX = fabs(a_radiusX);
m_radiusY = fabs(a_radiusY);
m_radiusZ = fabs(a_radiusZ);
// update bounding box
updateBoundaryBox();
// invalidate display list
markForUpdate(false);
}
//==============================================================================
/*!
This method sets the radius of this ellpsoid along the __x__ axis.
\param a_radiusX Radius of ellipsoid along __x__axis.
*/
//==============================================================================
void cShapeEllipsoid::setRadiusX(const double& a_radiusX)
{
// set new radius
m_radiusX = fabs(a_radiusX);
// update bounding box
updateBoundaryBox();
// invalidate display list
markForUpdate(false);
}
//==============================================================================
/*!
This method sets the radius of this ellpsoid along the __y__ axis.
\param a_radiusY Radius of ellipsoid along __y__axis.
*/
//==============================================================================
void cShapeEllipsoid::setRadiusY(const double& a_radiusY)
{
// set new radius
m_radiusY = fabs(a_radiusY);
// update bounding box
updateBoundaryBox();
// invalidate display list
markForUpdate(false);
}
//==============================================================================
/*!
This method sets the radius of this ellpsoid along the __z__ axis.
\param a_radiusZ Radius of ellipsoid along __z__axis.
*/
//==============================================================================
void cShapeEllipsoid::setRadiusZ(const double& a_radiusZ)
{
// set new radius
m_radiusZ = fabs(a_radiusZ);
// update bounding box
updateBoundaryBox();
// invalidate display list
markForUpdate(false);
}
//==============================================================================
/*!
This method renders the object using OpenGL
\param a_options Render options.
*/
//==============================================================================
void cShapeEllipsoid::render(cRenderOptions& a_options)
{
#ifdef C_USE_OPENGL
/////////////////////////////////////////////////////////////////////////
// ENABLE SHADER
/////////////////////////////////////////////////////////////////////////
if ((m_shaderProgram != nullptr) && (!a_options.m_creating_shadow_map))
{
// enable shader
m_shaderProgram->use(this, a_options);
}
/////////////////////////////////////////////////////////////////////////
// Render parts that use material properties
/////////////////////////////////////////////////////////////////////////
if (SECTION_RENDER_PARTS_WITH_MATERIALS(a_options, m_useTransparency))
{
// render material properties
if (m_useMaterialProperty)
{
m_material->render(a_options);
}
// set rendering style
gluQuadricDrawStyle (m_quadric, GLU_FILL);
// set normal-rendering mode
gluQuadricNormals (m_quadric, GLU_SMOOTH);
// render texture property if defined
if ((m_texture != nullptr) && (m_useTextureMapping))
{
// activate texture
m_texture->renderInitialize(a_options);
// generate texture coordinates
gluQuadricTexture(m_quadric, GL_TRUE);
}
// render an ellipsoid
double radius = cMin(m_radiusX, cMin(m_radiusY, m_radiusZ));
double scaleX = m_radiusX / radius;
double scaleY = m_radiusY / radius;
double scaleZ = m_radiusZ / radius;
glScalef(scaleX, scaleY, scaleZ);
gluSphere(m_quadric, radius, 36, 36);
glScalef(1.0, 1.0, 1.0);
// turn off texture rendering
if ((m_texture != nullptr) && (m_useTextureMapping))
{
m_texture->renderFinalize(a_options);
}
}
/////////////////////////////////////////////////////////////////////////
// DISABLE SHADER
/////////////////////////////////////////////////////////////////////////
if ((m_shaderProgram != nullptr) && (!a_options.m_creating_shadow_map))
{
// disable shader
m_shaderProgram->disable();
}
#endif
}
//==============================================================================
/*!
This method uses the position of the tool and searches for the nearest point
located at the surface of the current object and identifies if the point is
located inside or outside of the object.
\param a_toolPos Position of the tool.
\param a_toolVel Velocity of the tool.
\param a_IDN Identification number of the force algorithm.
*/
//==============================================================================
void cShapeEllipsoid::computeLocalInteraction(const cVector3d& a_toolPos,
const cVector3d& a_toolVel,
const unsigned int a_IDN)
{
// scale ellpsoid to sphere
double radius = cMin(m_radiusX, cMin(m_radiusY, m_radiusZ));
double scaleX = m_radiusX / radius;
double scaleY = m_radiusY / radius;
double scaleZ = m_radiusZ / radius;
cVector3d pos = a_toolPos;
pos.mul(1.0 / scaleX, 1.0 / scaleY, 1.0 / scaleZ);
// compute distance from center of sphere to tool
double distance = pos.length();
// from the position of the tool, search for the nearest point located
// on the surface of the sphere
if (distance > 0)
{
m_interactionPoint = cMul( (radius/distance), pos);
m_interactionNormal = m_interactionPoint;
m_interactionPoint.mul(scaleX, scaleY, scaleZ);
m_interactionNormal.mul(1.0 / scaleX, 1.0 / scaleY, 1.0 / scaleZ);
m_interactionNormal.normalize();
}
else
{
m_interactionPoint = a_toolPos;
m_interactionNormal.set(0,0,1);
}
// check if tool is located inside or outside of the sphere
if (distance <= radius)
{
m_interactionInside = true;
}
else
{
m_interactionInside = false;
}
}
//==============================================================================
/*!
This method updates the boundary box of this object.
*/
//==============================================================================
void cShapeEllipsoid::updateBoundaryBox()
{
m_boundaryBoxMin.set(-m_radiusX, -m_radiusY, -m_radiusZ);
m_boundaryBoxMax.set( m_radiusX, m_radiusY, m_radiusZ);
}
//==============================================================================
/*!
This method scales the size of this object with given scale factor.
\param a_scaleFactor Scale factor.
*/
//==============================================================================
void cShapeEllipsoid::scaleObject(const double& a_scaleFactor)
{
// update radius
m_radiusX *= a_scaleFactor;
m_radiusY *= a_scaleFactor;
m_radiusZ *= a_scaleFactor;
// update bounding box
updateBoundaryBox();
// invalidate display list
markForUpdate(false);
}
//==============================================================================
/*!
This method determines whether a given segment intersects this object. \n
The segment is described by a start point \p a_segmentPointA and end
point \p a_segmentPointB. \n
All detected collisions are reported in the collision recorder passed
by argument \p a_recorder. \n
Specifications about the type of collisions reported are specified by
argument \p a_settings.
\param a_segmentPointA Start point of segment.
\param a_segmentPointB End point of segment.
\param a_recorder Recorder which stores all collision events.
\param a_settings Collision settings information.
\return __true__ if a collision has occurred, __false__ otherwise.
*/
//==============================================================================
bool cShapeEllipsoid::computeOtherCollisionDetection(cVector3d& a_segmentPointA,
cVector3d& a_segmentPointB,
cCollisionRecorder& a_recorder,
cCollisionSettings& a_settings)
{
////////////////////////////////////////////////////////////////////////////
// COMPUTE COLLISION
////////////////////////////////////////////////////////////////////////////
// ignore shape if requested
if (a_settings.m_ignoreShapes) { return (false); }
// no collision has occurred yet
bool hit = false;
// temp variable to store collision data
cVector3d collisionPoint0, collisionPoint1;
cVector3d collisionNormal0, collisionNormal1;
double collisionDistanceSq = 0.0;
// compute collision detection between segment and sphere
if (cIntersectionSegmentEllipsoid(a_segmentPointA,
a_segmentPointB,
cVector3d(0.0, 0.0, 0.0),
m_radiusX,
m_radiusY,
m_radiusZ,
collisionPoint0,
collisionNormal0,
collisionPoint1,
collisionNormal1) > 0)
{
hit = true;
collisionDistanceSq = cDistanceSq(a_segmentPointA, collisionPoint0);
}
////////////////////////////////////////////////////////////////////////////
// REPORT COLLISION
////////////////////////////////////////////////////////////////////////////
// here we finally report the new collision to the collision event handler.
if (hit)
{
// we verify if anew collision needs to be created or if we simply
// need to update the nearest collision.
if (a_settings.m_checkForNearestCollisionOnly)
{
// no new collision event is create. We just check if we need
// to update the nearest collision
if(collisionDistanceSq <= a_recorder.m_nearestCollision.m_squareDistance)
{
// report basic collision data
a_recorder.m_nearestCollision.m_type = C_COL_SHAPE;
a_recorder.m_nearestCollision.m_object = this;
a_recorder.m_nearestCollision.m_localPos = collisionPoint0;
a_recorder.m_nearestCollision.m_localNormal = collisionNormal0;
a_recorder.m_nearestCollision.m_squareDistance = collisionDistanceSq;
a_recorder.m_nearestCollision.m_adjustedSegmentAPoint = a_segmentPointA;
// report advanced collision data
if (!a_settings.m_returnMinimalCollisionData)
{
a_recorder.m_nearestCollision.m_globalPos = cAdd(getGlobalPos(),
cMul(getGlobalRot(),
a_recorder.m_nearestCollision.m_localPos));
a_recorder.m_nearestCollision.m_globalNormal = cMul(getGlobalRot(),
a_recorder.m_nearestCollision.m_localNormal);
}
}
}
else
{
cCollisionEvent newCollisionEvent;
// report basic collision data
newCollisionEvent.m_type = C_COL_SHAPE;
newCollisionEvent.m_object = this;
newCollisionEvent.m_triangles = nullptr;
newCollisionEvent.m_localPos = collisionPoint0;
newCollisionEvent.m_localNormal = collisionNormal0;
newCollisionEvent.m_squareDistance = collisionDistanceSq;
newCollisionEvent.m_adjustedSegmentAPoint = a_segmentPointA;
// report advanced collision data
if (!a_settings.m_returnMinimalCollisionData)
{
newCollisionEvent.m_globalPos = cAdd(getGlobalPos(),
cMul(getGlobalRot(),
newCollisionEvent.m_localPos));
newCollisionEvent.m_globalNormal = cMul(getGlobalRot(),
newCollisionEvent.m_localNormal);
}
// add new collision even to collision list
a_recorder.m_collisions.push_back(newCollisionEvent);
// check if this new collision is a candidate for "nearest one"
if(collisionDistanceSq <= a_recorder.m_nearestCollision.m_squareDistance)
{
a_recorder.m_nearestCollision = newCollisionEvent;
}
}
}
// return result
return (hit);
}
//------------------------------------------------------------------------------
} // namespace chai3d
//------------------------------------------------------------------------------
| apache-2.0 |
facebook/fbthrift | thrift/compiler/detail/mustache/test/interpolation_test.cpp | 1 | 5287 | /*
* Copyright (c) Meta Platforms, Inc. and 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 <folly/portability/GTest.h>
#include <thrift/compiler/detail/mustache/mstch.h>
using namespace apache::thrift;
// Mustache-free templates should render as-is.
TEST(InterpolationTEST, NoInterpolation) {
EXPECT_EQ(
"Hello from {Mustache}!\n",
mstch::render("Hello from {Mustache}!\n", mstch::node()));
}
// Unadorned tags should interpolate content into the template.
TEST(InterpolationTEST, BasicInterpolation) {
EXPECT_EQ(
"Hello, world!\n",
mstch::render(
"Hello, {{subject}}!\n",
mstch::map{{"subject", std::string("world")}}));
}
// Integers should interpolate seamlessly.
TEST(InterpolationTEST, BasicIntegerInterpolation) {
EXPECT_EQ(
"\"85 miles an hour!\"",
mstch::render("\"{{mph}} miles an hour!\"", mstch::map{{"mph", 85}}));
}
// Decimals should interpolate seamlessly with proper significance.
TEST(InterpolationTEST, BasicDecimalInterpolation) {
EXPECT_EQ(
"\"1.21 jiggawatts!\"",
mstch::render("\"{{power}} jiggawatts!\"", mstch::map{{"power", 1.21}}));
}
// Failed context lookups should default to empty strings.
TEST(InterpolationTEST, BasicContextMissInterpolation) {
EXPECT_EQ(
"I () be seen!", mstch::render("I ({{cannot}}) be seen!", mstch::node()));
}
// Dotted names should be considered a form of shorthand for sections.
TEST(InterpolationTEST, DottedNamesBasicInterpolation) {
EXPECT_EQ(
"\"Joe\" == \"Joe\"",
mstch::render(
"\"{{person.name}}\" == \"{{#person}}{{name}}{{/person}}\"",
mstch::map{{"person", mstch::map{{"name", std::string("Joe")}}}}));
}
// Dotted names should be functional to any level of nesting.
TEST(InterpolationTEST, DottedNamesArbitraryDepth) {
EXPECT_EQ(
"\"Phil\" == \"Phil\"",
mstch::render(
"\"{{a.b.c.d.e.name}}\" == \"Phil\"",
mstch::map{
{"a",
mstch::map{
{"b",
mstch::map{
{"c",
mstch::map{
{"d",
mstch::map{
{"e",
mstch::map{
{"name",
std::string("Phil")}}}}}}}}}}}}));
}
// Any falsey value prior to the last part of the name should yield ''.
TEST(InterpolationTEST, DottedNamesBrokenChains) {
EXPECT_EQ(
"\"\" == \"\"",
mstch::render("\"{{a.b.c}}\" == \"\"", mstch::map{{"a", mstch::node()}}));
}
// Each part of a dotted name should resolve only against its parent.
TEST(InterpolationTEST, DottedNamesBrokenChainResolution) {
EXPECT_EQ(
"\"\" == \"\"",
mstch::render(
"\"{{a.b.c.name}}\" == \"\"",
mstch::map{
{"a", mstch::map{{"b", mstch::node()}}},
{"c", mstch::map{{"name", std::string("Jim")}}}}));
}
// The first part of a dotted name should resolve as any other name.
TEST(InterpolationTEST, DottedNamesInitialResolution) {
EXPECT_EQ(
"\"Phil\" == \"Phil\"",
mstch::render(
"\"{{#a}}{{b.c.d.e.name}}{{/a}}\" == \"Phil\"",
mstch::map{
{"a",
mstch::map{
{"b",
mstch::map{
{"c",
mstch::map{
{"d",
mstch::map{
{"e",
mstch::map{
{"name", std::string("Phil")}}}}}}}}}}},
{"b",
mstch::map{
{"c",
mstch::map{
{"d",
mstch::map{
{"e",
mstch::map{
{"name", std::string("Wrong")}}}}}}}}}}));
}
// Interpolation should not alter surrounding whitespace.
TEST(InterpolationTEST, InterpolationSurroundingWhitespace) {
EXPECT_EQ(
"| --- |",
mstch::render(
"| {{string}} |", mstch::map{{"string", std::string("---")}}));
}
// Standalone interpolation should not alter surrounding whitespace.
TEST(InterpolationTEST, InterpolationStandalone) {
EXPECT_EQ(
" ---\\n",
mstch::render(
" {{string}}\\n", mstch::map{{"string", std::string("---")}}));
}
// Superfluous in-tag whitespace should be ignored.
TEST(InterpolationTEST, InterpolationWithPadding) {
EXPECT_EQ(
"|---|",
mstch::render(
"|{{ string }}|", mstch::map{{"string", std::string("---")}}));
}
| apache-2.0 |
ucam-smt/ucam-smt | cpp/tests/fstio.gtest.cpp | 1 | 2892 | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use these files 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 2012 - Gonzalo Iglesias, Adrià de Gispert, William Byrne
/** \file
* \brief Unit testing: Input/Output fst operations with compression.
* \date 8-8-2012
* \author Gonzalo Iglesias
*/
#include <openfst.h>
#include <googletesting.h>
#ifndef GMAINTEST
#include "main.custom_assert.hpp"
#include "main.logger.hpp"
#endif
#include "szfstream.hpp"
#include "fstio.hpp"
namespace bfs = boost::filesystem;
namespace googletesting {
///Basic test for input/output enhanced fst operations
///Create an vector/const fst, write to compressed binary format, read back and test that both fsts are equivalent.
TEST ( FstIo, basic_test ) {
fst::VectorFst<fst::StdArc> aux;
aux.AddState();
aux.AddState();
aux.SetStart ( 0 );
aux.SetFinal ( 1, fst::StdArc::Weight::One() );
aux.AddArc ( 0, fst::StdArc ( 10, 10, 0.5, 1 ) );
FstWrite ( aux, "obliviate.fst.gz" );
boost::scoped_ptr< fst::VectorFst<fst::StdArc> > aux2
(fst::VectorFstRead<fst::StdArc> ( "obliviate.fst.gz" ) );
EXPECT_TRUE ( Equivalent ( aux, *aux2 ) );
bfs::remove ( bfs::path ( "obliviate.fst.gz" ) );
fst::ConstFst<fst::StdArc> caux ( aux );
FstWrite ( caux, "const.obliviate.fst.gz" );
FstWrite ( caux, "const.obliviate.txt" );
// // \todo This test is no longer working since openfst 1.3.4 but works in openfst.1.3.2. Needs investigation.
// FstWrite ( caux, "const.obliviate.fst" );
// ucam::util::iszfstream file ( "const.obliviate.fst.gz" );
// fst::FstReadOptions fro;
// fst::ConstFst<fst::StdArc> *h = fst::ConstFst<fst::StdArc>::Read ( *file.getStream(), fro );
// if (h == NULL) {
// LERROR("Ufa?");
// exit(0);
// }
// boost::scoped_ptr< fst::ConstFst<fst::StdArc> > caux2( fst::ConstFstRead<fst::StdArc> ( "const.obliviate.fst.gz" ) ) ;
//EXPECT_TRUE ( Equivalent ( caux, *caux2 ) );
bfs::remove ( bfs::path ( "const.obliviate.fst.gz" ) );
ucam::util::iszfstream isz ( "const.obliviate.txt" );
std::string t, t2;
while ( getline ( isz, t ) ) t2 += t + "\n";
LDEBUG("t2=" << t2);
EXPECT_TRUE ( t2 == "0\t1\t10\t10\t0.5\n1\n"
|| t2 == "0\t1\t10\t0.5\n1\t0\n" ); //openfst 1.5.0
bfs::remove ( bfs::path ( "const.obliviate.txt" ) );
}
};
#ifndef GMAINTEST
int main ( int argc, char **argv ) {
::testing::InitGoogleTest ( &argc, argv );
return RUN_ALL_TESTS();
}
#endif
| apache-2.0 |
google/oss-fuzz | projects/brpc/Fuzz_http.cpp | 1 | 1080 | /* Copyright 2022 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <stdint.h>
#include "brpc/server.h"
#include "brpc/details/http_message.h"
#include "brpc/policy/http_rpc_protocol.h"
#include "echo.pb.h"
#define kMinInputLength 5
#define kMaxInputLength 1024
extern "C" int
LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)
{/*incubator-brpc/test/brpc_http_message_unittest.cpp*/
if (Size < kMinInputLength || Size > kMaxInputLength){
return 0;
}
brpc::HttpMessage http_message;
http_message.ParseFromArray((char *)Data, Size);
return 0;
}
| apache-2.0 |
LiberatorUSA/GUCEF | dependencies/aws-cpp-sdk-s3/source/model/FilterRuleName.cpp | 1 | 2390 | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/s3/model/FilterRuleName.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace S3
{
namespace Model
{
namespace FilterRuleNameMapper
{
static const int prefix_HASH = HashingUtils::HashString("prefix");
static const int suffix_HASH = HashingUtils::HashString("suffix");
FilterRuleName GetFilterRuleNameForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == prefix_HASH)
{
return FilterRuleName::prefix;
}
else if (hashCode == suffix_HASH)
{
return FilterRuleName::suffix;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<FilterRuleName>(hashCode);
}
return FilterRuleName::NOT_SET;
}
Aws::String GetNameForFilterRuleName(FilterRuleName enumValue)
{
switch(enumValue)
{
case FilterRuleName::prefix:
return "prefix";
case FilterRuleName::suffix:
return "suffix";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace FilterRuleNameMapper
} // namespace Model
} // namespace S3
} // namespace Aws
| apache-2.0 |
drankye/kerb-token | krb5/src/lib/rpc/bindresvport.c | 1 | 2680 | /* lib/rpc/bindresvport.c */
/*
* Copyright (c) 2010, Oracle America, 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 the "Oracle America, 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 <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <gssrpc/rpc.h>
#include <errno.h>
/*
* Bind a socket to a privileged IP port
*/
int
bindresvport(int sd, struct sockaddr_in *sockin)
{
int res;
static short port;
struct sockaddr_in myaddr;
int i;
#define STARTPORT 600
#define ENDPORT (IPPORT_RESERVED - 1)
#define NPORTS (ENDPORT - STARTPORT + 1)
if (sockin == (struct sockaddr_in *)0) {
sockin = &myaddr;
memset(sockin, 0, sizeof (*sockin));
sockin->sin_family = AF_INET;
} else if (sockin->sin_family != AF_INET) {
errno = EPFNOSUPPORT;
return (-1);
}
if (port == 0) {
port = (getpid() % NPORTS) + STARTPORT;
}
res = -1;
errno = EADDRINUSE;
for (i = 0; i < NPORTS && res < 0 && errno == EADDRINUSE; i++) {
sockin->sin_port = htons(port++);
if (port > ENDPORT) {
port = STARTPORT;
}
res = bind(sd, (struct sockaddr *) sockin,
sizeof(struct sockaddr_in));
}
return (res);
}
| apache-2.0 |
finikorg/zephyr | subsys/bluetooth/host/keys_br.c | 1 | 5334 | /* keys_br.c - Bluetooth BR/EDR key handling */
/*
* Copyright (c) 2015-2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h>
#include <string.h>
#include <zephyr/sys/atomic.h>
#include <zephyr/sys/util.h>
#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/hci.h>
#include <zephyr/settings/settings.h>
#define BT_DBG_ENABLED IS_ENABLED(CONFIG_BT_DEBUG_KEYS)
#define LOG_MODULE_NAME bt_keys_br
#include "common/log.h"
#include "hci_core.h"
#include "settings.h"
#include "keys.h"
static struct bt_keys_link_key key_pool[CONFIG_BT_MAX_PAIRED];
#if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
static uint32_t aging_counter_val;
static struct bt_keys_link_key *last_keys_updated;
#endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
struct bt_keys_link_key *bt_keys_find_link_key(const bt_addr_t *addr)
{
struct bt_keys_link_key *key;
int i;
BT_DBG("%s", bt_addr_str(addr));
for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
key = &key_pool[i];
if (!bt_addr_cmp(&key->addr, addr)) {
return key;
}
}
return NULL;
}
struct bt_keys_link_key *bt_keys_get_link_key(const bt_addr_t *addr)
{
struct bt_keys_link_key *key;
key = bt_keys_find_link_key(addr);
if (key) {
return key;
}
key = bt_keys_find_link_key(BT_ADDR_ANY);
#if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
if (!key) {
int i;
key = &key_pool[0];
for (i = 1; i < ARRAY_SIZE(key_pool); i++) {
struct bt_keys_link_key *current = &key_pool[i];
if (current->aging_counter < key->aging_counter) {
key = current;
}
}
if (key) {
bt_keys_link_key_clear(key);
}
}
#endif
if (key) {
bt_addr_copy(&key->addr, addr);
#if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
key->aging_counter = ++aging_counter_val;
last_keys_updated = key;
#endif
BT_DBG("created %p for %s", key, bt_addr_str(addr));
return key;
}
BT_DBG("unable to create keys for %s", bt_addr_str(addr));
return NULL;
}
void bt_keys_link_key_clear(struct bt_keys_link_key *link_key)
{
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
char key[BT_SETTINGS_KEY_MAX];
bt_addr_le_t le_addr;
le_addr.type = BT_ADDR_LE_PUBLIC;
bt_addr_copy(&le_addr.a, &link_key->addr);
bt_settings_encode_key(key, sizeof(key), "link_key",
&le_addr, NULL);
settings_delete(key);
}
BT_DBG("%s", bt_addr_str(&link_key->addr));
(void)memset(link_key, 0, sizeof(*link_key));
}
void bt_keys_link_key_clear_addr(const bt_addr_t *addr)
{
int i;
struct bt_keys_link_key *key;
if (!addr) {
for (i = 0; i < ARRAY_SIZE(key_pool); i++) {
key = &key_pool[i];
bt_keys_link_key_clear(key);
}
return;
}
key = bt_keys_find_link_key(addr);
if (key) {
bt_keys_link_key_clear(key);
}
}
void bt_keys_link_key_store(struct bt_keys_link_key *link_key)
{
if (IS_ENABLED(CONFIG_BT_SETTINGS)) {
int err;
char key[BT_SETTINGS_KEY_MAX];
bt_addr_le_t le_addr;
le_addr.type = BT_ADDR_LE_PUBLIC;
bt_addr_copy(&le_addr.a, &link_key->addr);
bt_settings_encode_key(key, sizeof(key), "link_key",
&le_addr, NULL);
err = settings_save_one(key, link_key->storage_start,
BT_KEYS_LINK_KEY_STORAGE_LEN);
if (err) {
BT_ERR("Failed to save link key (err %d)", err);
}
}
}
#if defined(CONFIG_BT_SETTINGS)
static int link_key_set(const char *name, size_t len_rd,
settings_read_cb read_cb, void *cb_arg)
{
int err;
ssize_t len;
bt_addr_le_t le_addr;
struct bt_keys_link_key *link_key;
char val[BT_KEYS_LINK_KEY_STORAGE_LEN];
if (!name) {
BT_ERR("Insufficient number of arguments");
return -EINVAL;
}
len = read_cb(cb_arg, val, sizeof(val));
if (len < 0) {
BT_ERR("Failed to read value (err %zu)", len);
return -EINVAL;
}
BT_DBG("name %s val %s", name,
len ? bt_hex(val, sizeof(val)) : "(null)");
err = bt_settings_decode_key(name, &le_addr);
if (err) {
BT_ERR("Unable to decode address %s", name);
return -EINVAL;
}
link_key = bt_keys_get_link_key(&le_addr.a);
if (len != BT_KEYS_LINK_KEY_STORAGE_LEN) {
if (link_key) {
bt_keys_link_key_clear(link_key);
BT_DBG("Clear keys for %s", bt_addr_le_str(&le_addr));
} else {
BT_WARN("Unable to find deleted keys for %s",
bt_addr_le_str(&le_addr));
}
return 0;
}
memcpy(link_key->storage_start, val, len);
BT_DBG("Successfully restored link key for %s",
bt_addr_le_str(&le_addr));
#if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
if (aging_counter_val < link_key->aging_counter) {
aging_counter_val = link_key->aging_counter;
}
#endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
return 0;
}
SETTINGS_STATIC_HANDLER_DEFINE(bt_link_key, "bt/link_key", NULL, link_key_set,
NULL, NULL);
#if IS_ENABLED(CONFIG_BT_KEYS_OVERWRITE_OLDEST)
void bt_keys_link_key_update_usage(const bt_addr_t *addr)
{
struct bt_keys_link_key *link_key = bt_keys_find_link_key(addr);
if (!link_key) {
return;
}
if (last_keys_updated == link_key) {
return;
}
link_key->aging_counter = ++aging_counter_val;
last_keys_updated = link_key;
BT_DBG("Aging counter for %s is set to %u", bt_addr_str(addr),
link_key->aging_counter);
if (IS_ENABLED(CONFIG_BT_KEYS_SAVE_AGING_COUNTER_ON_PAIRING)) {
bt_keys_link_key_store(link_key);
}
}
#endif /* CONFIG_BT_KEYS_OVERWRITE_OLDEST */
#endif /* defined(CONFIG_BT_SETTINGS) */
| apache-2.0 |
cedral/aws-sdk-cpp | aws-cpp-sdk-quicksight/source/model/UpdateDataSetRequest.cpp | 2 | 3701 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/quicksight/model/UpdateDataSetRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::QuickSight::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
UpdateDataSetRequest::UpdateDataSetRequest() :
m_awsAccountIdHasBeenSet(false),
m_dataSetIdHasBeenSet(false),
m_nameHasBeenSet(false),
m_physicalTableMapHasBeenSet(false),
m_logicalTableMapHasBeenSet(false),
m_importMode(DataSetImportMode::NOT_SET),
m_importModeHasBeenSet(false),
m_columnGroupsHasBeenSet(false),
m_fieldFoldersHasBeenSet(false),
m_rowLevelPermissionDataSetHasBeenSet(false),
m_rowLevelPermissionTagConfigurationHasBeenSet(false),
m_columnLevelPermissionRulesHasBeenSet(false),
m_dataSetUsageConfigurationHasBeenSet(false)
{
}
Aws::String UpdateDataSetRequest::SerializePayload() const
{
JsonValue payload;
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_physicalTableMapHasBeenSet)
{
JsonValue physicalTableMapJsonMap;
for(auto& physicalTableMapItem : m_physicalTableMap)
{
physicalTableMapJsonMap.WithObject(physicalTableMapItem.first, physicalTableMapItem.second.Jsonize());
}
payload.WithObject("PhysicalTableMap", std::move(physicalTableMapJsonMap));
}
if(m_logicalTableMapHasBeenSet)
{
JsonValue logicalTableMapJsonMap;
for(auto& logicalTableMapItem : m_logicalTableMap)
{
logicalTableMapJsonMap.WithObject(logicalTableMapItem.first, logicalTableMapItem.second.Jsonize());
}
payload.WithObject("LogicalTableMap", std::move(logicalTableMapJsonMap));
}
if(m_importModeHasBeenSet)
{
payload.WithString("ImportMode", DataSetImportModeMapper::GetNameForDataSetImportMode(m_importMode));
}
if(m_columnGroupsHasBeenSet)
{
Array<JsonValue> columnGroupsJsonList(m_columnGroups.size());
for(unsigned columnGroupsIndex = 0; columnGroupsIndex < columnGroupsJsonList.GetLength(); ++columnGroupsIndex)
{
columnGroupsJsonList[columnGroupsIndex].AsObject(m_columnGroups[columnGroupsIndex].Jsonize());
}
payload.WithArray("ColumnGroups", std::move(columnGroupsJsonList));
}
if(m_fieldFoldersHasBeenSet)
{
JsonValue fieldFoldersJsonMap;
for(auto& fieldFoldersItem : m_fieldFolders)
{
fieldFoldersJsonMap.WithObject(fieldFoldersItem.first, fieldFoldersItem.second.Jsonize());
}
payload.WithObject("FieldFolders", std::move(fieldFoldersJsonMap));
}
if(m_rowLevelPermissionDataSetHasBeenSet)
{
payload.WithObject("RowLevelPermissionDataSet", m_rowLevelPermissionDataSet.Jsonize());
}
if(m_rowLevelPermissionTagConfigurationHasBeenSet)
{
payload.WithObject("RowLevelPermissionTagConfiguration", m_rowLevelPermissionTagConfiguration.Jsonize());
}
if(m_columnLevelPermissionRulesHasBeenSet)
{
Array<JsonValue> columnLevelPermissionRulesJsonList(m_columnLevelPermissionRules.size());
for(unsigned columnLevelPermissionRulesIndex = 0; columnLevelPermissionRulesIndex < columnLevelPermissionRulesJsonList.GetLength(); ++columnLevelPermissionRulesIndex)
{
columnLevelPermissionRulesJsonList[columnLevelPermissionRulesIndex].AsObject(m_columnLevelPermissionRules[columnLevelPermissionRulesIndex].Jsonize());
}
payload.WithArray("ColumnLevelPermissionRules", std::move(columnLevelPermissionRulesJsonList));
}
if(m_dataSetUsageConfigurationHasBeenSet)
{
payload.WithObject("DataSetUsageConfiguration", m_dataSetUsageConfiguration.Jsonize());
}
return payload.View().WriteReadable();
}
| apache-2.0 |
milanlenco/vpp | src/plugins/ioam/encap/ip6_ioam_pot.c | 2 | 7624 | /*
* 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 <vlib/vlib.h>
#include <vnet/vnet.h>
#include <vnet/pg/pg.h>
#include <vppinfra/error.h>
#include <vnet/ip/ip6.h>
#include <vppinfra/hash.h>
#include <vppinfra/error.h>
#include <vppinfra/elog.h>
#include <ioam/encap/ip6_ioam_pot.h>
#include <ioam/lib-pot/pot_util.h>
#define foreach_ip6_hop_by_hop_ioam_pot_stats \
_(PROCESSED, "Pkts with ip6 hop-by-hop pot options") \
_(PROFILE_MISS, "Pkts with ip6 hop-by-hop pot options but no profile set") \
_(PASSED, "Pkts with POT in Policy") \
_(FAILED, "Pkts with POT out of Policy")
static char * ip6_hop_by_hop_ioam_pot_stats_strings[] = {
#define _(sym,string) string,
foreach_ip6_hop_by_hop_ioam_pot_stats
#undef _
};
typedef enum {
#define _(sym,str) IP6_IOAM_POT_##sym,
foreach_ip6_hop_by_hop_ioam_pot_stats
#undef _
IP6_IOAM_POT_N_STATS,
} ip6_ioam_pot_stats_t;
typedef struct {
/* stats */
u64 counters[ARRAY_LEN(ip6_hop_by_hop_ioam_pot_stats_strings)];
/* convenience */
vlib_main_t * vlib_main;
vnet_main_t * vnet_main;
} ip6_hop_by_hop_ioam_pot_main_t;
ip6_hop_by_hop_ioam_pot_main_t ip6_hop_by_hop_ioam_pot_main;
always_inline void
ip6_ioam_stats_increment_counter (u32 counter_index, u64 increment)
{
ip6_hop_by_hop_ioam_pot_main_t *hm = &ip6_hop_by_hop_ioam_pot_main;
hm->counters[counter_index] += increment;
}
static u8 * format_ioam_pot (u8 * s, va_list * args)
{
ioam_pot_option_t * pot0 = va_arg (*args, ioam_pot_option_t *);
u64 random, cumulative;
random = cumulative = 0;
if (pot0)
{
random = clib_net_to_host_u64 (pot0->random);
cumulative = clib_net_to_host_u64 (pot0->cumulative);
}
s = format (s, "random = 0x%Lx, Cumulative = 0x%Lx, Index = 0x%x",
random, cumulative, pot0 ? pot0->reserved_profile_id : ~0);
return s;
}
u8 *
ip6_hbh_ioam_proof_of_transit_trace_handler (u8 *s, ip6_hop_by_hop_option_t *opt)
{
ioam_pot_option_t *pot;
s = format (s, " POT opt present\n");
pot = (ioam_pot_option_t *) opt;
s = format (s, " %U\n", format_ioam_pot, pot);
return (s);
}
int
ip6_hbh_ioam_proof_of_transit_handler (vlib_buffer_t *b,
ip6_header_t *ip,
ip6_hop_by_hop_option_t *opt0)
{
ioam_pot_option_t * pot0;
u64 random = 0, cumulative = 0;
int rv = 0;
u8 pot_profile_index;
pot_profile *pot_profile = 0, *new_profile = 0;
u8 pot_encap = 0;
pot0 = (ioam_pot_option_t *) opt0;
pot_encap = (pot0->random == 0);
pot_profile_index = pot_profile_get_active_id();
pot_profile = pot_profile_get_active();
if (pot_encap && PREDICT_FALSE(!pot_profile))
{
ip6_ioam_stats_increment_counter (IP6_IOAM_POT_PROFILE_MISS, 1);
return(-1);
}
if (pot_encap)
{
pot0->reserved_profile_id =
pot_profile_index & PROFILE_ID_MASK;
pot_profile_incr_usage_stats(pot_profile);
}
else
{ /* Non encap node */
if (PREDICT_FALSE(pot0->reserved_profile_id !=
pot_profile_index || pot_profile == 0))
{
/* New profile announced by encap node. */
new_profile =
pot_profile_find(pot0->reserved_profile_id);
if (PREDICT_FALSE(new_profile == 0 ||
new_profile->valid == 0))
{
ip6_ioam_stats_increment_counter (IP6_IOAM_POT_PROFILE_MISS, 1);
return(-1);
}
else
{
pot_profile_index = pot0->reserved_profile_id;
pot_profile = new_profile;
pot_profile_set_active(pot_profile_index);
pot_profile_reset_usage_stats(pot_profile);
}
}
pot_profile_incr_usage_stats(pot_profile);
}
if (pot0->random == 0)
{
pot0->random = clib_host_to_net_u64(pot_generate_random(pot_profile));
pot0->cumulative = 0;
}
random = clib_net_to_host_u64(pot0->random);
cumulative = clib_net_to_host_u64(pot0->cumulative);
pot0->cumulative = clib_host_to_net_u64(
pot_update_cumulative(pot_profile,
cumulative,
random));
ip6_ioam_stats_increment_counter (IP6_IOAM_POT_PROCESSED, 1);
return (rv);
}
int
ip6_hbh_ioam_proof_of_transit_pop_handler (vlib_buffer_t *b, ip6_header_t *ip,
ip6_hop_by_hop_option_t *opt0)
{
ioam_pot_option_t * pot0;
u64 random = 0;
u64 cumulative = 0;
int rv = 0;
pot_profile *pot_profile = 0;
u8 result = 0;
pot0 = (ioam_pot_option_t *) opt0;
random = clib_net_to_host_u64(pot0->random);
cumulative = clib_net_to_host_u64(pot0->cumulative);
pot_profile = pot_profile_get_active();
result = pot_validate (pot_profile,
cumulative, random);
if (result == 1)
{
ip6_ioam_stats_increment_counter (IP6_IOAM_POT_PASSED, 1);
}
else
{
ip6_ioam_stats_increment_counter (IP6_IOAM_POT_FAILED, 1);
}
return (rv);
}
int ip6_hop_by_hop_ioam_pot_rewrite_handler (u8 *rewrite_string, u8 *rewrite_size)
{
ioam_pot_option_t * pot_option;
if (rewrite_string && *rewrite_size == sizeof(ioam_pot_option_t))
{
pot_option = (ioam_pot_option_t *)rewrite_string;
pot_option->hdr.type = HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT
| HBH_OPTION_TYPE_DATA_CHANGE_ENROUTE;
pot_option->hdr.length = sizeof (ioam_pot_option_t) -
sizeof (ip6_hop_by_hop_option_t);
return(0);
}
return(-1);
}
static clib_error_t *
ip6_show_ioam_pot_cmd_fn (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
ip6_hop_by_hop_ioam_pot_main_t *hm = &ip6_hop_by_hop_ioam_pot_main;
u8 *s = 0;
int i = 0;
for ( i = 0; i < IP6_IOAM_POT_N_STATS; i++)
{
s = format(s, " %s - %lu\n", ip6_hop_by_hop_ioam_pot_stats_strings[i],
hm->counters[i]);
}
vlib_cli_output(vm, "%v", s);
vec_free(s);
return 0;
}
VLIB_CLI_COMMAND (ip6_show_ioam_pot_cmd, static) = {
.path = "show ioam pot",
.short_help = "iOAM pot statistics",
.function = ip6_show_ioam_pot_cmd_fn,
};
static clib_error_t *
ip6_hop_by_hop_ioam_pot_init (vlib_main_t * vm)
{
ip6_hop_by_hop_ioam_pot_main_t * hm = &ip6_hop_by_hop_ioam_pot_main;
clib_error_t * error;
if ((error = vlib_call_init_function (vm, ip6_hop_by_hop_ioam_init)))
return(error);
hm->vlib_main = vm;
hm->vnet_main = vnet_get_main();
memset(hm->counters, 0, sizeof(hm->counters));
if (ip6_hbh_register_option(HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT, ip6_hbh_ioam_proof_of_transit_handler,
ip6_hbh_ioam_proof_of_transit_trace_handler) < 0)
return (clib_error_create("registration of HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT failed"));
if (ip6_hbh_add_register_option(HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT,
sizeof(ioam_pot_option_t),
ip6_hop_by_hop_ioam_pot_rewrite_handler) < 0)
return (clib_error_create("registration of HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT for rewrite failed"));
if (ip6_hbh_pop_register_option(HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT,
ip6_hbh_ioam_proof_of_transit_pop_handler) < 0)
return (clib_error_create("registration of HBH_OPTION_TYPE_IOAM_PROOF_OF_TRANSIT POP failed"));
return (0);
}
VLIB_INIT_FUNCTION (ip6_hop_by_hop_ioam_pot_init);
| apache-2.0 |
dAck2cC2/m3e | src/system/media/audio_utils/tests/fifo_tests.cpp | 2 | 8753 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Test program for audio_utils FIFO library.
// This only tests the single-threaded aspects, not the barriers.
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <audio_utils/fifo.h>
#include <audio_utils/sndfile.h>
#ifndef min
#define min(x, y) (((x) < (y)) ? (x) : (y))
#endif
int main(int argc, char **argv)
{
size_t frameCount = 0;
size_t maxFramesPerRead = 0;
size_t maxFramesPerWrite = 0;
bool readerThrottlesWriter = true;
bool verbose = false;
int i;
for (i = 1; i < argc; i++) {
char *arg = argv[i];
if (arg[0] != '-')
break;
switch (arg[1]) {
case 'f': // FIFO frame count
frameCount = atoi(&arg[2]);
break;
case 'r': // maximum frame count per read from FIFO
maxFramesPerRead = atoi(&arg[2]);
break;
case 't': // disable throttling of writer by reader
readerThrottlesWriter = false;
break;
case 'v': // enable verbose logging
verbose = true;
break;
case 'w': // maximum frame count per write to FIFO
maxFramesPerWrite = atoi(&arg[2]);
break;
default:
fprintf(stderr, "%s: unknown option %s\n", argv[0], arg);
goto usage;
}
}
if (frameCount == 0) {
frameCount = 256;
}
if (maxFramesPerRead == 0) {
maxFramesPerRead = frameCount;
}
if (maxFramesPerWrite == 0) {
maxFramesPerWrite = frameCount;
}
if (argc - i != 2) {
usage:
fprintf(stderr, "usage: %s [-f#] [-r#] [-t] [-v] [-w#] in.wav out.wav\n", argv[0]);
return EXIT_FAILURE;
}
char *inputFile = argv[i];
char *outputFile = argv[i+1];
SF_INFO sfinfoin;
memset(&sfinfoin, 0, sizeof(sfinfoin));
SNDFILE *sfin = sf_open(inputFile, SFM_READ, &sfinfoin);
if (sfin == NULL) {
perror(inputFile);
return EXIT_FAILURE;
}
switch (sfinfoin.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_SUBMASK)) {
case SF_FORMAT_WAV | SF_FORMAT_PCM_16:
case SF_FORMAT_WAV | SF_FORMAT_PCM_U8:
break;
default:
fprintf(stderr, "%s: unsupported format\n", inputFile);
sf_close(sfin);
return EXIT_FAILURE;
}
size_t frameSize = sizeof(int16_t) * sfinfoin.channels;
int16_t *inputBuffer = new int16_t[sfinfoin.frames * sfinfoin.channels];
sf_count_t actualRead = sf_readf_short(sfin, inputBuffer, sfinfoin.frames);
if (actualRead != sfinfoin.frames) {
fprintf(stderr, "%s: unexpected EOF or error\n", inputFile);
sf_close(sfin);
return EXIT_FAILURE;
}
sf_close(sfin);
int16_t *outputBuffer = new int16_t[sfinfoin.frames * sfinfoin.channels];
size_t framesWritten = 0;
size_t framesRead = 0;
int16_t *fifoBuffer = new int16_t[frameCount * sfinfoin.channels];
audio_utils_fifo fifo(frameCount, frameSize, fifoBuffer, readerThrottlesWriter);
audio_utils_fifo_writer fifoWriter(fifo);
audio_utils_fifo_reader fifoReader(fifo, readerThrottlesWriter);
int fifoWriteCount = 0, fifoReadCount = 0;
int fifoFillLevel = 0, minFillLevel = INT_MAX, maxFillLevel = INT_MIN;
for (;;) {
size_t framesToWrite = sfinfoin.frames - framesWritten;
size_t framesToRead = sfinfoin.frames - framesRead;
if (framesToWrite == 0 && (framesToRead == 0 || !readerThrottlesWriter)) {
break;
}
if (framesToWrite > maxFramesPerWrite) {
framesToWrite = maxFramesPerWrite;
}
framesToWrite = rand() % (framesToWrite + 1);
ssize_t actualWritten = fifoWriter.write(
&inputBuffer[framesWritten * sfinfoin.channels], framesToWrite);
if (verbose) {
printf("wrote %d out of %d\n", (int) actualWritten, (int) framesToWrite);
}
if (actualWritten < 0 || (size_t) actualWritten > framesToWrite) {
fprintf(stderr, "write to FIFO failed\n");
break;
}
if (actualWritten < min((int) frameCount - fifoFillLevel, (int) framesToWrite)) {
fprintf(stderr, "only wrote %d when should have written min(%d, %d)\n",
(int) actualWritten, (int) frameCount - fifoFillLevel, (int) framesToWrite);
}
framesWritten += actualWritten;
if (actualWritten > 0) {
fifoWriteCount++;
}
fifoFillLevel += actualWritten;
if (verbose) {
printf("fill level after write %d\n", fifoFillLevel);
}
if (fifoFillLevel > maxFillLevel) {
maxFillLevel = fifoFillLevel;
if (maxFillLevel > (int) frameCount) {
if (readerThrottlesWriter) {
printf("maxFillLevel=%d > frameCount=%d\n", maxFillLevel, (int) frameCount);
abort();
}
}
}
if (framesToRead > maxFramesPerRead) {
framesToRead = maxFramesPerRead;
}
framesToRead = rand() % (framesToRead + 1);
ssize_t actualRead = fifoReader.read(
&outputBuffer[framesRead * sfinfoin.channels], framesToRead);
if (verbose) {
printf("read %d out of %d\n", (int) actualRead, (int) framesToRead);
}
if (actualRead < 0 || (size_t) actualRead > framesToRead) {
switch (actualRead) {
case -EIO:
fprintf(stderr, "read from FIFO failed: corrupted indices\n");
abort();
break;
case -EOVERFLOW:
if (readerThrottlesWriter) {
fprintf(stderr, "read from FIFO failed: unexpected overflow\n");
abort();
}
printf("warning: reader lost frames\n");
actualRead = 0;
break;
default:
if (actualRead < 0) {
fprintf(stderr, "read from FIFO failed: unexpected error code %d\n",
(int) actualRead);
} else {
fprintf(stderr, "read from FIFO failed: actualRead=%d > framesToRead=%d\n",
(int) actualRead, (int) framesToRead);
}
abort();
}
}
if (actualRead < min(fifoFillLevel, (int) framesToRead)) {
//fprintf(stderr, "only read %d when should have read min(%d, %d)\n",
// (int) actualRead, fifoFillLevel, (int) framesToRead);
}
framesRead += actualRead;
if (actualRead > 0) {
fifoReadCount++;
}
fifoFillLevel -= actualRead;
if (verbose) {
printf("fill level after read %d\n", fifoFillLevel);
}
if (fifoFillLevel < minFillLevel) {
minFillLevel = fifoFillLevel;
if (minFillLevel < 0) {
printf("minFillLevel=%d < 0\n", minFillLevel);
abort();
}
}
}
delete[] inputBuffer;
inputBuffer = NULL;
delete[] fifoBuffer;
fifoBuffer = NULL;
printf("FIFO non-empty writes: %d, non-empty reads: %d\n", fifoWriteCount, fifoReadCount);
printf("fill=%d, min=%d, max=%d\n", fifoFillLevel, minFillLevel, maxFillLevel);
printf("writing output\n");
SF_INFO sfinfoout;
memset(&sfinfoout, 0, sizeof(sfinfoout));
sfinfoout.samplerate = sfinfoin.samplerate;
sfinfoout.channels = sfinfoin.channels;
sfinfoout.format = sfinfoin.format;
SNDFILE *sfout = sf_open(outputFile, SFM_WRITE, &sfinfoout);
if (sfout == NULL) {
perror(outputFile);
return EXIT_FAILURE;
}
sf_count_t actualWritten = sf_writef_short(sfout, outputBuffer, framesRead);
delete[] outputBuffer;
outputBuffer = NULL;
if (actualWritten != (sf_count_t) framesRead) {
fprintf(stderr, "%s: unexpected error\n", outputFile);
sf_close(sfout);
return EXIT_FAILURE;
}
sf_close(sfout);
printf("done\n");
return EXIT_SUCCESS;
}
| apache-2.0 |
nashif/zephyr | samples/bluetooth/eddystone/src/main.c | 2 | 20563 | /* main.c - Application main entry point */
/*
* Copyright (c) 2015-2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/types.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <sys/printk.h>
#include <sys/util.h>
#include <sys/byteorder.h>
#include <zephyr.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/conn.h>
#include <bluetooth/uuid.h>
#include <bluetooth/gatt.h>
#define NUMBER_OF_SLOTS 1
#define EDS_VERSION 0x00
#define EDS_URL_READ_OFFSET 2
#define EDS_URL_WRITE_OFFSET 4
#define EDS_IDLE_TIMEOUT K_SECONDS(30)
/* Idle timer */
struct k_delayed_work idle_work;
static const struct bt_data ad[] = {
BT_DATA_BYTES(BT_DATA_FLAGS, (BT_LE_AD_GENERAL | BT_LE_AD_NO_BREDR)),
/* Eddystone Service UUID a3c87500-8ed3-4bdf-8a39-a01bebede295 */
BT_DATA_BYTES(BT_DATA_UUID128_ALL,
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x00, 0x75, 0xc8, 0xa3),
};
/* Eddystone Service Variables */
/* Service UUID a3c87500-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x00, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87501-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_caps_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x01, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87502-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_slot_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x02, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87503-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_intv_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x03, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87504-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_tx_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x04, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87505-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_adv_tx_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x05, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87506-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_lock_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x06, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87507-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_unlock_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x07, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87508-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_ecdh_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x08, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c87509-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_eid_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x09, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c8750a-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_data_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x0a, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c8750b-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_reset_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x0b, 0x75, 0xc8, 0xa3);
/* Characteristic UUID a3c8750c-8ed3-4bdf-8a39-a01bebede295 */
static struct bt_uuid_128 eds_connectable_uuid = BT_UUID_INIT_128(
0x95, 0xe2, 0xed, 0xeb, 0x1b, 0xa0, 0x39, 0x8a,
0xdf, 0x4b, 0xd3, 0x8e, 0x0c, 0x75, 0xc8, 0xa3);
enum {
EDS_TYPE_UID = 0x00,
EDS_TYPE_URL = 0x10,
EDS_TYPE_TLM = 0x20,
EDS_TYPE_EID = 0x30,
EDS_TYPE_NONE = 0xff,
};
enum {
EDS_SLOT_UID = sys_cpu_to_be16(BIT(0)),
EDS_SLOT_URL = sys_cpu_to_be16(BIT(1)),
EDS_SLOT_TLM = sys_cpu_to_be16(BIT(2)),
EDS_SLOT_EID = sys_cpu_to_be16(BIT(3)),
};
struct eds_capabilities {
uint8_t version;
uint8_t slots;
uint8_t uids;
uint8_t adv_types;
uint16_t slot_types;
uint8_t tx_power;
} __packed;
static struct eds_capabilities eds_caps = {
.version = EDS_VERSION,
.slots = NUMBER_OF_SLOTS,
.slot_types = EDS_SLOT_URL, /* TODO: Add support for other slot types */
};
uint8_t eds_active_slot;
enum {
EDS_LOCKED = 0x00,
EDS_UNLOCKED = 0x01,
EDS_UNLOCKED_NO_RELOCKING = 0x02,
};
struct eds_slot {
uint8_t type;
uint8_t state;
uint8_t connectable;
uint16_t interval;
uint8_t tx_power;
uint8_t adv_tx_power;
uint8_t lock[16];
uint8_t challenge[16];
struct bt_data ad[3];
};
static struct eds_slot eds_slots[NUMBER_OF_SLOTS] = {
[0 ... (NUMBER_OF_SLOTS - 1)] = {
.type = EDS_TYPE_NONE, /* Start as disabled */
.state = EDS_UNLOCKED, /* Start unlocked */
.interval = sys_cpu_to_be16(BT_GAP_ADV_FAST_INT_MIN_2),
.lock = { 'Z', 'e', 'p', 'h', 'y', 'r', ' ', 'E', 'd', 'd',
'y', 's', 't', 'o', 'n', 'e' },
.challenge = {},
.ad = {
BT_DATA_BYTES(BT_DATA_FLAGS, BT_LE_AD_NO_BREDR),
BT_DATA_BYTES(BT_DATA_UUID16_ALL, 0xaa, 0xfe),
BT_DATA_BYTES(BT_DATA_SVC_DATA16,
0xaa, 0xfe, /* Eddystone UUID */
0x10, /* Eddystone-URL frame type */
0x00, /* Calibrated Tx power at 0m */
0x00, /* URL Scheme Prefix http://www. */
'z', 'e', 'p', 'h', 'y', 'r',
'p', 'r', 'o', 'j', 'e', 'c', 't',
0x08) /* .org */
},
},
};
static ssize_t read_caps(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
const struct eds_capabilities *caps = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, caps,
sizeof(*caps));
}
static ssize_t read_slot(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
return bt_gatt_attr_read(conn, attr, buf, len, offset,
&eds_active_slot, sizeof(eds_active_slot));
}
static ssize_t write_slot(struct bt_conn *conn,
const struct bt_gatt_attr *attr, const void *buf,
uint16_t len, uint16_t offset, uint8_t flags)
{
uint8_t value;
if (offset + len > sizeof(value)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
memcpy(&value, buf, len);
if (value + 1 > NUMBER_OF_SLOTS) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
eds_active_slot = value;
return len;
}
static ssize_t read_tx_power(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_READ_NOT_PERMITTED);
}
return bt_gatt_attr_read(conn, attr, buf, len, offset, &slot->tx_power,
sizeof(slot->tx_power));
}
static ssize_t write_tx_power(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf, uint16_t len, uint16_t offset,
uint8_t flags)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
if (offset + len > sizeof(slot->tx_power)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
memcpy(&slot->tx_power, buf, len);
return len;
}
static ssize_t read_adv_tx_power(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_READ_NOT_PERMITTED);
}
return bt_gatt_attr_read(conn, attr, buf, len, offset, &slot->tx_power,
sizeof(slot->tx_power));
}
static ssize_t write_adv_tx_power(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf, uint16_t len,
uint16_t offset,
uint8_t flags)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
if (offset + len > sizeof(slot->adv_tx_power)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
memcpy(&slot->adv_tx_power, buf, len);
return len;
}
static ssize_t read_interval(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
return bt_gatt_attr_read(conn, attr, buf, len, offset, &slot->interval,
sizeof(slot->interval));
}
static ssize_t read_lock(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
return bt_gatt_attr_read(conn, attr, buf, len, offset, &slot->state,
sizeof(slot->state));
}
static ssize_t write_lock(struct bt_conn *conn,
const struct bt_gatt_attr *attr, const void *buf,
uint16_t len, uint16_t offset, uint8_t flags)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
uint8_t value;
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
if (offset) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
/* Write 1 byte to lock or 17 bytes to transition to a new lock state */
if (len != 1U) {
/* TODO: Allow setting new lock code, using AES-128-ECB to
* decrypt with the existing lock code and set the unencrypted
* value as the new code.
*/
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
memcpy(&value, buf, sizeof(value));
if (value > EDS_UNLOCKED_NO_RELOCKING) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
slot->state = value;
return len;
}
static ssize_t read_unlock(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state != EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_READ_NOT_PERMITTED);
}
/* returns a 128-bit challenge token. This token is for one-time use
* and cannot be replayed.
*/
if (bt_rand(slot->challenge, sizeof(slot->challenge))) {
return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);
}
return bt_gatt_attr_read(conn, attr, buf, len, offset, slot->challenge,
sizeof(slot->challenge));
}
static ssize_t write_unlock(struct bt_conn *conn,
const struct bt_gatt_attr *attr, const void *buf,
uint16_t len, uint16_t offset, uint8_t flags)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state != EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_READ_NOT_PERMITTED);
}
/* TODO: accepts a 128-bit encrypted value that verifies the client
* knows the beacon's lock code.
*/
return BT_GATT_ERR(BT_ATT_ERR_NOT_SUPPORTED);
}
static uint8_t eds_ecdh[32] = {}; /* TODO: Add ECDH key */
static ssize_t read_ecdh(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
uint8_t *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
sizeof(eds_ecdh));
}
static uint8_t eds_eid[16] = {}; /* TODO: Add EID key */
static ssize_t read_eid(struct bt_conn *conn, const struct bt_gatt_attr *attr,
void *buf, uint16_t len, uint16_t offset)
{
uint8_t *value = attr->user_data;
return bt_gatt_attr_read(conn, attr, buf, len, offset, value,
sizeof(eds_eid));
}
static ssize_t read_adv_data(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
uint16_t len, uint16_t offset)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_READ_NOT_PERMITTED);
}
/* If the slot is currently not broadcasting, reading the slot data
* shall return either an empty array or a single byte of 0x00.
*/
if (slot->type == EDS_TYPE_NONE) {
return 0;
}
return bt_gatt_attr_read(conn, attr, buf, len, offset,
slot->ad[2].data + EDS_URL_READ_OFFSET,
slot->ad[2].data_len - EDS_URL_READ_OFFSET);
}
static int eds_slot_restart(struct eds_slot *slot, uint8_t type)
{
int err;
char addr_s[BT_ADDR_LE_STR_LEN];
bt_addr_le_t addr = {0};
/* Restart advertising */
bt_le_adv_stop();
if (type == EDS_TYPE_NONE) {
struct bt_le_oob oob;
/* Restore connectable if slot */
if (bt_le_oob_get_local(BT_ID_DEFAULT, &oob) == 0) {
addr = oob.addr;
}
err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad),
NULL, 0);
} else {
size_t count = 1;
bt_id_get(&addr, &count);
err = bt_le_adv_start(BT_LE_ADV_NCONN_IDENTITY, slot->ad,
ARRAY_SIZE(slot->ad), NULL, 0);
}
if (err) {
printk("Advertising failed to start (err %d)\n", err);
return err;
}
bt_addr_le_to_str(&addr, addr_s, sizeof(addr_s));
printk("Advertising as %s\n", addr_s);
slot->type = type;
return 0;
}
static ssize_t write_adv_data(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf, uint16_t len, uint16_t offset,
uint8_t flags)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
uint8_t type;
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_READ_NOT_PERMITTED);
}
if (offset) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
/* Writing an empty array, clears the slot and stops Tx. */
if (!len) {
eds_slot_restart(slot, EDS_TYPE_NONE);
return len;
}
/* Write length: 17 bytes (UID), 19 bytes (URL), 1 byte (TLM), 34 or
* 18 bytes (EID)
*/
if (len > 19) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
memcpy(&type, buf, sizeof(type));
switch (type) {
case EDS_TYPE_URL:
/* written data is just the frame type and any ID-related
* information, and doesn't include the Tx power since that is
* controlled by characteristics 4 (Radio Tx Power) and
* 5 (Advertised Tx Power).
*/
slot->ad[2].data_len = MIN(slot->ad[2].data_len,
len + EDS_URL_WRITE_OFFSET);
memcpy(&slot->ad[2].data + EDS_URL_WRITE_OFFSET, buf,
slot->ad[2].data_len - EDS_URL_WRITE_OFFSET);
/* Restart slot */
if (eds_slot_restart(slot, type) < 0) {
return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY);
}
return len;
case EDS_TYPE_UID:
case EDS_TYPE_TLM:
case EDS_TYPE_EID:
default:
/* TODO: Add support for other types. */
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
}
static ssize_t write_reset(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf, uint16_t len, uint16_t offset,
uint8_t flags)
{
/* TODO: Power cycle or reload for storage the values */
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
static ssize_t read_connectable(struct bt_conn *conn,
const struct bt_gatt_attr *attr, void *buf,
uint16_t len, uint16_t offset)
{
uint8_t connectable = 0x01;
/* Returning a non-zero value indicates that the beacon is capable
* of becoming non-connectable
*/
return bt_gatt_attr_read(conn, attr, buf, len, offset,
&connectable, sizeof(connectable));
}
static ssize_t write_connectable(struct bt_conn *conn,
const struct bt_gatt_attr *attr,
const void *buf, uint16_t len, uint16_t offset,
uint8_t flags)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
if (slot->state == EDS_LOCKED) {
return BT_GATT_ERR(BT_ATT_ERR_WRITE_NOT_PERMITTED);
}
if (offset) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET);
}
if (len > sizeof(slot->connectable)) {
return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
}
/* If any non-zero value is written, the beacon shall remain in its
* connectable state until any other value is written.
*/
memcpy(&slot->connectable, buf, len);
return len;
}
/* Eddystone Configuration Service Declaration */
BT_GATT_SERVICE_DEFINE(eds_svc,
BT_GATT_PRIMARY_SERVICE(&eds_uuid),
/* Capabilities: Readable only when unlocked. Never writable. */
BT_GATT_CHARACTERISTIC(&eds_caps_uuid.uuid, BT_GATT_CHRC_READ,
BT_GATT_PERM_READ, read_caps, NULL, &eds_caps),
/* Active slot: Must be unlocked for both read and write. */
BT_GATT_CHARACTERISTIC(&eds_slot_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_slot, write_slot, NULL),
/* Advertising Interval: Must be unlocked for both read and write. */
BT_GATT_CHARACTERISTIC(&eds_intv_uuid.uuid, BT_GATT_CHRC_READ,
BT_GATT_PERM_READ, read_interval, NULL, NULL),
/* Radio TX Power: Must be unlocked for both read and write. */
BT_GATT_CHARACTERISTIC(&eds_tx_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_tx_power, write_tx_power, NULL),
/* Advertised TX Power: Must be unlocked for both read and write. */
BT_GATT_CHARACTERISTIC(&eds_adv_tx_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_adv_tx_power, write_adv_tx_power, NULL),
/* Lock State:
* Readable in locked or unlocked state.
* Writeable only in unlocked state.
*/
BT_GATT_CHARACTERISTIC(&eds_lock_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_lock, write_lock, NULL),
/* Unlock:
* Readable only in locked state.
* Writeable only in locked state.
*/
BT_GATT_CHARACTERISTIC(&eds_unlock_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_unlock, write_unlock, NULL),
/* Public ECDH Key: Readable only in unlocked state. Never writable. */
BT_GATT_CHARACTERISTIC(&eds_ecdh_uuid.uuid, BT_GATT_CHRC_READ,
BT_GATT_PERM_READ, read_ecdh, NULL, &eds_ecdh),
/* EID Identity Key:Readable only in unlocked state. Never writable. */
BT_GATT_CHARACTERISTIC(&eds_eid_uuid.uuid, BT_GATT_CHRC_READ,
BT_GATT_PERM_READ, read_eid, NULL, eds_eid),
/* ADV Slot Data: Must be unlocked for both read and write. */
BT_GATT_CHARACTERISTIC(&eds_data_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_adv_data, write_adv_data, NULL),
/* ADV Factory Reset: Must be unlocked for write. */
BT_GATT_CHARACTERISTIC(&eds_reset_uuid.uuid, BT_GATT_CHRC_WRITE,
BT_GATT_PERM_WRITE, NULL, write_reset, NULL),
/* ADV Remain Connectable: Must be unlocked for write. */
BT_GATT_CHARACTERISTIC(&eds_connectable_uuid.uuid,
BT_GATT_CHRC_READ | BT_GATT_CHRC_WRITE,
BT_GATT_PERM_READ | BT_GATT_PERM_WRITE,
read_connectable, write_connectable, NULL),
);
static void bt_ready(int err)
{
char addr_s[BT_ADDR_LE_STR_LEN];
struct bt_le_oob oob;
if (err) {
printk("Bluetooth init failed (err %d)\n", err);
return;
}
printk("Bluetooth initialized\n");
/* Start advertising */
err = bt_le_adv_start(BT_LE_ADV_CONN_NAME, ad, ARRAY_SIZE(ad), NULL, 0);
if (err) {
printk("Advertising failed to start (err %d)\n", err);
return;
}
/* Restore connectable if slot */
bt_le_oob_get_local(BT_ID_DEFAULT, &oob);
bt_addr_le_to_str(&oob.addr, addr_s, sizeof(addr_s));
printk("Initial advertising as %s\n", addr_s);
k_delayed_work_submit(&idle_work, EDS_IDLE_TIMEOUT);
printk("Configuration mode: waiting connections...\n");
}
static void idle_timeout(struct k_work *work)
{
if (eds_slots[eds_active_slot].type == EDS_TYPE_NONE) {
printk("Switching to Beacon mode %u.\n", eds_active_slot);
eds_slot_restart(&eds_slots[eds_active_slot], EDS_TYPE_URL);
}
}
static void connected(struct bt_conn *conn, uint8_t err)
{
if (err) {
printk("Connection failed (err 0x%02x)\n", err);
} else {
printk("Connected\n");
k_delayed_work_cancel(&idle_work);
}
}
static void disconnected(struct bt_conn *conn, uint8_t reason)
{
struct eds_slot *slot = &eds_slots[eds_active_slot];
printk("Disconnected (reason 0x%02x)\n", reason);
if (!slot->connectable) {
k_delayed_work_submit(&idle_work, K_NO_WAIT);
}
}
static struct bt_conn_cb conn_callbacks = {
.connected = connected,
.disconnected = disconnected,
};
void main(void)
{
int err;
bt_conn_cb_register(&conn_callbacks);
k_delayed_work_init(&idle_work, idle_timeout);
/* Initialize the Bluetooth Subsystem */
err = bt_enable(bt_ready);
if (err) {
printk("Bluetooth init failed (err %d)\n", err);
}
}
| apache-2.0 |
gerritjvv/cryptoplayground | kerberos/kdc/src/krb5-1.16/src/tests/gssapi/t_err.c | 2 | 4924 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* tests/gssapi/t_err.c - Test accept_sec_context error generation */
/*
* Copyright (C) 2013 by the Massachusetts Institute of Technology.
* 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.
*/
/*
* This test program verifies that the krb5 gss_accept_sec_context can produce
* error tokens and that gss_init_sec_context can interpret them.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "common.h"
static void
check_replay_error(const char *msg, OM_uint32 major, OM_uint32 minor)
{
OM_uint32 tmpmin, msg_ctx = 0;
const char *replay = "Request is a replay";
gss_buffer_desc m;
if (major != GSS_S_FAILURE) {
fprintf(stderr, "%s: expected major code GSS_S_FAILURE\n", msg);
check_gsserr(msg, major, minor);
exit(1);
}
(void)gss_display_status(&tmpmin, minor, GSS_C_MECH_CODE, GSS_C_NULL_OID,
&msg_ctx, &m);
if (m.length != strlen(replay) || memcmp(m.value, replay, m.length) != 0) {
fprintf(stderr, "%s: expected replay error; got %.*s\n", msg,
(int)m.length, (char *)m.value);
exit(1);
}
(void)gss_release_buffer(&tmpmin, &m);
}
int
main(int argc, char *argv[])
{
OM_uint32 minor, major, flags;
gss_OID mech = &mech_krb5;
gss_name_t tname;
gss_buffer_desc itok, atok;
gss_ctx_id_t ictx = GSS_C_NO_CONTEXT, actx = GSS_C_NO_CONTEXT;
if (argc != 2) {
fprintf(stderr, "Usage: %s targetname\n", argv[0]);
return 1;
}
tname = import_name(argv[1]);
/* Get the initial context token. */
flags = GSS_C_REPLAY_FLAG | GSS_C_SEQUENCE_FLAG | GSS_C_MUTUAL_FLAG;
major = gss_init_sec_context(&minor, GSS_C_NO_CREDENTIAL, &ictx, tname,
mech, flags, GSS_C_INDEFINITE,
GSS_C_NO_CHANNEL_BINDINGS, GSS_C_NO_BUFFER,
NULL, &itok, NULL, NULL);
check_gsserr("gss_init_sec_context(1)", major, minor);
assert(major == GSS_S_CONTINUE_NEEDED);
/* Process this token into an acceptor context, then discard it. */
major = gss_accept_sec_context(&minor, &actx, GSS_C_NO_CREDENTIAL, &itok,
GSS_C_NO_CHANNEL_BINDINGS, NULL,
NULL, &atok, NULL, NULL, NULL);
check_gsserr("gss_accept_sec_context(1)", major, minor);
(void)gss_release_buffer(&minor, &atok);
(void)gss_delete_sec_context(&minor, &actx, NULL);
/* Process the same token again, producing a replay error. */
major = gss_accept_sec_context(&minor, &actx, GSS_C_NO_CREDENTIAL, &itok,
GSS_C_NO_CHANNEL_BINDINGS, NULL,
NULL, &atok, NULL, NULL, NULL);
check_replay_error("gss_accept_sec_context(2)", major, minor);
assert(atok.length != 0);
/* Send the error token back the initiator. */
(void)gss_release_buffer(&minor, &itok);
major = gss_init_sec_context(&minor, GSS_C_NO_CREDENTIAL, &ictx, tname,
mech, flags, GSS_C_INDEFINITE,
GSS_C_NO_CHANNEL_BINDINGS, &atok,
NULL, &itok, NULL, NULL);
check_replay_error("gss_init_sec_context(2)", major, minor);
(void)gss_release_name(&minor, &tname);
(void)gss_release_buffer(&minor, &itok);
(void)gss_release_buffer(&minor, &atok);
(void)gss_delete_sec_context(&minor, &ictx, NULL);
(void)gss_delete_sec_context(&minor, &actx, NULL);
return 0;
}
| apache-2.0 |
sergecodd/FireFox-OS | B2G/gecko/layout/xul/base/src/nsXULTooltipListener.cpp | 2 | 21708 | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsXULTooltipListener.h"
#include "nsIDOMMouseEvent.h"
#include "nsIDOMEventTarget.h"
#include "nsIDOMXULDocument.h"
#include "nsIDOMXULElement.h"
#include "nsIDocument.h"
#include "nsGkAtoms.h"
#include "nsIPopupBoxObject.h"
#include "nsMenuPopupFrame.h"
#include "nsIServiceManager.h"
#include "nsIDragService.h"
#include "nsIDragSession.h"
#ifdef MOZ_XUL
#include "nsITreeView.h"
#endif
#include "nsGUIEvent.h"
#include "nsIScriptContext.h"
#include "nsPIDOMWindow.h"
#ifdef MOZ_XUL
#include "nsXULPopupManager.h"
#endif
#include "nsIRootBox.h"
#include "nsEventDispatcher.h"
#include "mozilla/Preferences.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/dom/Element.h"
using namespace mozilla;
nsXULTooltipListener* nsXULTooltipListener::mInstance = nullptr;
//////////////////////////////////////////////////////////////////////////
//// nsISupports
nsXULTooltipListener::nsXULTooltipListener()
: mMouseScreenX(0)
, mMouseScreenY(0)
, mTooltipShownOnce(false)
#ifdef MOZ_XUL
, mIsSourceTree(false)
, mNeedTitletip(false)
, mLastTreeRow(-1)
#endif
{
if (sTooltipListenerCount++ == 0) {
// register the callback so we get notified of updates
Preferences::RegisterCallback(ToolbarTipsPrefChanged,
"browser.chrome.toolbar_tips");
// Call the pref callback to initialize our state.
ToolbarTipsPrefChanged("browser.chrome.toolbar_tips", nullptr);
}
}
nsXULTooltipListener::~nsXULTooltipListener()
{
if (nsXULTooltipListener::mInstance == this) {
ClearTooltipCache();
}
HideTooltip();
if (--sTooltipListenerCount == 0) {
// Unregister our pref observer
Preferences::UnregisterCallback(ToolbarTipsPrefChanged,
"browser.chrome.toolbar_tips");
}
}
NS_IMPL_ISUPPORTS1(nsXULTooltipListener, nsIDOMEventListener)
void
nsXULTooltipListener::MouseOut(nsIDOMEvent* aEvent)
{
// reset flag so that tooltip will display on the next MouseMove
mTooltipShownOnce = false;
// if the timer is running and no tooltip is shown, we
// have to cancel the timer here so that it doesn't
// show the tooltip if we move the mouse out of the window
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if (mTooltipTimer && !currentTooltip) {
mTooltipTimer->Cancel();
mTooltipTimer = nullptr;
return;
}
#ifdef DEBUG_crap
if (mNeedTitletip)
return;
#endif
#ifdef MOZ_XUL
// check to see if the mouse left the targetNode, and if so,
// hide the tooltip
if (currentTooltip) {
// which node did the mouse leave?
nsCOMPtr<nsIDOMEventTarget> eventTarget;
aEvent->GetTarget(getter_AddRefs(eventTarget));
nsCOMPtr<nsIDOMNode> targetNode(do_QueryInterface(eventTarget));
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm) {
nsCOMPtr<nsIDOMNode> tooltipNode =
pm->GetLastTriggerTooltipNode(currentTooltip->GetCurrentDoc());
if (tooltipNode == targetNode) {
// if the target node is the current tooltip target node, the mouse
// left the node the tooltip appeared on, so close the tooltip.
HideTooltip();
// reset special tree tracking
if (mIsSourceTree) {
mLastTreeRow = -1;
mLastTreeCol = nullptr;
}
}
}
}
#endif
}
void
nsXULTooltipListener::MouseMove(nsIDOMEvent* aEvent)
{
if (!sShowTooltips)
return;
// stash the coordinates of the event so that we can still get back to it from within the
// timer callback. On win32, we'll get a MouseMove event even when a popup goes away --
// even when the mouse doesn't change position! To get around this, we make sure the
// mouse has really moved before proceeding.
nsCOMPtr<nsIDOMMouseEvent> mouseEvent(do_QueryInterface(aEvent));
if (!mouseEvent)
return;
int32_t newMouseX, newMouseY;
mouseEvent->GetScreenX(&newMouseX);
mouseEvent->GetScreenY(&newMouseY);
// filter out false win32 MouseMove event
if (mMouseScreenX == newMouseX && mMouseScreenY == newMouseY)
return;
// filter out minor movements due to crappy optical mice and shaky hands
// to prevent tooltips from hiding prematurely.
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if ((currentTooltip) &&
(abs(mMouseScreenX - newMouseX) <= kTooltipMouseMoveTolerance) &&
(abs(mMouseScreenY - newMouseY) <= kTooltipMouseMoveTolerance))
return;
mMouseScreenX = newMouseX;
mMouseScreenY = newMouseY;
nsCOMPtr<nsIDOMEventTarget> currentTarget;
aEvent->GetCurrentTarget(getter_AddRefs(currentTarget));
nsCOMPtr<nsIContent> sourceContent = do_QueryInterface(currentTarget);
mSourceNode = do_GetWeakReference(sourceContent);
#ifdef MOZ_XUL
mIsSourceTree = sourceContent->Tag() == nsGkAtoms::treechildren;
if (mIsSourceTree)
CheckTreeBodyMove(mouseEvent);
#endif
// as the mouse moves, we want to make sure we reset the timer to show it,
// so that the delay is from when the mouse stops moving, not when it enters
// the node.
KillTooltipTimer();
// If the mouse moves while the tooltip is up, hide it. If nothing is
// showing and the tooltip hasn't been displayed since the mouse entered
// the node, then start the timer to show the tooltip.
if (!currentTooltip && !mTooltipShownOnce) {
nsCOMPtr<nsIDOMEventTarget> eventTarget;
aEvent->GetTarget(getter_AddRefs(eventTarget));
// don't show tooltips attached to elements outside of a menu popup
// when hovering over an element inside it. The popupsinherittooltip
// attribute may be used to disable this behaviour, which is useful for
// large menu hierarchies such as bookmarks.
if (!sourceContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::popupsinherittooltip,
nsGkAtoms::_true, eCaseMatters)) {
nsCOMPtr<nsIContent> targetContent = do_QueryInterface(eventTarget);
while (targetContent && targetContent != sourceContent) {
nsIAtom* tag = targetContent->Tag();
if (targetContent->GetNameSpaceID() == kNameSpaceID_XUL &&
(tag == nsGkAtoms::menupopup ||
tag == nsGkAtoms::panel ||
tag == nsGkAtoms::tooltip)) {
mSourceNode = nullptr;
return;
}
targetContent = targetContent->GetParent();
}
}
mTooltipTimer = do_CreateInstance("@mozilla.org/timer;1");
if (mTooltipTimer) {
mTargetNode = do_GetWeakReference(eventTarget);
if (mTargetNode) {
nsresult rv =
mTooltipTimer->InitWithFuncCallback(sTooltipCallback, this,
LookAndFeel::GetInt(LookAndFeel::eIntID_TooltipDelay, 500),
nsITimer::TYPE_ONE_SHOT);
if (NS_FAILED(rv)) {
mTargetNode = nullptr;
mSourceNode = nullptr;
}
}
}
return;
}
#ifdef MOZ_XUL
if (mIsSourceTree)
return;
#endif
HideTooltip();
// set a flag so that the tooltip is only displayed once until the mouse
// leaves the node
mTooltipShownOnce = true;
}
NS_IMETHODIMP
nsXULTooltipListener::HandleEvent(nsIDOMEvent* aEvent)
{
nsAutoString type;
aEvent->GetType(type);
if (type.EqualsLiteral("DOMMouseScroll") ||
type.EqualsLiteral("keydown") ||
type.EqualsLiteral("mousedown") ||
type.EqualsLiteral("mouseup") ||
type.EqualsLiteral("dragstart")) {
HideTooltip();
return NS_OK;
}
if (type.EqualsLiteral("popuphiding")) {
DestroyTooltip();
return NS_OK;
}
// Note that mousemove, mouseover and mouseout might be
// fired even during dragging due to widget's bug.
nsCOMPtr<nsIDragService> dragService =
do_GetService("@mozilla.org/widget/dragservice;1");
NS_ENSURE_TRUE(dragService, NS_OK);
nsCOMPtr<nsIDragSession> dragSession;
dragService->GetCurrentSession(getter_AddRefs(dragSession));
if (dragSession) {
return NS_OK;
}
// Not dragging.
if (type.EqualsLiteral("mousemove")) {
MouseMove(aEvent);
return NS_OK;
}
if (type.EqualsLiteral("mouseout")) {
MouseOut(aEvent);
return NS_OK;
}
return NS_OK;
}
//////////////////////////////////////////////////////////////////////////
//// nsXULTooltipListener
// static
int
nsXULTooltipListener::ToolbarTipsPrefChanged(const char *aPref,
void *aClosure)
{
sShowTooltips =
Preferences::GetBool("browser.chrome.toolbar_tips", sShowTooltips);
return 0;
}
//////////////////////////////////////////////////////////////////////////
//// nsXULTooltipListener
bool nsXULTooltipListener::sShowTooltips = false;
uint32_t nsXULTooltipListener::sTooltipListenerCount = 0;
nsresult
nsXULTooltipListener::AddTooltipSupport(nsIContent* aNode)
{
if (!aNode)
return NS_ERROR_NULL_POINTER;
aNode->AddSystemEventListener(NS_LITERAL_STRING("mouseout"), this,
false, false);
aNode->AddSystemEventListener(NS_LITERAL_STRING("mousemove"), this,
false, false);
aNode->AddSystemEventListener(NS_LITERAL_STRING("dragstart"), this,
true, false);
return NS_OK;
}
nsresult
nsXULTooltipListener::RemoveTooltipSupport(nsIContent* aNode)
{
if (!aNode)
return NS_ERROR_NULL_POINTER;
aNode->RemoveSystemEventListener(NS_LITERAL_STRING("mouseout"), this, false);
aNode->RemoveSystemEventListener(NS_LITERAL_STRING("mousemove"), this, false);
aNode->RemoveSystemEventListener(NS_LITERAL_STRING("dragstart"), this, true);
return NS_OK;
}
#ifdef MOZ_XUL
void
nsXULTooltipListener::CheckTreeBodyMove(nsIDOMMouseEvent* aMouseEvent)
{
nsCOMPtr<nsIContent> sourceNode = do_QueryReferent(mSourceNode);
if (!sourceNode)
return;
// get the boxObject of the documentElement of the document the tree is in
nsCOMPtr<nsIBoxObject> bx;
nsIDocument* doc = sourceNode->GetDocument();
if (doc) {
nsCOMPtr<nsIDOMElement> docElement = do_QueryInterface(doc->GetRootElement());
if (docElement) {
doc->GetBoxObjectFor(docElement, getter_AddRefs(bx));
}
}
nsCOMPtr<nsITreeBoxObject> obx;
GetSourceTreeBoxObject(getter_AddRefs(obx));
if (bx && obx) {
int32_t x, y;
aMouseEvent->GetScreenX(&x);
aMouseEvent->GetScreenY(&y);
int32_t row;
nsCOMPtr<nsITreeColumn> col;
nsAutoCString obj;
// subtract off the documentElement's boxObject
int32_t boxX, boxY;
bx->GetScreenX(&boxX);
bx->GetScreenY(&boxY);
x -= boxX;
y -= boxY;
obx->GetCellAt(x, y, &row, getter_AddRefs(col), obj);
// determine if we are going to need a titletip
// XXX check the disabletitletips attribute on the tree content
mNeedTitletip = false;
if (row >= 0 && obj.EqualsLiteral("text")) {
obx->IsCellCropped(row, col, &mNeedTitletip);
}
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if (currentTooltip && (row != mLastTreeRow || col != mLastTreeCol)) {
HideTooltip();
}
mLastTreeRow = row;
mLastTreeCol = col;
}
}
#endif
nsresult
nsXULTooltipListener::ShowTooltip()
{
nsCOMPtr<nsIContent> sourceNode = do_QueryReferent(mSourceNode);
// get the tooltip content designated for the target node
nsCOMPtr<nsIContent> tooltipNode;
GetTooltipFor(sourceNode, getter_AddRefs(tooltipNode));
if (!tooltipNode || sourceNode == tooltipNode)
return NS_ERROR_FAILURE; // the target node doesn't need a tooltip
// set the node in the document that triggered the tooltip and show it
nsCOMPtr<nsIDOMXULDocument> xulDoc(do_QueryInterface(tooltipNode->GetDocument()));
if (xulDoc) {
// Make sure the target node is still attached to some document.
// It might have been deleted.
if (sourceNode->GetDocument()) {
#ifdef MOZ_XUL
if (!mIsSourceTree) {
mLastTreeRow = -1;
mLastTreeCol = nullptr;
}
#endif
mCurrentTooltip = do_GetWeakReference(tooltipNode);
LaunchTooltip();
mTargetNode = nullptr;
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if (!currentTooltip)
return NS_OK;
// listen for popuphidden on the tooltip node, so that we can
// be sure DestroyPopup is called even if someone else closes the tooltip
currentTooltip->AddSystemEventListener(NS_LITERAL_STRING("popuphiding"),
this, false, false);
// listen for mousedown, mouseup, keydown, and DOMMouseScroll events at document level
nsIDocument* doc = sourceNode->GetDocument();
if (doc) {
// Probably, we should listen to untrusted events for hiding tooltips
// on content since tooltips might disturb something of web
// applications. If we don't specify the aWantsUntrusted of
// AddSystemEventListener(), the event target sets it to TRUE if the
// target is in content.
doc->AddSystemEventListener(NS_LITERAL_STRING("DOMMouseScroll"),
this, true);
doc->AddSystemEventListener(NS_LITERAL_STRING("mousedown"),
this, true);
doc->AddSystemEventListener(NS_LITERAL_STRING("mouseup"),
this, true);
doc->AddSystemEventListener(NS_LITERAL_STRING("keydown"),
this, true);
}
mSourceNode = nullptr;
}
}
return NS_OK;
}
#ifdef MOZ_XUL
// XXX: "This stuff inside DEBUG_crap could be used to make tree tooltips work
// in the future."
#ifdef DEBUG_crap
static void
GetTreeCellCoords(nsITreeBoxObject* aTreeBox, nsIContent* aSourceNode,
int32_t aRow, nsITreeColumn* aCol, int32_t* aX, int32_t* aY)
{
int32_t junk;
aTreeBox->GetCoordsForCellItem(aRow, aCol, EmptyCString(), aX, aY, &junk, &junk);
nsCOMPtr<nsIDOMXULElement> xulEl(do_QueryInterface(aSourceNode));
nsCOMPtr<nsIBoxObject> bx;
xulEl->GetBoxObject(getter_AddRefs(bx));
int32_t myX, myY;
bx->GetX(&myX);
bx->GetY(&myY);
*aX += myX;
*aY += myY;
}
#endif
static void
SetTitletipLabel(nsITreeBoxObject* aTreeBox, nsIContent* aTooltip,
int32_t aRow, nsITreeColumn* aCol)
{
nsCOMPtr<nsITreeView> view;
aTreeBox->GetView(getter_AddRefs(view));
if (view) {
nsAutoString label;
#ifdef DEBUG
nsresult rv =
#endif
view->GetCellText(aRow, aCol, label);
NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Couldn't get the cell text!");
aTooltip->SetAttr(kNameSpaceID_None, nsGkAtoms::label, label, true);
}
}
#endif
void
nsXULTooltipListener::LaunchTooltip()
{
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if (!currentTooltip)
return;
#ifdef MOZ_XUL
if (mIsSourceTree && mNeedTitletip) {
nsCOMPtr<nsITreeBoxObject> obx;
GetSourceTreeBoxObject(getter_AddRefs(obx));
SetTitletipLabel(obx, currentTooltip, mLastTreeRow, mLastTreeCol);
if (!(currentTooltip = do_QueryReferent(mCurrentTooltip))) {
// Because of mutation events, currentTooltip can be null.
return;
}
currentTooltip->SetAttr(kNameSpaceID_None, nsGkAtoms::titletip, NS_LITERAL_STRING("true"), true);
} else {
currentTooltip->UnsetAttr(kNameSpaceID_None, nsGkAtoms::titletip, true);
}
if (!(currentTooltip = do_QueryReferent(mCurrentTooltip))) {
// Because of mutation events, currentTooltip can be null.
return;
}
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm) {
nsCOMPtr<nsIContent> target = do_QueryReferent(mTargetNode);
pm->ShowTooltipAtScreen(currentTooltip, target, mMouseScreenX, mMouseScreenY);
// Clear the current tooltip if the popup was not opened successfully.
if (!pm->IsPopupOpen(currentTooltip))
mCurrentTooltip = nullptr;
}
#endif
}
nsresult
nsXULTooltipListener::HideTooltip()
{
#ifdef MOZ_XUL
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if (currentTooltip) {
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm)
pm->HidePopup(currentTooltip, false, false, false);
}
#endif
DestroyTooltip();
return NS_OK;
}
static void
GetImmediateChild(nsIContent* aContent, nsIAtom *aTag, nsIContent** aResult)
{
*aResult = nullptr;
uint32_t childCount = aContent->GetChildCount();
for (uint32_t i = 0; i < childCount; i++) {
nsIContent *child = aContent->GetChildAt(i);
if (child->Tag() == aTag) {
*aResult = child;
NS_ADDREF(*aResult);
return;
}
}
return;
}
nsresult
nsXULTooltipListener::FindTooltip(nsIContent* aTarget, nsIContent** aTooltip)
{
if (!aTarget)
return NS_ERROR_NULL_POINTER;
// before we go on, make sure that target node still has a window
nsIDocument *document = aTarget->GetDocument();
if (!document) {
NS_WARNING("Unable to retrieve the tooltip node document.");
return NS_ERROR_FAILURE;
}
nsPIDOMWindow *window = document->GetWindow();
if (!window) {
return NS_OK;
}
bool closed;
window->GetClosed(&closed);
if (closed) {
return NS_OK;
}
nsAutoString tooltipText;
aTarget->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, tooltipText);
if (!tooltipText.IsEmpty()) {
// specifying tooltiptext means we will always use the default tooltip
nsIRootBox* rootBox = nsIRootBox::GetRootBox(document->GetShell());
NS_ENSURE_STATE(rootBox);
*aTooltip = rootBox->GetDefaultTooltip();
if (*aTooltip) {
NS_ADDREF(*aTooltip);
(*aTooltip)->SetAttr(kNameSpaceID_None, nsGkAtoms::label, tooltipText, true);
}
return NS_OK;
}
nsAutoString tooltipId;
aTarget->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltip, tooltipId);
// if tooltip == _child, look for first <tooltip> child
if (tooltipId.EqualsLiteral("_child")) {
GetImmediateChild(aTarget, nsGkAtoms::tooltip, aTooltip);
return NS_OK;
}
if (!tooltipId.IsEmpty()) {
// tooltip must be an id, use getElementById to find it
nsCOMPtr<nsIContent> tooltipEl = document->GetElementById(tooltipId);
if (tooltipEl) {
#ifdef MOZ_XUL
mNeedTitletip = false;
#endif
tooltipEl.forget(aTooltip);
return NS_OK;
}
}
#ifdef MOZ_XUL
// titletips should just use the default tooltip
if (mIsSourceTree && mNeedTitletip) {
nsIRootBox* rootBox = nsIRootBox::GetRootBox(document->GetShell());
NS_ENSURE_STATE(rootBox);
NS_IF_ADDREF(*aTooltip = rootBox->GetDefaultTooltip());
}
#endif
return NS_OK;
}
nsresult
nsXULTooltipListener::GetTooltipFor(nsIContent* aTarget, nsIContent** aTooltip)
{
*aTooltip = nullptr;
nsCOMPtr<nsIContent> tooltip;
nsresult rv = FindTooltip(aTarget, getter_AddRefs(tooltip));
if (NS_FAILED(rv) || !tooltip) {
return rv;
}
#ifdef MOZ_XUL
// Submenus can't be used as tooltips, see bug 288763.
nsIContent* parent = tooltip->GetParent();
if (parent) {
nsMenuFrame* menu = do_QueryFrame(parent->GetPrimaryFrame());
if (menu) {
NS_WARNING("Menu cannot be used as a tooltip");
return NS_ERROR_FAILURE;
}
}
#endif
tooltip.swap(*aTooltip);
return rv;
}
nsresult
nsXULTooltipListener::DestroyTooltip()
{
nsCOMPtr<nsIDOMEventListener> kungFuDeathGrip(this);
nsCOMPtr<nsIContent> currentTooltip = do_QueryReferent(mCurrentTooltip);
if (currentTooltip) {
// clear out the tooltip node on the document
nsCOMPtr<nsIDocument> doc = currentTooltip->GetDocument();
if (doc) {
// remove the mousedown and keydown listener from document
doc->RemoveSystemEventListener(NS_LITERAL_STRING("DOMMouseScroll"), this,
true);
doc->RemoveSystemEventListener(NS_LITERAL_STRING("mousedown"), this,
true);
doc->RemoveSystemEventListener(NS_LITERAL_STRING("mouseup"), this, true);
doc->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"), this, true);
}
// remove the popuphidden listener from tooltip
nsCOMPtr<nsIDOMEventTarget> evtTarget(do_QueryInterface(currentTooltip));
// release tooltip before removing listener to prevent our destructor from
// being called recursively (bug 120863)
mCurrentTooltip = nullptr;
evtTarget->RemoveEventListener(NS_LITERAL_STRING("popuphiding"), this, false);
}
// kill any ongoing timers
KillTooltipTimer();
mSourceNode = nullptr;
#ifdef MOZ_XUL
mLastTreeCol = nullptr;
#endif
return NS_OK;
}
void
nsXULTooltipListener::KillTooltipTimer()
{
if (mTooltipTimer) {
mTooltipTimer->Cancel();
mTooltipTimer = nullptr;
mTargetNode = nullptr;
}
}
void
nsXULTooltipListener::sTooltipCallback(nsITimer *aTimer, void *aListener)
{
nsRefPtr<nsXULTooltipListener> instance = mInstance;
if (instance)
instance->ShowTooltip();
}
#ifdef MOZ_XUL
nsresult
nsXULTooltipListener::GetSourceTreeBoxObject(nsITreeBoxObject** aBoxObject)
{
*aBoxObject = nullptr;
nsCOMPtr<nsIContent> sourceNode = do_QueryReferent(mSourceNode);
if (mIsSourceTree && sourceNode) {
nsCOMPtr<nsIDOMXULElement> xulEl(do_QueryInterface(sourceNode->GetParent()));
if (xulEl) {
nsCOMPtr<nsIBoxObject> bx;
xulEl->GetBoxObject(getter_AddRefs(bx));
nsCOMPtr<nsITreeBoxObject> obx(do_QueryInterface(bx));
if (obx) {
*aBoxObject = obx;
NS_ADDREF(*aBoxObject);
return NS_OK;
}
}
}
return NS_ERROR_FAILURE;
}
#endif
| apache-2.0 |
wickman/mesos | src/common/resources.cpp | 2 | 6299 | /**
* 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 <iostream>
#include <vector>
#include <glog/logging.h>
#include <stout/foreach.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
#include "common/resources.hpp"
#include "common/values.hpp"
using std::ostream;
using std::string;
using std::vector;
namespace mesos {
bool operator == (const Resource& left, const Resource& right)
{
if (left.name() == right.name() && left.type() == right.type()) {
if (left.type() == Value::SCALAR) {
return left.scalar() == right.scalar();
} else if (left.type() == Value::RANGES) {
return left.ranges() == right.ranges();
} else if (left.type() == Value::SET) {
return left.set() == right.set();
}
}
return false;
}
bool operator <= (const Resource& left, const Resource& right)
{
if (left.name() == right.name() && left.type() == right.type()) {
if (left.type() == Value::SCALAR) {
return left.scalar() <= right.scalar();
} else if (left.type() == Value::RANGES) {
return left.ranges() <= right.ranges();
} else if (left.type() == Value::SET) {
return left.set() <= right.set();
}
}
return false;
}
Resource operator + (const Resource& left, const Resource& right)
{
Resource result = left;
if (left.name() == right.name() && left.type() == right.type()) {
if (left.type() == Value::SCALAR) {
result.mutable_scalar()->MergeFrom(left.scalar() + right.scalar());
} else if (left.type() == Value::RANGES) {
result.mutable_ranges()->Clear();
result.mutable_ranges()->MergeFrom(left.ranges() + right.ranges());
} else if (left.type() == Value::SET) {
result.mutable_set()->Clear();
result.mutable_set()->MergeFrom(left.set() + right.set());
}
}
return result;
}
Resource operator - (const Resource& left, const Resource& right)
{
Resource result = left;
if (left.name() == right.name() && left.type() == right.type()) {
if (left.type() == Value::SCALAR) {
result.mutable_scalar()->MergeFrom(left.scalar() - right.scalar());
} else if (left.type() == Value::RANGES) {
result.mutable_ranges()->Clear();
result.mutable_ranges()->MergeFrom(left.ranges() - right.ranges());
} else if (left.type() == Value::SET) {
result.mutable_set()->Clear();
result.mutable_set()->MergeFrom(left.set() - right.set());
}
}
return result;
}
Resource& operator += (Resource& left, const Resource& right)
{
if (left.name() == right.name() && left.type() == right.type()) {
if (left.type() == Value::SCALAR) {
left.mutable_scalar()->MergeFrom(left.scalar() + right.scalar());
} else if (left.type() == Value::RANGES) {
left.mutable_ranges()->Clear();
left.mutable_ranges()->MergeFrom(left.ranges() + right.ranges());
} else if (left.type() == Value::SET) {
left.mutable_set()->Clear();
left.mutable_set()->MergeFrom(left.set() + right.set());
}
}
return left;
}
Resource& operator -= (Resource& left, const Resource& right)
{
if (left.name() == right.name() && left.type() == right.type()) {
if (left.type() == Value::SCALAR) {
left.mutable_scalar()->MergeFrom(left.scalar() - right.scalar());
} else if (left.type() == Value::RANGES) {
left.mutable_ranges()->Clear();
left.mutable_ranges()->MergeFrom(left.ranges() - right.ranges());
} else if (left.type() == Value::SET) {
left.mutable_set()->Clear();
left.mutable_set()->MergeFrom(left.set() - right.set());
}
}
return left;
}
ostream& operator << (ostream& stream, const Resource& resource)
{
stream << resource.name() << "=";
switch (resource.type()) {
case Value::SCALAR: stream << resource.scalar(); break;
case Value::RANGES: stream << resource.ranges(); break;
case Value::SET: stream << resource.set(); break;
default:
LOG(FATAL) << "Unexpected Value type: " << resource.type();
break;
}
return stream;
}
namespace internal {
Resource Resources::parse(const std::string& name, const std::string& text)
{
Resource resource;
Try<Value> result = values::parse(text);
if (result.isError()) {
LOG(FATAL) << "Failed to parse resource " << name
<< " text " << text
<< " error " << result.error();
} else{
Value value = result.get();
resource.set_name(name);
if (value.type() == Value::RANGES) {
resource.set_type(Value::RANGES);
resource.mutable_ranges()->MergeFrom(value.ranges());
} else if (value.type() == Value::SET) {
resource.set_type(Value::SET);
resource.mutable_set()->MergeFrom(value.set());
} else if (value.type() == Value::SCALAR) {
resource.set_type(Value::SCALAR);
resource.mutable_scalar()->MergeFrom(value.scalar());
} else {
LOG(FATAL) << "Bad type for resource " << name
<< " text " << text
<< " type " << value.type();
}
}
return resource;
}
Resources Resources::parse(const string& s)
{
// Tokenize and parse the value of "resources".
Resources resources;
vector<string> tokens = strings::tokenize(s, ";\n");
for (size_t i = 0; i < tokens.size(); i++) {
const vector<string>& pairs = strings::tokenize(tokens[i], ":");
if (pairs.size() != 2) {
LOG(FATAL) << "Bad value for resources, missing ':' within " << pairs[0];
}
resources += parse(pairs[0], pairs[1]);
}
return resources;
}
} // namespace internal {
} // namespace mesos {
| apache-2.0 |
allevato/swift | lib/AST/TypeCheckRequests.cpp | 3 | 50781 | //===--- TypeCheckRequests.cpp - Type Checking Requests ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/TypeRepr.h"
#include "swift/AST/Types.h"
#include "swift/Subsystems.h"
using namespace swift;
namespace swift {
// Implement the type checker type zone (zone 10).
#define SWIFT_TYPEID_ZONE TypeChecker
#define SWIFT_TYPEID_HEADER "swift/AST/TypeCheckerTypeIDZone.def"
#include "swift/Basic/ImplementTypeIDZone.h"
#undef SWIFT_TYPEID_ZONE
#undef SWIFT_TYPEID_HEADER
}
void swift::simple_display(
llvm::raw_ostream &out,
const llvm::PointerUnion<const TypeDecl *, const ExtensionDecl *> &value) {
if (auto type = value.dyn_cast<const TypeDecl *>()) {
type->dumpRef(out);
return;
}
auto ext = value.get<const ExtensionDecl *>();
simple_display(out, ext);
}
void swift::simple_display(llvm::raw_ostream &out,
const TypeResolutionStage &value) {
switch (value) {
case TypeResolutionStage::Structural:
out << "structural";
break;
case TypeResolutionStage::Interface:
out << "interface";
break;
case TypeResolutionStage::Contextual:
out << "contextual";
break;
}
}
void swift::simple_display(llvm::raw_ostream &out, Type type) {
if (type)
type.print(out);
else
out << "null";
}
void swift::simple_display(llvm::raw_ostream &out, const TypeRepr *TyR) {
if (TyR)
TyR->print(out);
else
out << "null";
}
void swift::simple_display(llvm::raw_ostream &out, const TypeLoc source) {
out << "(";
simple_display(out, source.getType());
out << ", ";
simple_display(out, source.getTypeRepr());
out << ")";
}
//----------------------------------------------------------------------------//
// Inherited type computation.
//----------------------------------------------------------------------------//
SourceLoc InheritedTypeRequest::getNearestLoc() const {
const auto &storage = getStorage();
auto &typeLoc = getInheritedTypeLocAtIndex(std::get<0>(storage),
std::get<1>(storage));
return typeLoc.getLoc();
}
bool InheritedTypeRequest::isCached() const {
return std::get<2>(getStorage()) == TypeResolutionStage::Interface;
}
Optional<Type> InheritedTypeRequest::getCachedResult() const {
const auto &storage = getStorage();
auto &typeLoc = getInheritedTypeLocAtIndex(std::get<0>(storage),
std::get<1>(storage));
if (typeLoc.wasValidated())
return typeLoc.getType();
return None;
}
void InheritedTypeRequest::cacheResult(Type value) const {
const auto &storage = getStorage();
auto &typeLoc = getInheritedTypeLocAtIndex(std::get<0>(storage),
std::get<1>(storage));
const_cast<TypeLoc &>(typeLoc).setType(value);
}
//----------------------------------------------------------------------------//
// Superclass computation.
//----------------------------------------------------------------------------//
void SuperclassTypeRequest::diagnoseCycle(DiagnosticEngine &diags) const {
// FIXME: Improve this diagnostic.
auto nominalDecl = std::get<0>(getStorage());
diags.diagnose(nominalDecl, diag::circular_class_inheritance,
nominalDecl->getName());
}
bool SuperclassTypeRequest::isCached() const {
return std::get<1>(getStorage()) == TypeResolutionStage::Interface;
}
Optional<Type> SuperclassTypeRequest::getCachedResult() const {
auto nominalDecl = std::get<0>(getStorage());
if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
if (classDecl->LazySemanticInfo.SuperclassType.getInt())
return classDecl->LazySemanticInfo.SuperclassType.getPointer();
if (auto *protocolDecl = dyn_cast<ProtocolDecl>(nominalDecl))
if (protocolDecl->LazySemanticInfo.SuperclassType.getInt())
return protocolDecl->LazySemanticInfo.SuperclassType.getPointer();
return None;
}
void SuperclassTypeRequest::cacheResult(Type value) const {
auto nominalDecl = std::get<0>(getStorage());
if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
classDecl->LazySemanticInfo.SuperclassType.setPointerAndInt(value, true);
if (auto *protocolDecl = dyn_cast<ProtocolDecl>(nominalDecl))
protocolDecl->LazySemanticInfo.SuperclassType.setPointerAndInt(value, true);
}
evaluator::DependencySource SuperclassTypeRequest::readDependencySource(
const evaluator::DependencyRecorder &e) const {
const auto access = std::get<0>(getStorage())->getFormalAccess();
return {
e.getActiveDependencySourceOrNull(),
evaluator::getScopeForAccessLevel(access)
};
}
void SuperclassTypeRequest::writeDependencySink(
evaluator::DependencyCollector &tracker, Type value) const {
if (!value)
return;
// FIXME: This is compatible with the existing name tracking scheme, but
// ignoring this name when we fail to look up a class is bogus.
ClassDecl *Super = value->getClassOrBoundGenericClass();
if (!Super)
return;
tracker.addPotentialMember(Super);
}
//----------------------------------------------------------------------------//
// Enum raw type computation.
//----------------------------------------------------------------------------//
void EnumRawTypeRequest::diagnoseCycle(DiagnosticEngine &diags) const {
// FIXME: Improve this diagnostic.
auto enumDecl = std::get<0>(getStorage());
diags.diagnose(enumDecl, diag::circular_enum_inheritance, enumDecl->getName());
}
bool EnumRawTypeRequest::isCached() const {
return std::get<1>(getStorage()) == TypeResolutionStage::Interface;
}
Optional<Type> EnumRawTypeRequest::getCachedResult() const {
auto enumDecl = std::get<0>(getStorage());
if (enumDecl->LazySemanticInfo.hasRawType())
return enumDecl->LazySemanticInfo.RawTypeAndFlags.getPointer();
return None;
}
void EnumRawTypeRequest::cacheResult(Type value) const {
auto enumDecl = std::get<0>(getStorage());
enumDecl->LazySemanticInfo.cacheRawType(value);
}
//----------------------------------------------------------------------------//
// isObjC computation.
//----------------------------------------------------------------------------//
Optional<bool> IsObjCRequest::getCachedResult() const {
auto decl = std::get<0>(getStorage());
if (decl->LazySemanticInfo.isObjCComputed)
return decl->LazySemanticInfo.isObjC;
return None;
}
void IsObjCRequest::cacheResult(bool value) const {
auto decl = std::get<0>(getStorage());
decl->setIsObjC(value);
}
//----------------------------------------------------------------------------//
// requiresClass computation.
//----------------------------------------------------------------------------//
void ProtocolRequiresClassRequest::diagnoseCycle(DiagnosticEngine &diags) const {
auto decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::circular_protocol_def, decl->getName());
}
void ProtocolRequiresClassRequest::noteCycleStep(DiagnosticEngine &diags) const {
auto requirement = std::get<0>(getStorage());
diags.diagnose(requirement, diag::kind_declname_declared_here,
DescriptiveDeclKind::Protocol,
requirement->getName());
}
Optional<bool> ProtocolRequiresClassRequest::getCachedResult() const {
auto decl = std::get<0>(getStorage());
return decl->getCachedRequiresClass();
}
void ProtocolRequiresClassRequest::cacheResult(bool value) const {
auto decl = std::get<0>(getStorage());
decl->setCachedRequiresClass(value);
}
//----------------------------------------------------------------------------//
// existentialConformsToSelf computation.
//----------------------------------------------------------------------------//
void ExistentialConformsToSelfRequest::diagnoseCycle(DiagnosticEngine &diags) const {
auto decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::circular_protocol_def, decl->getName());
}
void ExistentialConformsToSelfRequest::noteCycleStep(DiagnosticEngine &diags) const {
auto requirement = std::get<0>(getStorage());
diags.diagnose(requirement, diag::kind_declname_declared_here,
DescriptiveDeclKind::Protocol, requirement->getName());
}
Optional<bool> ExistentialConformsToSelfRequest::getCachedResult() const {
auto decl = std::get<0>(getStorage());
return decl->getCachedExistentialConformsToSelf();
}
void ExistentialConformsToSelfRequest::cacheResult(bool value) const {
auto decl = std::get<0>(getStorage());
decl->setCachedExistentialConformsToSelf(value);
}
//----------------------------------------------------------------------------//
// existentialTypeSupported computation.
//----------------------------------------------------------------------------//
void ExistentialTypeSupportedRequest::diagnoseCycle(DiagnosticEngine &diags) const {
auto decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::circular_protocol_def, decl->getName());
}
void ExistentialTypeSupportedRequest::noteCycleStep(DiagnosticEngine &diags) const {
auto requirement = std::get<0>(getStorage());
diags.diagnose(requirement, diag::kind_declname_declared_here,
DescriptiveDeclKind::Protocol, requirement->getName());
}
Optional<bool> ExistentialTypeSupportedRequest::getCachedResult() const {
auto decl = std::get<0>(getStorage());
return decl->getCachedExistentialTypeSupported();
}
void ExistentialTypeSupportedRequest::cacheResult(bool value) const {
auto decl = std::get<0>(getStorage());
decl->setCachedExistentialTypeSupported(value);
}
//----------------------------------------------------------------------------//
// isFinal computation.
//----------------------------------------------------------------------------//
Optional<bool> IsFinalRequest::getCachedResult() const {
auto decl = std::get<0>(getStorage());
if (decl->LazySemanticInfo.isFinalComputed)
return decl->LazySemanticInfo.isFinal;
return None;
}
void IsFinalRequest::cacheResult(bool value) const {
auto decl = std::get<0>(getStorage());
decl->LazySemanticInfo.isFinalComputed = true;
decl->LazySemanticInfo.isFinal = value;
// Add an attribute for printing
if (value && !decl->getAttrs().hasAttribute<FinalAttr>())
decl->getAttrs().add(new (decl->getASTContext()) FinalAttr(/*Implicit=*/true));
}
//----------------------------------------------------------------------------//
// isDynamic computation.
//----------------------------------------------------------------------------//
Optional<bool> IsDynamicRequest::getCachedResult() const {
auto decl = std::get<0>(getStorage());
if (decl->LazySemanticInfo.isDynamicComputed)
return decl->LazySemanticInfo.isDynamic;
return None;
}
void IsDynamicRequest::cacheResult(bool value) const {
auto decl = std::get<0>(getStorage());
decl->setIsDynamic(value);
// Add an attribute for printing
if (value && !decl->getAttrs().hasAttribute<DynamicAttr>())
decl->getAttrs().add(new (decl->getASTContext()) DynamicAttr(/*Implicit=*/true));
}
//----------------------------------------------------------------------------//
// RequirementSignatureRequest computation.
//----------------------------------------------------------------------------//
Optional<ArrayRef<Requirement>> RequirementSignatureRequest::getCachedResult() const {
auto proto = std::get<0>(getStorage());
if (proto->isRequirementSignatureComputed())
return proto->getCachedRequirementSignature();
return None;
}
void RequirementSignatureRequest::cacheResult(ArrayRef<Requirement> value) const {
auto proto = std::get<0>(getStorage());
proto->setRequirementSignature(value);
}
//----------------------------------------------------------------------------//
// Requirement computation.
//----------------------------------------------------------------------------//
WhereClauseOwner::WhereClauseOwner(GenericContext *genCtx): dc(genCtx) {
if (const auto whereClause = genCtx->getTrailingWhereClause())
source = whereClause;
else
source = genCtx->getGenericParams();
}
WhereClauseOwner::WhereClauseOwner(AssociatedTypeDecl *atd)
: dc(atd->getInnermostDeclContext()),
source(atd->getTrailingWhereClause()) {}
SourceLoc WhereClauseOwner::getLoc() const {
if (auto where = source.dyn_cast<TrailingWhereClause *>())
return where->getWhereLoc();
if (auto attr = source.dyn_cast<SpecializeAttr *>())
return attr->getLocation();
return source.get<GenericParamList *>()->getWhereLoc();
}
void swift::simple_display(llvm::raw_ostream &out,
const WhereClauseOwner &owner) {
if (owner.source.is<TrailingWhereClause *>()) {
simple_display(out, owner.dc->getAsDecl());
} else if (owner.source.is<SpecializeAttr *>()) {
out << "@_specialize";
} else {
out << "(SIL generic parameter list)";
}
}
SourceLoc RequirementRequest::getNearestLoc() const {
auto owner = std::get<0>(getStorage());
return owner.getLoc();
}
void RequirementRequest::noteCycleStep(DiagnosticEngine &diags) const {
// For now, the GSB does a better job of describing the exact structure of
// the cycle.
//
// FIXME: We should consider merging the circularity handling the GSB does
// into this request. See rdar://55263708
}
MutableArrayRef<RequirementRepr> WhereClauseOwner::getRequirements() const {
if (const auto genericParams = source.dyn_cast<GenericParamList *>()) {
return genericParams->getRequirements();
} else if (const auto attr = source.dyn_cast<SpecializeAttr *>()) {
if (auto whereClause = attr->getTrailingWhereClause())
return whereClause->getRequirements();
} else if (const auto attr = source.dyn_cast<DifferentiableAttr *>()) {
if (auto whereClause = attr->getWhereClause())
return whereClause->getRequirements();
} else if (const auto whereClause = source.get<TrailingWhereClause *>()) {
return whereClause->getRequirements();
}
return { };
}
bool WhereClauseOwner::visitRequirements(
TypeResolutionStage stage,
llvm::function_ref<bool(Requirement, RequirementRepr *)> callback)
const && {
auto &evaluator = dc->getASTContext().evaluator;
auto requirements = getRequirements();
for (unsigned index : indices(requirements)) {
// Resolve to a requirement.
auto req = evaluator(RequirementRequest{*this, index, stage});
if (req) {
// Invoke the callback. If it returns true, we're done.
if (callback(*req, &requirements[index]))
return true;
continue;
}
llvm::handleAllErrors(
req.takeError(), [](const CyclicalRequestError<RequirementRequest> &E) {
// cycle detected
});
}
return false;
}
RequirementRepr &RequirementRequest::getRequirement() const {
auto owner = std::get<0>(getStorage());
auto index = std::get<1>(getStorage());
return owner.getRequirements()[index];
}
bool RequirementRequest::isCached() const {
return std::get<2>(getStorage()) == TypeResolutionStage::Interface;
}
//----------------------------------------------------------------------------//
// DefaultTypeRequest.
//----------------------------------------------------------------------------//
void swift::simple_display(llvm::raw_ostream &out,
const KnownProtocolKind kind) {
out << getProtocolName(kind);
}
//----------------------------------------------------------------------------//
// DefaultTypeRequest caching.
//----------------------------------------------------------------------------//
Optional<Type> DefaultTypeRequest::getCachedResult() const {
auto *DC = std::get<1>(getStorage());
auto knownProtocolKind = std::get<0>(getStorage());
const auto &cachedType = DC->getASTContext().getDefaultTypeRequestCache(
DC->getParentSourceFile(), knownProtocolKind);
return cachedType ? Optional<Type>(cachedType) : None;
}
void DefaultTypeRequest::cacheResult(Type value) const {
auto *DC = std::get<1>(getStorage());
auto knownProtocolKind = std::get<0>(getStorage());
auto &cacheEntry = DC->getASTContext().getDefaultTypeRequestCache(
DC->getParentSourceFile(), knownProtocolKind);
cacheEntry = value;
}
bool PropertyWrapperTypeInfoRequest::isCached() const {
auto nominal = std::get<0>(getStorage());
return nominal->getAttrs().hasAttribute<PropertyWrapperAttr>();;
}
bool AttachedPropertyWrappersRequest::isCached() const {
auto var = std::get<0>(getStorage());
return !var->getAttrs().isEmpty();
}
bool AttachedPropertyWrapperTypeRequest::isCached() const {
auto var = std::get<0>(getStorage());
return !var->getAttrs().isEmpty();
}
bool PropertyWrapperBackingPropertyTypeRequest::isCached() const {
auto var = std::get<0>(getStorage());
return !var->getAttrs().isEmpty();
}
bool PropertyWrapperBackingPropertyInfoRequest::isCached() const {
auto var = std::get<0>(getStorage());
return !var->getAttrs().isEmpty();
}
bool PropertyWrapperMutabilityRequest::isCached() const {
auto var = std::get<0>(getStorage());
return !var->getAttrs().isEmpty();
}
bool PropertyWrapperLValuenessRequest::isCached() const {
auto var = std::get<0>(getStorage());
return !var->getAttrs().isEmpty();
}
void swift::simple_display(
llvm::raw_ostream &out, const PropertyWrapperTypeInfo &propertyWrapper) {
out << "{ ";
if (propertyWrapper.valueVar)
out << propertyWrapper.valueVar->printRef();
else
out << "null";
out << " }";
}
void swift::simple_display(
llvm::raw_ostream &out,
const PropertyWrapperBackingPropertyInfo &backingInfo) {
out << "{ ";
if (backingInfo.backingVar)
backingInfo.backingVar->dumpRef(out);
out << " }";
}
void swift::simple_display(
llvm::raw_ostream &out, const CtorInitializerKind initKind) {
out << "{ ";
switch (initKind) {
case CtorInitializerKind::Designated:
out << "designated"; break;
case CtorInitializerKind::Convenience:
out << "convenience"; break;
case CtorInitializerKind::ConvenienceFactory:
out << "convenience_factory"; break;
case CtorInitializerKind::Factory:
out << "factory"; break;
}
out << " }";
}
void swift::simple_display(llvm::raw_ostream &os, PropertyWrapperMutability m) {
static const char *names[] =
{"is nonmutating", "is mutating", "doesn't exist"};
os << "getter " << names[m.Getter] << ", setter " << names[m.Setter];
}
void swift::simple_display(llvm::raw_ostream &out, PropertyWrapperLValueness l) {
out << "is lvalue for get: {";
simple_display(out, l.isLValueForGetAccess);
out << "}, is lvalue for set: {";
simple_display(out, l.isLValueForSetAccess);
out << "}";
}
void swift::simple_display(llvm::raw_ostream &out,
ResilienceExpansion value) {
switch (value) {
case ResilienceExpansion::Minimal:
out << "minimal";
break;
case ResilienceExpansion::Maximal:
out << "maximal";
break;
}
}
void swift::simple_display(llvm::raw_ostream &out,
FragileFunctionKind value) {
switch (value.kind) {
case FragileFunctionKind::Transparent:
out << "transparent";
break;
case FragileFunctionKind::Inlinable:
out << "inlinable";
break;
case FragileFunctionKind::AlwaysEmitIntoClient:
out << "alwaysEmitIntoClient";
break;
case FragileFunctionKind::DefaultArgument:
out << "defaultArgument";
break;
case FragileFunctionKind::PropertyInitializer:
out << "propertyInitializer";
break;
case FragileFunctionKind::None:
out << "none";
break;
}
out << ", allowUsableFromInline: "
<< (value.allowUsableFromInline ? "true" : "false");
}
//----------------------------------------------------------------------------//
// FunctionBuilder-related requests.
//----------------------------------------------------------------------------//
bool AttachedFunctionBuilderRequest::isCached() const {
// Only needs to be cached if there are any custom attributes.
auto var = std::get<0>(getStorage());
return var->getAttrs().hasAttribute<CustomAttr>();
}
//----------------------------------------------------------------------------//
// SelfAccessKindRequest computation.
//----------------------------------------------------------------------------//
Optional<SelfAccessKind> SelfAccessKindRequest::getCachedResult() const {
auto *funcDecl = std::get<0>(getStorage());
return funcDecl->getCachedSelfAccessKind();
}
void SelfAccessKindRequest::cacheResult(SelfAccessKind value) const {
auto *funcDecl = std::get<0>(getStorage());
funcDecl->setSelfAccessKind(value);
}
//----------------------------------------------------------------------------//
// IsGetterMutatingRequest computation.
//----------------------------------------------------------------------------//
Optional<bool> IsGetterMutatingRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
if (storage->LazySemanticInfo.IsGetterMutatingComputed)
return storage->LazySemanticInfo.IsGetterMutating;
return None;
}
void IsGetterMutatingRequest::cacheResult(bool value) const {
auto *storage = std::get<0>(getStorage());
storage->setIsGetterMutating(value);
}
//----------------------------------------------------------------------------//
// IsSetterMutatingRequest computation.
//----------------------------------------------------------------------------//
Optional<bool> IsSetterMutatingRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
if (storage->LazySemanticInfo.IsSetterMutatingComputed)
return storage->LazySemanticInfo.IsSetterMutating;
return None;
}
void IsSetterMutatingRequest::cacheResult(bool value) const {
auto *storage = std::get<0>(getStorage());
storage->setIsSetterMutating(value);
}
//----------------------------------------------------------------------------//
// OpaqueReadOwnershipRequest computation.
//----------------------------------------------------------------------------//
Optional<OpaqueReadOwnership>
OpaqueReadOwnershipRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
if (storage->LazySemanticInfo.OpaqueReadOwnershipComputed)
return OpaqueReadOwnership(storage->LazySemanticInfo.OpaqueReadOwnership);
return None;
}
void OpaqueReadOwnershipRequest::cacheResult(OpaqueReadOwnership value) const {
auto *storage = std::get<0>(getStorage());
storage->setOpaqueReadOwnership(value);
}
//----------------------------------------------------------------------------//
// StorageImplInfoRequest computation.
//----------------------------------------------------------------------------//
Optional<StorageImplInfo>
StorageImplInfoRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
if (storage->LazySemanticInfo.ImplInfoComputed)
return storage->ImplInfo;
return None;
}
void StorageImplInfoRequest::cacheResult(StorageImplInfo value) const {
auto *storage = std::get<0>(getStorage());
storage->setImplInfo(value);
}
//----------------------------------------------------------------------------//
// RequiresOpaqueAccessorsRequest computation.
//----------------------------------------------------------------------------//
Optional<bool>
RequiresOpaqueAccessorsRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
if (storage->LazySemanticInfo.RequiresOpaqueAccessorsComputed)
return storage->LazySemanticInfo.RequiresOpaqueAccessors;
return None;
}
void RequiresOpaqueAccessorsRequest::cacheResult(bool value) const {
auto *storage = std::get<0>(getStorage());
storage->LazySemanticInfo.RequiresOpaqueAccessorsComputed = 1;
storage->LazySemanticInfo.RequiresOpaqueAccessors = value;
}
//----------------------------------------------------------------------------//
// RequiresOpaqueModifyCoroutineRequest computation.
//----------------------------------------------------------------------------//
Optional<bool>
RequiresOpaqueModifyCoroutineRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
if (storage->LazySemanticInfo.RequiresOpaqueModifyCoroutineComputed)
return storage->LazySemanticInfo.RequiresOpaqueModifyCoroutine;
return None;
}
void RequiresOpaqueModifyCoroutineRequest::cacheResult(bool value) const {
auto *storage = std::get<0>(getStorage());
storage->LazySemanticInfo.RequiresOpaqueModifyCoroutineComputed = 1;
storage->LazySemanticInfo.RequiresOpaqueModifyCoroutine = value;
}
//----------------------------------------------------------------------------//
// IsAccessorTransparentRequest computation.
//----------------------------------------------------------------------------//
Optional<bool>
IsAccessorTransparentRequest::getCachedResult() const {
auto *accessor = std::get<0>(getStorage());
return accessor->getCachedIsTransparent();
}
void IsAccessorTransparentRequest::cacheResult(bool value) const {
auto *accessor = std::get<0>(getStorage());
accessor->setIsTransparent(value);
// For interface printing, API diff, etc.
if (value) {
auto &attrs = accessor->getAttrs();
if (!attrs.hasAttribute<TransparentAttr>()) {
auto &ctx = accessor->getASTContext();
attrs.add(new (ctx) TransparentAttr(/*IsImplicit=*/true));
}
}
}
//----------------------------------------------------------------------------//
// SynthesizeAccessorRequest computation.
//----------------------------------------------------------------------------//
Optional<AccessorDecl *>
SynthesizeAccessorRequest::getCachedResult() const {
auto *storage = std::get<0>(getStorage());
auto kind = std::get<1>(getStorage());
auto *accessor = storage->getAccessor(kind);
if (accessor)
return accessor;
return None;
}
void SynthesizeAccessorRequest::cacheResult(AccessorDecl *accessor) const {
auto *storage = std::get<0>(getStorage());
auto kind = std::get<1>(getStorage());
storage->setSynthesizedAccessor(kind, accessor);
}
//----------------------------------------------------------------------------//
// IsImplicitlyUnwrappedOptionalRequest computation.
//----------------------------------------------------------------------------//
Optional<bool>
IsImplicitlyUnwrappedOptionalRequest::getCachedResult() const {
auto *decl = std::get<0>(getStorage());
if (decl->LazySemanticInfo.isIUOComputed)
return decl->LazySemanticInfo.isIUO;
return None;
}
void IsImplicitlyUnwrappedOptionalRequest::cacheResult(bool value) const {
auto *decl = std::get<0>(getStorage());
decl->setImplicitlyUnwrappedOptional(value);
}
//----------------------------------------------------------------------------//
// GenericSignatureRequest computation.
//----------------------------------------------------------------------------//
Optional<GenericSignature> GenericSignatureRequest::getCachedResult() const {
auto *GC = std::get<0>(getStorage());
if (GC->GenericSigAndBit.getInt()) {
return GC->GenericSigAndBit.getPointer();
}
return None;
}
void GenericSignatureRequest::cacheResult(GenericSignature value) const {
auto *GC = std::get<0>(getStorage());
GC->GenericSigAndBit.setPointerAndInt(value, true);
}
//----------------------------------------------------------------------------//
// InferredGenericSignatureRequest computation.
//----------------------------------------------------------------------------//
void InferredGenericSignatureRequest::noteCycleStep(DiagnosticEngine &d) const {
// For now, the GSB does a better job of describing the exact structure of
// the cycle.
//
// FIXME: We should consider merging the circularity handling the GSB does
// into this request. See rdar://55263708
}
//----------------------------------------------------------------------------//
// UnderlyingTypeRequest computation.
//----------------------------------------------------------------------------//
Optional<Type>
UnderlyingTypeRequest::getCachedResult() const {
auto *typeAlias = std::get<0>(getStorage());
if (auto type = typeAlias->UnderlyingTy.getType())
return type;
return None;
}
void UnderlyingTypeRequest::cacheResult(Type value) const {
auto *typeAlias = std::get<0>(getStorage());
typeAlias->UnderlyingTy.setType(value);
}
void UnderlyingTypeRequest::diagnoseCycle(DiagnosticEngine &diags) const {
auto aliasDecl = std::get<0>(getStorage());
diags.diagnose(aliasDecl, diag::recursive_decl_reference,
aliasDecl->getDescriptiveKind(),
aliasDecl->getName());
}
//----------------------------------------------------------------------------//
// EnumRawValuesRequest computation.
//----------------------------------------------------------------------------//
bool EnumRawValuesRequest::isCached() const {
return std::get<1>(getStorage()) == TypeResolutionStage::Interface;
}
Optional<evaluator::SideEffect> EnumRawValuesRequest::getCachedResult() const {
auto *ED = std::get<0>(getStorage());
if (ED->LazySemanticInfo.hasCheckedRawValues())
return std::make_tuple<>();
return None;
}
void EnumRawValuesRequest::cacheResult(evaluator::SideEffect) const {
auto *ED = std::get<0>(getStorage());
auto flags = ED->LazySemanticInfo.RawTypeAndFlags.getInt() |
EnumDecl::HasFixedRawValues |
EnumDecl::HasFixedRawValuesAndTypes;
ED->LazySemanticInfo.RawTypeAndFlags.setInt(flags);
}
void EnumRawValuesRequest::diagnoseCycle(DiagnosticEngine &diags) const {
// This request computes the raw type, and so participates in cycles involving
// it. For now, the raw type provides a rich enough circularity diagnostic
// that we can silence ourselves.
}
void EnumRawValuesRequest::noteCycleStep(DiagnosticEngine &diags) const {
}
//----------------------------------------------------------------------------//
// IsStaticRequest computation.
//----------------------------------------------------------------------------//
Optional<bool> IsStaticRequest::getCachedResult() const {
auto *FD = std::get<0>(getStorage());
return FD->getCachedIsStatic();
}
void IsStaticRequest::cacheResult(bool result) const {
auto *FD = std::get<0>(getStorage());
FD->setStatic(result);
}
//----------------------------------------------------------------------------//
// NeedsNewVTableEntryRequest computation.
//----------------------------------------------------------------------------//
Optional<bool> NeedsNewVTableEntryRequest::getCachedResult() const {
auto *decl = std::get<0>(getStorage());
if (decl->LazySemanticInfo.NeedsNewVTableEntryComputed)
return decl->LazySemanticInfo.NeedsNewVTableEntry;
return None;
}
void NeedsNewVTableEntryRequest::cacheResult(bool value) const {
auto *decl = std::get<0>(getStorage());
decl->LazySemanticInfo.NeedsNewVTableEntryComputed = true;
decl->LazySemanticInfo.NeedsNewVTableEntry = value;
}
//----------------------------------------------------------------------------//
// ParamSpecifierRequest computation.
//----------------------------------------------------------------------------//
Optional<ParamSpecifier> ParamSpecifierRequest::getCachedResult() const {
auto *decl = std::get<0>(getStorage());
return decl->getCachedSpecifier();
}
void ParamSpecifierRequest::cacheResult(ParamSpecifier specifier) const {
auto *decl = std::get<0>(getStorage());
decl->setSpecifier(specifier);
}
//----------------------------------------------------------------------------//
// ResultTypeRequest computation.
//----------------------------------------------------------------------------//
TypeLoc &ResultTypeRequest::getResultTypeLoc() const {
auto *decl = std::get<0>(getStorage());
if (auto *funcDecl = dyn_cast<FuncDecl>(decl))
return funcDecl->getBodyResultTypeLoc();
auto *subscriptDecl = cast<SubscriptDecl>(decl);
return subscriptDecl->getElementTypeLoc();
}
Optional<Type> ResultTypeRequest::getCachedResult() const {
if (auto type = getResultTypeLoc().getType())
return type;
return None;
}
void ResultTypeRequest::cacheResult(Type type) const {
getResultTypeLoc().setType(type);
}
//----------------------------------------------------------------------------//
// PatternBindingEntryRequest computation.
//----------------------------------------------------------------------------//
Optional<const PatternBindingEntry *>
PatternBindingEntryRequest::getCachedResult() const {
auto *PBD = std::get<0>(getStorage());
auto idx = std::get<1>(getStorage());
if (!PBD->getPatternList()[idx].isFullyValidated()) {
return None;
}
return &PBD->getPatternList()[idx];
}
void PatternBindingEntryRequest::cacheResult(
const PatternBindingEntry *value) const {
auto *PBD = std::get<0>(getStorage());
auto idx = std::get<1>(getStorage());
PBD->getMutablePatternList()[idx].setFullyValidated();
}
//----------------------------------------------------------------------------//
// NamingPatternRequest computation.
//----------------------------------------------------------------------------//
Optional<NamedPattern *> NamingPatternRequest::getCachedResult() const {
auto *VD = std::get<0>(getStorage());
if (auto *Pat = VD->NamingPattern) {
return Pat;
}
return None;
}
void NamingPatternRequest::cacheResult(NamedPattern *value) const {
auto *VD = std::get<0>(getStorage());
VD->NamingPattern = value;
}
//----------------------------------------------------------------------------//
// InterfaceTypeRequest computation.
//----------------------------------------------------------------------------//
Optional<Type> InterfaceTypeRequest::getCachedResult() const {
auto *decl = std::get<0>(getStorage());
if (auto Ty = decl->TypeAndAccess.getPointer()) {
return Ty;
}
return None;
}
void InterfaceTypeRequest::cacheResult(Type type) const {
auto *decl = std::get<0>(getStorage());
if (type) {
assert(!type->hasTypeVariable() && "Type variable in interface type");
assert(!type->is<InOutType>() && "Interface type must be materializable");
assert(!type->hasArchetype() && "Archetype in interface type");
}
decl->TypeAndAccess.setPointer(type);
}
//----------------------------------------------------------------------------//
// ValidatePrecedenceGroupRequest computation.
//----------------------------------------------------------------------------//
SourceLoc ValidatePrecedenceGroupRequest::getNearestLoc() const {
auto &desc = std::get<0>(getStorage());
return desc.getLoc();
}
void ValidatePrecedenceGroupRequest::diagnoseCycle(
DiagnosticEngine &diags) const {
auto &desc = std::get<0>(getStorage());
if (auto pathDir = desc.pathDirection) {
diags.diagnose(desc.nameLoc, diag::precedence_group_cycle, (bool)*pathDir);
} else {
diags.diagnose(desc.nameLoc, diag::circular_reference);
}
}
void ValidatePrecedenceGroupRequest::noteCycleStep(
DiagnosticEngine &diag) const {
auto &desc = std::get<0>(getStorage());
diag.diagnose(desc.nameLoc,
diag::circular_reference_through_precedence_group, desc.ident);
}
SourceLoc PrecedenceGroupDescriptor::getLoc() const {
return nameLoc;
}
void swift::simple_display(llvm::raw_ostream &out,
const PrecedenceGroupDescriptor &desc) {
out << "precedence group " << desc.ident << " at ";
desc.nameLoc.print(out, desc.dc->getASTContext().SourceMgr);
}
//----------------------------------------------------------------------------//
// InheritsSuperclassInitializersRequest computation.
//----------------------------------------------------------------------------//
Optional<bool> InheritsSuperclassInitializersRequest::getCachedResult() const {
auto *decl = std::get<0>(getStorage());
return decl->getCachedInheritsSuperclassInitializers();
}
void InheritsSuperclassInitializersRequest::cacheResult(bool value) const {
auto *decl = std::get<0>(getStorage());
decl->setInheritsSuperclassInitializers(value);
}
//----------------------------------------------------------------------------//
// ResolveImplicitMemberRequest computation.
//----------------------------------------------------------------------------//
void swift::simple_display(llvm::raw_ostream &out,
ImplicitMemberAction action) {
switch (action) {
case ImplicitMemberAction::ResolveImplicitInit:
out << "resolve implicit initializer";
break;
case ImplicitMemberAction::ResolveCodingKeys:
out << "resolve CodingKeys";
break;
case ImplicitMemberAction::ResolveEncodable:
out << "resolve Encodable.encode(to:)";
break;
case ImplicitMemberAction::ResolveDecodable:
out << "resolve Decodable.init(from:)";
break;
}
}
//----------------------------------------------------------------------------//
// TypeWitnessRequest computation.
//----------------------------------------------------------------------------//
Optional<TypeWitnessAndDecl> TypeWitnessRequest::getCachedResult() const {
auto *conformance = std::get<0>(getStorage());
auto *requirement = std::get<1>(getStorage());
if (conformance->TypeWitnesses.count(requirement) == 0) {
return None;
}
return conformance->TypeWitnesses[requirement];
}
void TypeWitnessRequest::cacheResult(TypeWitnessAndDecl typeWitAndDecl) const {
// FIXME: Refactor this to be the thing that warms the cache.
}
//----------------------------------------------------------------------------//
// WitnessRequest computation.
//----------------------------------------------------------------------------//
Optional<Witness> ValueWitnessRequest::getCachedResult() const {
auto *conformance = std::get<0>(getStorage());
auto *requirement = std::get<1>(getStorage());
if (conformance->Mapping.count(requirement) == 0) {
return None;
}
return conformance->Mapping[requirement];
}
void ValueWitnessRequest::cacheResult(Witness type) const {
// FIXME: Refactor this to be the thing that warms the cache.
}
//----------------------------------------------------------------------------//
// PreCheckFunctionBuilderRequest computation.
//----------------------------------------------------------------------------//
void swift::simple_display(llvm::raw_ostream &out,
FunctionBuilderBodyPreCheck value) {
switch (value) {
case FunctionBuilderBodyPreCheck::Okay:
out << "okay";
break;
case FunctionBuilderBodyPreCheck::HasReturnStmt:
out << "has return statement";
break;
case FunctionBuilderBodyPreCheck::Error:
out << "error";
break;
}
}
//----------------------------------------------------------------------------//
// HasCircularInheritanceRequest computation.
//----------------------------------------------------------------------------//
void HasCircularInheritanceRequest::diagnoseCycle(
DiagnosticEngine &diags) const {
auto *decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::circular_class_inheritance, decl->getName());
}
void HasCircularInheritanceRequest::noteCycleStep(
DiagnosticEngine &diags) const {
auto *decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::kind_declname_declared_here,
decl->getDescriptiveKind(), decl->getName());
}
//----------------------------------------------------------------------------//
// HasCircularInheritedProtocolsRequest computation.
//----------------------------------------------------------------------------//
void HasCircularInheritedProtocolsRequest::diagnoseCycle(
DiagnosticEngine &diags) const {
auto *decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::circular_protocol_def, decl->getName());
}
void HasCircularInheritedProtocolsRequest::noteCycleStep(
DiagnosticEngine &diags) const {
auto *decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::kind_declname_declared_here,
decl->getDescriptiveKind(), decl->getName());
}
//----------------------------------------------------------------------------//
// HasCircularRawValueRequest computation.
//----------------------------------------------------------------------------//
void HasCircularRawValueRequest::diagnoseCycle(DiagnosticEngine &diags) const {
auto *decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::circular_enum_inheritance, decl->getName());
}
void HasCircularRawValueRequest::noteCycleStep(DiagnosticEngine &diags) const {
auto *decl = std::get<0>(getStorage());
diags.diagnose(decl, diag::kind_declname_declared_here,
decl->getDescriptiveKind(), decl->getName());
}
//----------------------------------------------------------------------------//
// DefaultArgumentInitContextRequest computation.
//----------------------------------------------------------------------------//
Optional<Initializer *>
DefaultArgumentInitContextRequest::getCachedResult() const {
auto *param = std::get<0>(getStorage());
return param->getCachedDefaultArgumentInitContext();
}
void DefaultArgumentInitContextRequest::cacheResult(Initializer *init) const {
auto *param = std::get<0>(getStorage());
param->setDefaultArgumentInitContext(init);
}
//----------------------------------------------------------------------------//
// DefaultArgumentExprRequest computation.
//----------------------------------------------------------------------------//
Optional<Expr *> DefaultArgumentExprRequest::getCachedResult() const {
auto *param = std::get<0>(getStorage());
auto *defaultInfo = param->DefaultValueAndFlags.getPointer();
if (!defaultInfo)
return None;
if (!defaultInfo->InitContextAndIsTypeChecked.getInt())
return None;
return defaultInfo->DefaultArg.get<Expr *>();
}
void DefaultArgumentExprRequest::cacheResult(Expr *expr) const {
auto *param = std::get<0>(getStorage());
param->setDefaultExpr(expr, /*isTypeChecked*/ true);
}
//----------------------------------------------------------------------------//
// CallerSideDefaultArgExprRequest computation.
//----------------------------------------------------------------------------//
Optional<Expr *> CallerSideDefaultArgExprRequest::getCachedResult() const {
auto *defaultExpr = std::get<0>(getStorage());
auto storage = defaultExpr->ContextOrCallerSideExpr;
assert(!storage.isNull());
if (auto *expr = storage.dyn_cast<Expr *>())
return expr;
return None;
}
void CallerSideDefaultArgExprRequest::cacheResult(Expr *expr) const {
auto *defaultExpr = std::get<0>(getStorage());
defaultExpr->ContextOrCallerSideExpr = expr;
}
//----------------------------------------------------------------------------//
// DifferentiableAttributeTypeCheckRequest computation.
//----------------------------------------------------------------------------//
Optional<IndexSubset *>
DifferentiableAttributeTypeCheckRequest::getCachedResult() const {
auto *attr = std::get<0>(getStorage());
if (attr->hasBeenTypeChecked())
return attr->ParameterIndicesAndBit.getPointer();
return None;
}
void DifferentiableAttributeTypeCheckRequest::cacheResult(
IndexSubset *parameterIndices) const {
auto *attr = std::get<0>(getStorage());
attr->ParameterIndicesAndBit.setPointerAndInt(parameterIndices, true);
}
//----------------------------------------------------------------------------//
// CheckRedeclarationRequest computation.
//----------------------------------------------------------------------------//
Optional<evaluator::SideEffect>
CheckRedeclarationRequest::getCachedResult() const {
if (!std::get<0>(getStorage())->alreadyCheckedRedeclaration())
return None;
return std::make_tuple<>();
}
void CheckRedeclarationRequest::cacheResult(evaluator::SideEffect) const {
std::get<0>(getStorage())->setCheckedRedeclaration();
}
evaluator::DependencySource CheckRedeclarationRequest::readDependencySource(
const evaluator::DependencyRecorder &eval) const {
auto *current = std::get<0>(getStorage());
auto *currentDC = current->getDeclContext();
return {
currentDC->getParentSourceFile(),
evaluator::getScopeForAccessLevel(current->getFormalAccess())
};
}
void CheckRedeclarationRequest::writeDependencySink(
evaluator::DependencyCollector &tracker, evaluator::SideEffect) const {
auto *current = std::get<0>(getStorage());
if (!current->hasName())
return;
DeclContext *currentDC = current->getDeclContext();
SourceFile *currentFile = currentDC->getParentSourceFile();
if (!currentFile || currentDC->isLocalContext())
return;
if (currentDC->isTypeContext()) {
if (auto nominal = currentDC->getSelfNominalTypeDecl()) {
tracker.addUsedMember(nominal, current->getBaseName());
}
} else {
tracker.addTopLevelName(current->getBaseName());
}
}
//----------------------------------------------------------------------------//
// LookupAllConformancesInContextRequest computation.
//----------------------------------------------------------------------------//
evaluator::DependencySource
LookupAllConformancesInContextRequest::readDependencySource(
const evaluator::DependencyRecorder &collector) const {
const auto *nominal = std::get<0>(getStorage())
->getAsGenericContext()
->getSelfNominalTypeDecl();
if (!nominal) {
return {collector.getActiveDependencySourceOrNull(),
evaluator::DependencyScope::Cascading};
}
return {collector.getActiveDependencySourceOrNull(),
evaluator::getScopeForAccessLevel(nominal->getFormalAccess())};
}
void LookupAllConformancesInContextRequest::writeDependencySink(
evaluator::DependencyCollector &tracker,
ProtocolConformanceLookupResult conformances) const {
for (auto conformance : conformances) {
tracker.addPotentialMember(conformance->getProtocol());
}
}
//----------------------------------------------------------------------------//
// ResolveTypeEraserTypeRequest computation.
//----------------------------------------------------------------------------//
Optional<Type> ResolveTypeEraserTypeRequest::getCachedResult() const {
auto *TyExpr = std::get<1>(getStorage())->TypeEraserExpr;
if (!TyExpr || !TyExpr->getType()) {
return None;
}
return TyExpr->getInstanceType();
}
void ResolveTypeEraserTypeRequest::cacheResult(Type value) const {
assert(value && "Resolved type erasure type to null type!");
auto *attr = std::get<1>(getStorage());
if (attr->TypeEraserExpr) {
attr->TypeEraserExpr->setType(MetatypeType::get(value));
} else {
attr->TypeEraserExpr = TypeExpr::createImplicit(value,
value->getASTContext());
}
}
//----------------------------------------------------------------------------//
// TypeCheckSourceFileRequest computation.
//----------------------------------------------------------------------------//
evaluator::DependencySource TypeCheckSourceFileRequest::readDependencySource(
const evaluator::DependencyRecorder &e) const {
return {std::get<0>(getStorage()), evaluator::DependencyScope::Cascading};
}
Optional<evaluator::SideEffect>
TypeCheckSourceFileRequest::getCachedResult() const {
auto *SF = std::get<0>(getStorage());
if (SF->ASTStage == SourceFile::TypeChecked)
return std::make_tuple<>();
return None;
}
void TypeCheckSourceFileRequest::cacheResult(evaluator::SideEffect) const {
auto *SF = std::get<0>(getStorage());
// Verify that we've checked types correctly.
SF->ASTStage = SourceFile::TypeChecked;
{
auto &Ctx = SF->getASTContext();
FrontendStatsTracer tracer(Ctx.Stats, "AST verification");
// Verify the SourceFile.
swift::verify(*SF);
}
}
//----------------------------------------------------------------------------//
// TypeCheckFunctionBodyRequest computation.
//----------------------------------------------------------------------------//
evaluator::DependencySource
TypeCheckFunctionBodyRequest::readDependencySource(
const evaluator::DependencyRecorder &e) const {
// We're going under a function body scope, unconditionally flip the scope
// to private.
return {
std::get<0>(getStorage())->getParentSourceFile(),
evaluator::DependencyScope::Private
};
}
//----------------------------------------------------------------------------//
// ModuleImplicitImportsRequest computation.
//----------------------------------------------------------------------------//
void swift::simple_display(llvm::raw_ostream &out,
const ImplicitImport &import) {
out << "implicit import of ";
simple_display(out, import.Module);
}
//----------------------------------------------------------------------------//
// ResolveTypeRequest computation.
//----------------------------------------------------------------------------//
void ResolveTypeRequest::noteCycleStep(DiagnosticEngine &diags) const {
auto *repr = std::get<1>(getStorage());
diags.diagnose(repr->getLoc(), diag::circular_type_resolution_note, repr);
}
void swift::simple_display(llvm::raw_ostream &out,
const TypeResolution *resolution) {
out << "while resolving type ";
}
SourceLoc swift::extractNearestSourceLoc(const TypeRepr *repr) {
if (!repr)
return SourceLoc();
return repr->getLoc();
}
//----------------------------------------------------------------------------//
// CustomAttrTypeRequest computation.
//----------------------------------------------------------------------------//
void swift::simple_display(llvm::raw_ostream &out, CustomAttrTypeKind value) {
switch (value) {
case CustomAttrTypeKind::NonGeneric:
out << "non-generic";
return;
case CustomAttrTypeKind::PropertyDelegate:
out << "property-delegate";
return;
}
llvm_unreachable("bad kind");
}
Optional<Type> CustomAttrTypeRequest::getCachedResult() const {
auto *attr = std::get<0>(getStorage());
if (auto ty = attr->getType()) {
return ty;
}
return None;
}
void CustomAttrTypeRequest::cacheResult(Type value) const {
auto *attr = std::get<0>(getStorage());
attr->setType(value);
}
| apache-2.0 |
awslabs/aws-sdk-cpp | aws-cpp-sdk-discovery/source/model/DescribeExportTasksRequest.cpp | 3 | 1872 | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/discovery/model/DescribeExportTasksRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::ApplicationDiscoveryService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeExportTasksRequest::DescribeExportTasksRequest() :
m_exportIdsHasBeenSet(false),
m_filtersHasBeenSet(false),
m_maxResults(0),
m_maxResultsHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
}
Aws::String DescribeExportTasksRequest::SerializePayload() const
{
JsonValue payload;
if(m_exportIdsHasBeenSet)
{
Array<JsonValue> exportIdsJsonList(m_exportIds.size());
for(unsigned exportIdsIndex = 0; exportIdsIndex < exportIdsJsonList.GetLength(); ++exportIdsIndex)
{
exportIdsJsonList[exportIdsIndex].AsString(m_exportIds[exportIdsIndex]);
}
payload.WithArray("exportIds", std::move(exportIdsJsonList));
}
if(m_filtersHasBeenSet)
{
Array<JsonValue> filtersJsonList(m_filters.size());
for(unsigned filtersIndex = 0; filtersIndex < filtersJsonList.GetLength(); ++filtersIndex)
{
filtersJsonList[filtersIndex].AsObject(m_filters[filtersIndex].Jsonize());
}
payload.WithArray("filters", std::move(filtersJsonList));
}
if(m_maxResultsHasBeenSet)
{
payload.WithInteger("maxResults", m_maxResults);
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("nextToken", m_nextToken);
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeExportTasksRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSPoseidonService_V2015_11_01.DescribeExportTasks"));
return headers;
}
| apache-2.0 |
krishnabangalore/Webinos-Platform | experiments/PolicyManager_c++_jni/core/policymanager/IPolicyBase.cpp | 3 | 1587 | /*******************************************************************************
* Copyright 2010 Telecom Italia SpA
*
* 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 "IPolicyBase.h"
/*
string IPolicyBase::first_matching_target_algorithm = "first-matching-target";
string IPolicyBase::deny_overrides_algorithm = "deny-overrides";
string IPolicyBase::permit_overrides_algorithm = "permit-overrides";
string IPolicyBase::first_applicable_algorithm = "first-applicable";
*/
IPolicyBase::IPolicyBase(TiXmlElement* elem)
{
description = (elem->Attribute("description")!=NULL) ? elem->Attribute("description") : "no_value";
// TODO Auto-generated constructor stub
}
IPolicyBase::IPolicyBase(IPolicyBase* base)
{
// TODO Auto-generated constructor stub
}
IPolicyBase::~IPolicyBase()
{
// TODO Auto-generated destructor stub
}
bool IPolicyBase::matchSubject(Request*){}
Effect IPolicyBase::evaluate(Request *){}
PolicyType IPolicyBase::get_iType(){
return POLICY_SET;
}
| apache-2.0 |
craigacgomez/flaming_monkey_system_core | libcutils/qtaguid.c | 4 | 4868 | /* libcutils/qtaguid.c
**
** Copyright 2011, 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.
*/
// #define LOG_NDEBUG 0
#define LOG_TAG "qtaguid"
#include <cutils/qtaguid.h>
#include <cutils/log.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
static const char* CTRL_PROCPATH = "/proc/net/xt_qtaguid/ctrl";
static const int CTRL_MAX_INPUT_LEN = 128;
static const char *GLOBAL_PACIFIER_PARAM = "/sys/module/xt_qtaguid/parameters/passive";
static const char *TAG_PACIFIER_PARAM = "/sys/module/xt_qtaguid/parameters/tag_tracking_passive";
/*
* One per proccess.
* Once the device is open, this process will have its socket tags tracked.
* And on exit or untimely death, all socket tags will be removed.
* A process can only open /dev/xt_qtaguid once.
* It should not close it unless it is really done with all the socket tags.
* Failure to open it will be visible when socket tagging will be attempted.
*/
static int resTrackFd = -1;
pthread_once_t resTrackInitDone = PTHREAD_ONCE_INIT;
/* Only call once per process. */
void qtaguid_resTrack(void) {
resTrackFd = TEMP_FAILURE_RETRY(open("/dev/xt_qtaguid", O_RDONLY));
if (resTrackFd >=0) {
TEMP_FAILURE_RETRY(fcntl(resTrackFd, F_SETFD, FD_CLOEXEC));
}
}
/*
* Returns:
* 0 on success.
* -errno on failure.
*/
static int write_ctrl(const char *cmd) {
int fd, res, savedErrno;
ALOGV("write_ctrl(%s)", cmd);
fd = TEMP_FAILURE_RETRY(open(CTRL_PROCPATH, O_WRONLY));
if (fd < 0) {
return -errno;
}
res = TEMP_FAILURE_RETRY(write(fd, cmd, strlen(cmd)));
if (res < 0) {
savedErrno = errno;
} else {
savedErrno = 0;
}
if (res < 0) {
ALOGI("Failed write_ctrl(%s) res=%d errno=%d", cmd, res, savedErrno);
}
close(fd);
return -savedErrno;
}
static int write_param(const char *param_path, const char *value) {
int param_fd;
int res;
param_fd = TEMP_FAILURE_RETRY(open(param_path, O_WRONLY));
if (param_fd < 0) {
return -errno;
}
res = TEMP_FAILURE_RETRY(write(param_fd, value, strlen(value)));
if (res < 0) {
return -errno;
}
close(param_fd);
return 0;
}
int qtaguid_tagSocket(int sockfd, int tag, uid_t uid) {
char lineBuf[CTRL_MAX_INPUT_LEN];
int res;
uint64_t kTag = ((uint64_t)tag << 32);
pthread_once(&resTrackInitDone, qtaguid_resTrack);
snprintf(lineBuf, sizeof(lineBuf), "t %d %llu %d", sockfd, kTag, uid);
ALOGV("Tagging socket %d with tag %llx{%u,0} for uid %d", sockfd, kTag, tag, uid);
res = write_ctrl(lineBuf);
if (res < 0) {
ALOGI("Tagging socket %d with tag %llx(%d) for uid %d failed errno=%d",
sockfd, kTag, tag, uid, res);
}
return res;
}
int qtaguid_untagSocket(int sockfd) {
char lineBuf[CTRL_MAX_INPUT_LEN];
int res;
ALOGV("Untagging socket %d", sockfd);
snprintf(lineBuf, sizeof(lineBuf), "u %d", sockfd);
res = write_ctrl(lineBuf);
if (res < 0) {
ALOGI("Untagging socket %d failed errno=%d", sockfd, res);
}
return res;
}
int qtaguid_setCounterSet(int counterSetNum, uid_t uid) {
char lineBuf[CTRL_MAX_INPUT_LEN];
int res;
ALOGV("Setting counters to set %d for uid %d", counterSetNum, uid);
snprintf(lineBuf, sizeof(lineBuf), "s %d %d", counterSetNum, uid);
res = write_ctrl(lineBuf);
return res;
}
int qtaguid_deleteTagData(int tag, uid_t uid) {
char lineBuf[CTRL_MAX_INPUT_LEN];
int fd, cnt = 0, res = 0;
uint64_t kTag = (uint64_t)tag << 32;
ALOGV("Deleting tag data with tag %llx{%d,0} for uid %d", kTag, tag, uid);
pthread_once(&resTrackInitDone, qtaguid_resTrack);
snprintf(lineBuf, sizeof(lineBuf), "d %llu %d", kTag, uid);
res = write_ctrl(lineBuf);
if (res < 0) {
ALOGI("Deleteing tag data with tag %llx/%d for uid %d failed with cnt=%d errno=%d",
kTag, tag, uid, cnt, errno);
}
return res;
}
int qtaguid_setPacifier(int on) {
int param_fd;
int res;
const char *value;
value = on ? "Y" : "N";
if (write_param(GLOBAL_PACIFIER_PARAM, value) < 0) {
return -errno;
}
if (write_param(TAG_PACIFIER_PARAM, value) < 0) {
return -errno;
}
return 0;
}
| apache-2.0 |
minhlongdo/bde | groups/bsl/bslmf/bslmf_forwardingtype.t.cpp | 4 | 70710 | // bslmf_forwardingtype.t.cpp -*-C++-*-
#include <bslmf_forwardingtype.h>
#include <bslmf_addconst.h>
#include <bslmf_addcv.h>
#include <bslmf_addlvaluereference.h>
#include <bslmf_addvolatile.h>
#include <bslmf_isarray.h>
#include <bslmf_issame.h> // for testing only
#include <bsls_bsltestutil.h>
#include <bsls_nativestd.h>
#include <bsls_platform.h>
#include <bsls_bsltestutil.h>
#include <utility> // native_std::move for C++11
#include <stdio.h> // atoi()
#include <stdlib.h> // atoi()
#include <typeinfo>
using namespace BloombergLP;
#if defined(BSLS_PLATFORM_CMP_MSVC)
#pragma warning(disable: 4521) // test classes offer multiple copy constructors
#endif
// Suppress bde_verify messages about all-uppercase type names. Test drivers
// are rife with short names like 'F' or 'PF' or 'T' or 'T1'.
// BDE_VERIFY pragma: -UC01
// ============================================================================
// TEST PLAN
// ----------------------------------------------------------------------------
// Overview
// --------
// This component provides a meta-function. We simply verify that it returns
// the proper type for a list of suitably chosen arguments. It also provides a
// utility function for which we verify that it returns the correct type and
// value. Finally, we perform an end-to-end test that exercises the intended
// use of the component in order to verify that it is actually useful as
// specified.
// ----------------------------------------------------------------------------
// [ 2] ForwardingType<TYPE>::Type
// [ 3] ForwardingTypeUtil<TYPE>::TargetType
// [ 3] ForwardingTypeUtil<TYPE>::forwardToTarget(v)
// ----------------------------------------------------------------------------
// [ 4] END-TO-END OVERLOADING
// [ 5] USAGE EXAMPLES
// [ 1] CvRefMatch<T>::operator()()
// [ 1] CvArrayMatch<T>::operator()()
// [ 1] FuncMatch<F>::operator()()
// ============================================================================
// STANDARD BSL ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
printf("Error " __FILE__ "(%d): %s (failed)\n", line, message);
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BSL TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLS_BSLTESTUTIL_ASSERT
#define ASSERTV BSLS_BSLTESTUTIL_ASSERTV
#define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT
#define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally.
#define P BSLS_BSLTESTUTIL_P // Print identifier and value.
#define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLS_BSLTESTUTIL_L_ // current Line number
// ============================================================================
// ADDITIONAL MACROS FOR THIS TEST DRIVER
// ----------------------------------------------------------------------------
#define ASSERT_SAME(X, Y) ASSERT((bsl::is_same<X, Y>::value))
#if defined(BSLS_PLATFORM_CMP_SUN) \
|| defined(BSLS_PLATFORM_CMP_IBM) \
||(defined(BSLS_PLATFORM_CMP_GNU) && BSLS_PLATFORM_CMP_VERSION < 40300) \
||(defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VERSION < 1700)
# define BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND
// This macro signifies that this compiler rejects 'Type[]' as incomplete,
// even in contexts where it should be valid, such as where it will pass by
// reference or pointer.
#endif
#if defined(BSLS_PLATFORM_CMP_MSVC) && BSLS_PLATFORM_CMP_VERSION <= 1800
// This was last tested with MSVC 2013, but the bug may persist in later
// versions, not yet released. Update the version test accordingly.
# define BSLMF_FORWARDINGTYPE_NO_ARRAY_DECAY_TO_RVALUE_REF
// This compiler cannot bind an rvalue array, such as 'char[]', to a
// rvalue-reference to a decayed array pointer, which would be 'char *&&'
// in this example.
#endif
#if defined(BSLS_PLATFORM_CMP_SUN)
# define BSLMF_FOWARDINGTYPE_WORK_AROUND_SUN_ARRAY_TESTS
// The Sun compiler has problems with any test involving arrays, triggering
// internal compiler errors with no hint of the line(s) triggering the
// problem. This appears to be an artifact of several function templates
// that are called by explicitly specifying the first template parameter to
// be an array type. If the function argument is also an array type, the
// internal compiler error is triggered, while transforming that function
// parameter type to an array reference appears to solve the problem. As
// the fix is entirely about making the test driver well-formed, and does
// not impact the component header, this is deemed an acceptable workaround
// to pass the test.
//
// This code has not yet been tested against the Sun CC 12.4 compiler (or
// later) which has significantly improved standard conformance, including
// support for most of C++11.
#endif
//=============================================================================
// GLOBAL TYPES/OBJECTS FOR TESTING
//-----------------------------------------------------------------------------
enum Enum { e_VAL1 = 1, e_VAL2 };
struct Struct {
int d_data;
explicit Struct(int v) : d_data(v) { }
// Construct from the specified 'v'.
Struct(Struct& other) : d_data(other.d_data) { }
Struct(const Struct& other) : d_data(other.d_data) { }
Struct(volatile Struct& other) : d_data(other.d_data) { }
Struct(const volatile Struct& other) : d_data(other.d_data) { }
// Copy-construct from the specified 'other'.
};
inline
bool operator==(Struct a, Struct b)
// Return true if the specified 'a' and 'b' objects have same data member
// value.
{
return a.d_data == b.d_data;
}
union Union {
int d_data;
explicit Union(int v) : d_data(v) { }
// Construct from the specified 'v'.
Union(Union& other) : d_data(other.d_data) { }
Union(const Union& other) : d_data(other.d_data) { }
Union(volatile Union& other) : d_data(other.d_data) { }
Union(const volatile Union& other) : d_data(other.d_data) { }
// Copy-construct from the specified 'other'.
};
inline
bool operator==(Union a, Union b)
// Return true if the specified 'a' and 'b' objects have the same data
// member value.
{
return a.d_data == b.d_data;
}
class Class {
int d_data;
public:
explicit Class(int v) : d_data(v) { }
// Construct from the specified 'v'.
Class(Class& other) : d_data(other.d_data) { }
Class(const Class& other) : d_data(other.d_data) { }
Class(volatile Class& other) : d_data(other.d_data) { }
Class(const volatile Class& other) : d_data(other.d_data) { }
// Copy-construct from the specified 'other'.
int value() const { return d_data; }
// Return the value of this object.
};
inline
bool operator==(Class a, Class b)
// Return true if the specified 'a' and 'b' have the same 'value()'.
{
return a.value() == b.value();
}
typedef void F ();
typedef void (* PF)();
typedef void Fi (int);
typedef void FRi (int&);
typedef char A [5];
typedef char AU [];
typedef int Struct::*Pm;
typedef int (Class::*Pmf)() const;
void func() { }
// Noop function that takes no arguments and returns nothing.
void funcI(int) { }
// Noop function that takes one by-value argument and returns nothing.
void funcRi(int&) { }
// Noop function that takes one by-reference argument and returns nothing.
enum {
k_LVALUE,
k_CONST_LVALUE,
k_VOLATILE_LVALUE,
k_CONST_VOLATILE_LVALUE,
k_RVALUE,
k_CONST_RVALUE,
k_VOLATILE_RVALUE,
k_CONST_VOLATILE_RVALUE,
k_FUNC_POINTER,
k_FUNC_REFERENCE
};
template <class TP>
TP toRvalue(TP v)
// Return a copy of the specified 'v' object. If 'TP' has a cv-qualifier,
// then the compiler might discard it in the return type. For testing
// purposes, what is important is that we get exactly what we would get
// when returning an object of type 'TP'.
{
return v;
}
template <class TP>
struct CvRefMatch {
// Function object type that can be invoked with a cv-qualified reference
// to an object of the specified 'TP' parameter type.
int operator()(TP&) const { return k_LVALUE; }
int operator()(const TP&) const { return k_CONST_LVALUE; }
int operator()(volatile TP&) const { return k_VOLATILE_LVALUE; }
int operator()(const volatile TP&) const { return k_CONST_VOLATILE_LVALUE;}
// Invoke with an l-value reference.
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
int operator()(TP&&) const { return k_RVALUE; }
int operator()(const TP&&) const { return k_CONST_RVALUE; }
int operator()(volatile TP&&) const { return k_VOLATILE_RVALUE; }
int operator()(const volatile TP&&) const
// Invoke with an r-value reference.
{ return k_CONST_VOLATILE_RVALUE; }
#endif
};
template <class TP>
class CvArrayMatch {
// Function object type that can be invoked with an array of the specified
// 'TP' parameter type.
template <size_t k_SZ>
int match(TP (&)[k_SZ], int) const { return int(k_SZ); }
// Matches an array of known size.
int match(TP [], ...) const { return 0; }
// Matches an array of unknown size.
public:
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
template <class ANY>
int operator()(ANY&& a) const { return match(a, 0); }
// Matches both lvalue and rvalue arrays.
#else
template <class ANY>
int operator()(ANY& a) const { return match(a, 0); }
#endif
};
template <class FUNC>
struct FuncMatch {
// Function object type that can be invoked with a function, function
// pointer, or function reference.
struct MatchFuncPtr {
// Class that is convertible from 'FUNC *'
MatchFuncPtr(FUNC *) { } // IMPLICIT
// Convert a 'FUNC *' pointer to a 'MatchFuncPtr' object.
};
int operator()(FUNC&) const { return k_FUNC_REFERENCE; }
// Match a function or a function reference.
int operator()(MatchFuncPtr) const { return k_FUNC_POINTER; }
// Match function pointer. This overload requires a user-defined
// conversion and this is less preferred than the previous one for
// arguments that match both.
};
template <class TP, class INVOCABLE>
int endToEndIntermediary(typename bslmf::ForwardingType<TP>::Type arg,
const INVOCABLE& target)
// Forward the specified 'arg' to the specified 'target'. This function is
// called in the middle of a chain of function calls that forward to the
// eventual 'target' invocable object.
{
return target(bslmf::ForwardingTypeUtil<TP>::forwardToTarget(arg));
}
template <class TP, class INVOCABLE>
int testEndToEnd(TP arg, const INVOCABLE& target)
// Forward the specified 'arg' to the specified 'target' via an
// intermediate function. This function is called at the start of a chain
// of function calls that forward to the eventual 'target' invocable
// object.
{
return endToEndIntermediary<TP>(arg, target);
}
#if defined(BSLMF_FOWARDINGTYPE_WORK_AROUND_SUN_ARRAY_TESTS)
template <class TP, class INVOCABLE>
int testEndToEndArray(typename bsl::add_lvalue_reference<TP>::type arg,
const INVOCABLE& target)
// Forward the specified 'arg' to the specified 'target' via an
// intermediate function. This function is called at the start of a chain
// of function calls that forward to the eventual 'target' invocable
// object.
{
return endToEndIntermediary<TP>(arg, target);
}
#endif
//=============================================================================
// USAGE EXAMPLES
//-----------------------------------------------------------------------------
///Usage
///-----
// In this section we show intended use of this component.
//
///Example 1: Direct look at metafunction results
///- - - - - - - - - - - - - - - - - - - - - - -
// In this example, we invoke 'ForwardingType' on a variety of types and look
// at the resulting 'Type' member:
//..
struct MyType {};
typedef MyType& MyTypeRef;
void usageExample1()
// Usage example.
{
typedef int T1;
typedef int& T2;
typedef const volatile double& T3;
typedef const double & T4;
typedef const float * & T5;
typedef const float * const & T6;
typedef MyType T7;
typedef const MyType& T8;
typedef MyType& T9;
typedef MyType *T10;
typedef int EXP1;
typedef int& EXP2;
typedef const volatile double& EXP3;
typedef const double & EXP4;
typedef const float * & EXP5;
typedef const float * const & EXP6;
typedef const MyType& EXP7;
typedef const MyType& EXP8;
typedef MyType& EXP9;
typedef MyType *EXP10;
ASSERT((bsl::is_same<bslmf::ForwardingType<T1>::Type, EXP1>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T2>::Type, EXP2>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T3>::Type, EXP3>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T4>::Type, EXP4>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T5>::Type, EXP5>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T6>::Type, EXP6>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T7>::Type, EXP7>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T8>::Type, EXP8>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T9>::Type, EXP9>::value));
ASSERT((bsl::is_same<bslmf::ForwardingType<T10>::Type, EXP10>::value));
}
//..
//
///Example 2: A logging invocation wrapper
///- - - - - - - - - - - - - - - - - - - - - - -
// This example illustrates the use of 'ForwardingType' to efficiently
// implement a wrapper class that holds a function pointer and logs
// information about each call to the pointed-to-function through the wrapper.
// Suppose the pointed-to-function takes three arguments whose types are
// specified via template arguments, where the first argument is required to
// be convertible to 'int'.
//
// First we create a wrapper class that holds a function pointer of the
// desired type:
//..
// Primary template is never defined.
template <class PROTOTYPE>
class LoggingWrapper;
template <class RET, class ARG1, class ARG2, class ARG3>
class LoggingWrapper<RET(ARG1, ARG2, ARG3)> {
// Specialization of wrapper for specified function prototype.
RET (*d_function_p)(ARG1, ARG2, ARG3);
public:
explicit LoggingWrapper(RET (*function_p)(ARG1, ARG2, ARG3))
// Create a 'LoggingWrapper' object for the specified 'function_p'
// function.
: d_function_p(function_p) { }
//..
// Then, we declare an overload of the function-call operator that actually
// invokes the wrapped function. In order to avoid excessive copies of
// pass-by-value arguments, we use 'ForwardingType' to declare a more efficient
// intermediate argument type for our private member function:
//..
RET operator()(typename bslmf::ForwardingType<ARG1>::Type a1,
typename bslmf::ForwardingType<ARG2>::Type a2,
typename bslmf::ForwardingType<ARG3>::Type a3) const;
// Invoke the stored function pointer with the specified 'a1',
// 'a2', and 'a3' arguments, logging the invocation and returning
// the result of the function pointer invocation.
};
//..
// Next, we define logging functions that simply count the number of
// invocations and number of returns from invocations (e.g., to count how may
// invocations completed without exiting via exceptions):
//..
int invocations = 0, returns = 0;
void logInvocation(int /* ignored */) { ++invocations; }
// Log an invocation of the wrapped function.
void logReturn(int /* ignored */) { ++returns; }
// Log a return from the wrapped function.
//..
// Now, we implement 'operator()' call the logging functions, either side of
// calling the logged function through the wrapped pointer. To reconstitute
// the arguments to the function as close as possible to the types they were
// passed in as, we call the 'forwardToTarget' member of 'ForwardingTypeUtil':
//..
template <class RET, class ARG1, class ARG2, class ARG3>
RET LoggingWrapper<RET(ARG1, ARG2, ARG3)>::operator()(
typename bslmf::ForwardingType<ARG1>::Type a1,
typename bslmf::ForwardingType<ARG2>::Type a2,
typename bslmf::ForwardingType<ARG3>::Type a3) const {
logInvocation(a1);
RET r = d_function_p(
bslmf::ForwardingTypeUtil<ARG1>::forwardToTarget(a1),
bslmf::ForwardingTypeUtil<ARG2>::forwardToTarget(a2),
bslmf::ForwardingTypeUtil<ARG3>::forwardToTarget(a3));
logReturn(a1);
return r;
}
//..
// Then, in order to see this wrapper in action, we must define a function we
// wish to wrap. This function will take an argument of type 'ArgType' that
// holds an integer 'value' and keeps track of whether it has been directly
// constructed or copied from anther 'ArgType' object. If it has been copied,
// it keeps track of how many "generations" of copy were made:
//..
class ArgType {
int d_value;
int d_copies;
public:
explicit ArgType(int v = 0) : d_value(v), d_copies(0) { }
// Create an 'ArgType' object. Optionally specify 'v' as the
// initial value of this 'ArgType' object, otherwise this object
// will hold the value 0.
ArgType(const ArgType& original)
// Create an 'ArgType' object that is a copy of the specified
// 'original'.
: d_value(original.d_value)
, d_copies(original.d_copies + 1)
{ }
int copies() const { return d_copies; }
// Return the number of copies that this object is from the
// original.
int value() const { return d_value; }
// Return the value of this object.
};
int myFunc(const short& i, ArgType& x, ArgType y)
// Assign the specified 'x' the value of the specified 'y' and return
// the 'value()' of 'x'. Verify that the specified 'i' matches
// 'y.copies()'. 'x' is passed by reference in order to demonstrate
// forwarding of reference arguments.
{
ASSERT(i == y.copies());
x = y;
return x.value();
}
//..
// Finally, we create a instance of 'LoggingWrapper' to wrap 'myFunc', and we
// invoke it. Note that 'y' is copied into the second argument of 'operator()'
// and is copied again when 'myFunc' is invoked. However, it is *not* copied
// when 'operator()' calls 'invoke()' because the 'ForwardType' of 'ArgType' is
// 'const ArgType&', which does not create another copy. In C++11, if
// 'ArgType' had a move constructor, then the number of copies would be only 1,
// since the final forwarding would be a move instead of a copy.
//..
void usageExample2()
// Usage Example
{
ArgType x(0);
ArgType y(99);
LoggingWrapper<int(const short&, ArgType&, ArgType)> lw(myFunc);
ASSERT(0 == invocations && 0 == returns);
lw(1, x, y); // Expect exactly one copy of 'y'
ASSERT(1 == invocations && 1 == returns);
ASSERT(99 == x.value());
}
//..
//=============================================================================
// MAIN PROGRAM
//-----------------------------------------------------------------------------
template <class TYPE>
bool sameAddress(const TYPE& a, const TYPE& b)
// Return true if address of the specified 'a' object matches the address
// of the specified 'b' object. Unlike a direct test, this function can be
// called even if 'a' or 'b' is an rvalue or rvalue reference.
{
return &a == &b;
}
template <class TYPE>
bool sameAddress(TYPE& a, TYPE& b)
// Return true if address of the specified 'a' entity (of parameterized
// 'TYPE')) matches the address of the specified 'b' entity. Note that
// this second overload is necessary only for compilers like IBM xlC that
// will not deduce a match for 'const &' for function types and references.
{
return &a == &b;
}
template <class TYPE>
void testForwardToTargetVal(TYPE obj)
// Test 'forwardToTarget' when the specified 'obj' is an rvalue.
{
typedef typename bslmf::ForwardingType<TYPE>::Type FwdType;
typedef typename bslmf::ForwardingTypeUtil<TYPE>::TargetType TargetType;
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
ASSERT_SAME(TYPE, typename bsl::remove_reference<TargetType>::type);
#else
ASSERTV(typeid(TYPE).name(),
(bsl::is_same<TYPE,
typename bsl::remove_reference<TargetType>::type>::value ||
bsl::is_same<const TYPE,
typename bsl::remove_reference<TargetType>::type>::value));
#endif
FwdType fwdObj = obj;
// For pass-by-value, compare original and final value.
ASSERTV(typeid(TYPE).name(),
obj == bslmf::ForwardingTypeUtil<TYPE>::forwardToTarget(fwdObj));
}
template <class TYPE>
#if defined(BSLMF_FOWARDINGTYPE_WORK_AROUND_SUN_ARRAY_TESTS)
void testForwardToTargetArray(
typename bsl::add_lvalue_reference<TYPE>::type obj)
#else
void testForwardToTargetArray(TYPE obj)
#endif
// Test 'forwardToTarget' when the specified 'obj' is an array.
{
typedef typename bslmf::ForwardingType<TYPE>::Type FwdType;
typedef typename bslmf::ForwardingTypeUtil<TYPE>::TargetType TargetType;
typedef typename bsl::add_lvalue_reference<TYPE>::type RefType;
// gcc 4.1.2 does not support reference collapsing.
ASSERT_SAME(RefType, TargetType);
FwdType fwdObj = obj;
// For arrays, compare address of first element of original and final
// arrays.
ASSERTV(typeid(TYPE).name(),
&obj[0] ==
&bslmf::ForwardingTypeUtil<TYPE>::forwardToTarget(fwdObj)[0]);
}
template <class TYPE>
void testForwardToTargetRef(TYPE ref)
// Test 'forwardToTarget' when the specified 'ref' is a reference type.
{
typedef typename bslmf::ForwardingType<TYPE>::Type FwdType;
typedef typename bslmf::ForwardingTypeUtil<TYPE>::TargetType TargetType;
ASSERT_SAME(TYPE, TargetType);
FwdType fwdRef = ref;
// For pass-by-reference, compare addresses of original and final
// references.
ASSERTV(typeid(TYPE).name(),
sameAddress(ref,
bslmf::ForwardingTypeUtil<TYPE>::forwardToTarget(fwdRef)));
}
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
bool verbose = argc > 2;
bool veryVerbose = argc > 3;
(void) verbose; // eliminate unused variable warning
(void) veryVerbose; // eliminate unused variable warning
printf("TEST " __FILE__ " CASE %d\n", test);
switch (test) { case 0: // Zero is always the leading case.
case 5: {
// --------------------------------------------------------------------
// USAGE EXAMPLES
//
// Concerns: The usage examples in the component doc compile and run
// as promised.
//
// Plan: Copy the usage example from the component header, replace
// 'assert' with 'ASSERT' and 'main' with 'usageExampleN' and verify
// that it compiles and runs successfully.
//
// Testing:
// USAGE EXAMPLES
// --------------------------------------------------------------------
if (verbose) printf("\nUSAGE EXAMPLES"
"\n==============\n");
usageExample1();
usageExample2();
} break;
case 4: {
// --------------------------------------------------------------------
// TESTING END-TO-END OVERLOADING
//
// Concerns:
//: 1 An argument of type 'TP' that is passed to one function as 'TP',
//: forwarded through a second function as
//: 'ForwardingType<TP>::Type' and passed to a third (target)
//: function by calling 'ForwardingTypeUtil<TP>::forwardToTarget()'
//: will be seen by the target function as if the original argument
//: had been passed directly to it, including selecting the correct
//: overload and instantiation of the target function.
//: 2 Rvalue types are forwarded to the target function without
//: cv-qualification, regardless of whether an rvalue type is
//: primitive or of class type.
//: 3 Lvalue reference types are forwarded to the target with the
//: original cv-qualification.
//: 4 Rvalue reference types (C++11 and newer) are forwarded to the
//: target with the original cv-qualification.
//: 5 Sized array types are forwarded to the target with the original
//: array size.
//: 6 array-of-unknown-bound types are forwarded to the target as
//: pointer types.
//
// Plan:
//: 1 For concern 1, create a small set of functor classes with
//: several overloads of 'operator()'. Each overload verifies
//: correct invocation by returning a different enumerated
//: value. Call each functor via an intermediary function that
//: takes a 'TP' argument and passes it to a second intermediary
//: function taking a 'ForwardingType<TP>::Type' argument which, in
//: turn, calls the functor. Verify that the functor returns the
//: same value as would be returned if it were called directly.
//: 2 For concern 2, perform step 1 with a functor class whose
//: 'operator()' takes 'const', 'volatile', and 'const
//: volatile' lvalue reference types (C++03 and before) or
//: unqualified, 'const', 'volatile', and 'const volatile' rvalue
//: reference types (C++11 and newer). Instantiate with a variety
//: of primitive and non-primitive rvalue types of different
//: cv-qualifications.
//: 3 For concern 3, repeat step 2, except instantiate with lvalue
//: reference types.
//: 4 For concern 4, repeat step 2, except instantiate with rvalue
//: reference types.
//: 5 For concerns 5 and 6, perform step 1 with a functor class whose
//: 'operator()' returns the size of the array on which it is
//: called, or zero for pointer types. Instantiate with a variety
//: of array types and reference-to-array types.
//
// Testing:
// END-TO-END OVERLOADING
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING END-TO-END OVERLOADING"
"\n==============================\n");
int i = 5;
Enum e = e_VAL2;
Struct s(99);
Union u(98);
Class c(97);
double d = 1.23;
double *p = &d;
F *f_p = func;
Pm m_p = &Struct::d_data;
Pmf mf_p = &Class::value;
char a[5] = { '5', '4', '3', '2', '1' };
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
char (&au)[] = reinterpret_cast<AU&>(a);
#endif
// Volatile rvalue types are not useful and have strange rules. Do not test
// them. Attempting to test volatile rvalues will not only complicate the test
// driver unnecessarily, it may actually hide real errors.
#define TEST_ENDTOEND_RVALUE(TP, v) { \
typedef TP T; \
typedef bsl::add_const<T>::type CT; \
CvRefMatch<T> target; \
ASSERT(testEndToEnd<T>(v, target) == target(toRvalue<T>(v))); \
ASSERT(testEndToEnd<CT>(v, target) == target(toRvalue<CT>(v))); \
}
if (veryVerbose) printf("rvalue types\n");
TEST_ENDTOEND_RVALUE(int , i);
TEST_ENDTOEND_RVALUE(Enum , e);
#if !defined(BSLS_PLATFORM_CMP_MSVC) || BSLS_PLATFORM_CMP_VERSION > 0x1500
// Our test harness exposes an MSVC 2008 bug that treats the test code
// as ambiguous.
TEST_ENDTOEND_RVALUE(Struct , s);
TEST_ENDTOEND_RVALUE(Union , u);
TEST_ENDTOEND_RVALUE(Class , c);
#endif
TEST_ENDTOEND_RVALUE(double , d);
TEST_ENDTOEND_RVALUE(double * , p);
TEST_ENDTOEND_RVALUE(F * , f_p);
TEST_ENDTOEND_RVALUE(Pm , m_p);
TEST_ENDTOEND_RVALUE(Pmf , mf_p);
#undef TEST_ENDTOEND_RVALUE
#define TEST_ENDTOEND_LVALUE_REF(TP, v) { \
typedef TP T; \
typedef bsl::add_const<T>::type CT; \
typedef bsl::add_volatile<T>::type VT; \
typedef bsl::add_cv<T>::type CVT; \
CT& cv = v; \
VT& vv = v; \
CVT& cvv = v; \
CvRefMatch<T> target; \
ASSERT(testEndToEnd<T&>(v, target) == target(v)); \
ASSERT(testEndToEnd<CT&>(cv, target) == target(cv)); \
ASSERT(testEndToEnd<VT&>(vv, target) == target(vv)); \
ASSERT(testEndToEnd<CVT&>(cvv, target) == target(cvv)); \
}
if (veryVerbose) printf("lvalue reference types\n");
TEST_ENDTOEND_LVALUE_REF(int , i);
TEST_ENDTOEND_LVALUE_REF(Enum , e);
TEST_ENDTOEND_LVALUE_REF(Struct , s);
TEST_ENDTOEND_LVALUE_REF(Union , u);
TEST_ENDTOEND_LVALUE_REF(Class , c);
TEST_ENDTOEND_LVALUE_REF(double , d);
TEST_ENDTOEND_LVALUE_REF(double * , p);
TEST_ENDTOEND_LVALUE_REF(F * , f_p);
TEST_ENDTOEND_LVALUE_REF(Pm , m_p);
TEST_ENDTOEND_LVALUE_REF(Pmf , mf_p);
#undef TEST_ENDTOEND_LVALUE_REF
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
#define TEST_ENDTOEND_RVALUE_REF(TP, v) { \
typedef TP T; \
typedef bsl::add_const<T>::type CT; \
typedef bsl::add_volatile<T>::type VT; \
typedef bsl::add_cv<T>::type CVT; \
CvRefMatch<T> target; \
ASSERT(testEndToEnd<T&&>(native_std::move(v), target) == \
target(native_std::move(v))); \
ASSERT(testEndToEnd<CT&&>(static_cast<CT&&>(v), target) == \
target(static_cast<CT&&>(v))); \
ASSERT(testEndToEnd<VT&&>(static_cast<VT&&>(v), target) == \
target(static_cast<VT&&>(v))); \
ASSERT(testEndToEnd<CVT&&>(static_cast<CVT&&>(v), target) == \
target(static_cast<CVT&&>(v))); \
}
if (veryVerbose) printf("rvalue reference types\n");
TEST_ENDTOEND_RVALUE_REF(int , i);
TEST_ENDTOEND_RVALUE_REF(Enum , e);
TEST_ENDTOEND_RVALUE_REF(Struct , s);
TEST_ENDTOEND_RVALUE_REF(Union , u);
TEST_ENDTOEND_RVALUE_REF(Class , c);
TEST_ENDTOEND_RVALUE_REF(double , d);
TEST_ENDTOEND_RVALUE_REF(double * , p);
TEST_ENDTOEND_RVALUE_REF(F * , f_p);
TEST_ENDTOEND_RVALUE_REF(Pm , m_p);
TEST_ENDTOEND_RVALUE_REF(Pmf , mf_p);
#undef TEST_ENDTOEND_RVALUE_REF
#endif // defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
if (veryVerbose) printf("array types\n");
#if defined(BSLMF_FOWARDINGTYPE_WORK_AROUND_SUN_ARRAY_TESTS)
#define TEST_ENDTOEND_ARRAY(TP, a, exp) { \
CvArrayMatch<char> am; \
ASSERT(testEndToEndArray<TP>(a, am) == exp); \
CvArrayMatch<const char> acm; \
ASSERT(testEndToEndArray<bsl::add_const<TP>::type>(a, acm)== exp);\
CvArrayMatch<volatile char> avm; \
ASSERT(testEndToEndArray<bsl::add_volatile<TP>::type>(a, avm) \
== exp);\
CvArrayMatch<const volatile char> acvm; \
ASSERT(testEndToEndArray<bsl::add_cv<TP>::type>(a, acvm) == exp);\
}
#else
#define TEST_ENDTOEND_ARRAY(TP, a, exp) { \
CvArrayMatch<char> am; \
ASSERT(testEndToEnd<TP>(a, am) == exp); \
CvArrayMatch<const char> acm; \
ASSERT(testEndToEnd<bsl::add_const<TP>::type>(a, acm) == exp); \
CvArrayMatch<volatile char> avm; \
ASSERT(testEndToEnd<bsl::add_volatile<TP>::type>(a, avm) == exp);\
CvArrayMatch<const volatile char> acvm; \
ASSERT(testEndToEnd<bsl::add_cv<TP>::type>(a, acvm) == exp); \
}
#endif
TEST_ENDTOEND_ARRAY(char[5], a, 5);
TEST_ENDTOEND_ARRAY(char(&)[5], a, 5);
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
TEST_ENDTOEND_ARRAY(char[], au, 0);
TEST_ENDTOEND_ARRAY(char(&)[], au, 0);
#endif
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES) \
&&!defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_DECAY_TO_RVALUE_REF)
TEST_ENDTOEND_ARRAY(char *&&, au, 0);
#endif
if (veryVerbose) printf("function types\n");
FuncMatch<F> fm;
ASSERT(testEndToEnd<F*>(f_p, fm) == k_FUNC_POINTER);
ASSERT(testEndToEnd<F&>(func, fm) == k_FUNC_REFERENCE);
} break;
case 3: {
// --------------------------------------------------------------------
// TESTING 'bslmf::ForwardingTypeUtil'
//
// Concerns:
//: 1 For types that are not references, arrays, or functions,
//: 'ForwardingTypeUtil<TYPE>::TargetType' is similar to
//: 'TYPE' except that 'TargetType' might be a const reference
//: (C++03) or rvalue reference (C++11+). An object of 'TYPE'
//: converted to 'ForwardingType<TYPE>::Type' and then forwarded
//: using 'ForwardingTypeUtil<TYPE>::forwardToTarget(), will yield
//: a value equal to the original object.
//: 2 For array types of (known or unknown) size,
//: 'ForwardingTypeUtil<TYPE>::TargetType' yields a reference to
//: 'TYPE'. An array object of 'TYPE' converted to
//: 'ForwardingType<TYPE>::Type' then forwarded using
//: 'ForwardingTypeUtil<TYPE>::forwardToTarget() will yield a
//: reference to the original array.
//: 3 For reference types, 'ForwardingTypeUtil<TYPE>::TargetType'
//: yields 'TYPE'. A reference of 'TYPE' converted to
//: 'ForwardingType<TYPE>::Type' then forwarded using
//: 'ForwardingTypeUtil<TYPE>::forwardToTarget() will yield a
//: a reference identical to the original.
//: 4 All of the above concerns apply when 'TYPE' is
//: cv-qualified. Note that passing volatile-qualified objects by
//: value or by rvalue-reference does not really happen in real code
//: and is not supported by this component.
//: 5 For function types, 'ForwardingTypeUtil<TYPE>::TargetType'
//: yields 'TYPE&'. A function converted to
//: 'ForwardingType<TYPE>::Type' then forwarded using
//: 'ForwardingTypeUtil<TYPE>::forwardToTarget() will yield a a
//: reference to the original function.
//
// Plan:
//: 1 For concern 1, implement a function template,
//: 'testForwardToTargetVal' that can be instantiated with a 'TYPE'
//: and that takes an argument 'obj' of 'TYPE'. Instantiated on a
//: variety of basic and non-basic types, 'testForwardToTargetVal'
//: performs the following operations:
//: a Verify that 'TargetType' is the expected transformation of
//: 'TYPE'.
//: b Initialize a temporary variable of type
//: 'ForwardingType<TYPE>::Type' using 'obj.
//: c Call 'forwardToTarget' on the temporary variable and verify
//: that the resulting object compares equal to 'obj'.
//: 2 For concern 2, implement a function template,
// 'testForwardToTargetArray', that can be instantiated with an
//: an array 'TYPE' (or reference-to-array 'TYPE') and that takes
//: an argument 'obj' of 'TYPE'. Instantiated on a variety of array
//: types of known and unknown size as well a lvalue and rvalues to
//: such types, 'testForwardToTargetArray' performs the following
//: operations:
//: a Verify that 'TargetType' is the expected transformation of
//: 'TYPE'.
//: b Initialize a temporary variable of type
//: 'ForwardingType<TYPE>::Type' using 'obj.
//: c Call 'forwardToTarget' on the temporary variable and verify
//: that the resulting object has the same address as 'obj'.
//: 3 For concern 3, implement a function template,
//: 'testForwardToTargetRef' that can be instantiated with a
//: reference 'TYPE' and that takes an argument 'ref' of 'TYPE'.
//: Instantiated on a variety of lvalue and rvalue reference types,
//: 'testForwardToTargetRef', performs the following operations:
//: a Verify that 'TargetType' is the expected transformation of
//: 'TYPE'.
//: b Initialize a temporary variable of type
//: 'ForwardingType<TYPE>::Type' using 'obj'.
//: c Call 'forwardToTarget' on the temporary variable and verify
//: that the returned reference has the same address as 'obj'.
//: 4 For concern 4, instantiate the templates defined in the previous
//: steps using cv-qualified template parameters.
//: 5 For concern 5, instantiate the template with a function
//: type, 'F' and then:
//: a Verify that 'TargetType' is 'F&'.
//: b Initialize a temporary variable of type
//: 'ForwardingType<F>::Type' using 'func'.
//: c Call 'forwardToTarget' on the temporary variable and verify
//: that the returned reference has the same address as 'func'.
//
// Testing:
// ForwardingTypeUtil<TYPE>::TargetType
// ForwardingTypeUtil<TYPE>::forwardToTarget(v)
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING 'bslmf::ForwardingTypeUtil'"
"\n===================================\n");
Enum e = e_VAL2;
Struct s(99);
Union u(98);
Class c(97);
double d = 1.23;
double *p = &d;
char a[5] = { '5', '4', '3', '2', '1' };
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
char (&au)[] = reinterpret_cast<AU&>(a);
#endif
F *f_p = func;
Pm m_p = &Struct::d_data;
Pmf mf_p = &Class::value;
testForwardToTargetVal<Enum >(e);
testForwardToTargetVal<Struct >(s);
testForwardToTargetVal<Union >(u);
testForwardToTargetVal<Class >(c);
testForwardToTargetVal<double >(d);
testForwardToTargetVal<double *>(p);
testForwardToTargetVal<PF >(f_p);
testForwardToTargetVal<Pm >(m_p);
testForwardToTargetVal<Pmf >(mf_p);
testForwardToTargetVal<Enum const>(e);
testForwardToTargetVal<Struct const>(s);
testForwardToTargetVal<Union const>(u);
testForwardToTargetVal<Class const>(c);
testForwardToTargetVal<double const>(d);
testForwardToTargetVal<double *const>(p);
testForwardToTargetVal<PF const>(f_p);
testForwardToTargetVal<Pm const>(m_p);
testForwardToTargetVal<Pmf const>(mf_p);
// Do note test volatile rvalues of class types. They have no real use
// and require strange copy constructors and comparison operators to
// test correctly.
testForwardToTargetVal<Enum volatile>(e);
testForwardToTargetVal<double volatile>(d);
testForwardToTargetVal<double *volatile>(p);
testForwardToTargetVal<PF volatile>(f_p);
testForwardToTargetVal<Pm volatile>(m_p);
testForwardToTargetVal<Pmf volatile>(mf_p);
#if !defined(BSLMF_FOWARDINGTYPE_WORK_AROUND_SUN_ARRAY_TESTS)
testForwardToTargetVal<A volatile>(a);
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
testForwardToTargetVal<AU volatile>(au);
#endif
#endif // Disable testing arrays on broken compilers
testForwardToTargetArray<A >(a);
testForwardToTargetArray<A const >(a);
testForwardToTargetArray<A &>(a);
testForwardToTargetArray<A const &>(a);
testForwardToTargetArray<A volatile&>(a);
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
testForwardToTargetArray<AU >(au);
testForwardToTargetArray<AU const >(au);
testForwardToTargetArray<AU &>(au);
testForwardToTargetArray<AU const &>(au);
testForwardToTargetArray<AU volatile&>(au);
#endif
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES) \
&&!defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_DECAY_TO_RVALUE_REF)
testForwardToTargetArray<A &&>(native_std::move(a));
testForwardToTargetArray<A const &&>(native_std::move(a));
testForwardToTargetArray<AU &&>(native_std::move(au));
testForwardToTargetArray<AU const &&>(native_std::move(au));
#endif
testForwardToTargetRef<Enum &>(e);
testForwardToTargetRef<Struct &>(s);
testForwardToTargetRef<Union &>(u);
testForwardToTargetRef<Class &>(c);
testForwardToTargetRef<double &>(d);
testForwardToTargetRef<double *&>(p);
testForwardToTargetRef<F &>(func);
testForwardToTargetRef<Fi &>(funcI);
testForwardToTargetRef<FRi &>(funcRi);
testForwardToTargetRef<PF &>(f_p);
testForwardToTargetRef<Pm &>(m_p);
testForwardToTargetRef<Pmf &>(mf_p);
testForwardToTargetRef<Enum const&>(e);
testForwardToTargetRef<Struct const&>(s);
testForwardToTargetRef<Union const&>(u);
testForwardToTargetRef<Class const&>(c);
testForwardToTargetRef<double const&>(d);
testForwardToTargetRef<double *const&>(p);
testForwardToTargetRef<PF const&>(f_p);
testForwardToTargetRef<Pm const&>(m_p);
testForwardToTargetRef<Pmf const&>(mf_p);
testForwardToTargetRef<Enum volatile&>(e);
testForwardToTargetRef<Struct volatile&>(s);
testForwardToTargetRef<Union volatile&>(u);
testForwardToTargetRef<Class volatile&>(c);
testForwardToTargetRef<double volatile&>(d);
testForwardToTargetRef<double *volatile&>(p);
testForwardToTargetRef<PF volatile&>(f_p);
testForwardToTargetRef<Pm volatile&>(m_p);
testForwardToTargetRef<Pmf volatile&>(mf_p);
testForwardToTargetRef<Enum const volatile&>(e);
testForwardToTargetRef<Struct const volatile&>(s);
testForwardToTargetRef<Union const volatile&>(u);
testForwardToTargetRef<Class const volatile&>(c);
testForwardToTargetRef<double const volatile&>(d);
testForwardToTargetRef<double *const volatile&>(p);
testForwardToTargetRef<PF const volatile&>(f_p);
testForwardToTargetRef<Pm const volatile&>(m_p);
testForwardToTargetRef<Pmf const volatile&>(mf_p);
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
testForwardToTargetRef<Struct &&>(native_std::move(s));
testForwardToTargetRef<Union &&>(native_std::move(u));
testForwardToTargetRef<Class &&>(native_std::move(c));
#if !defined(BSLS_PLATFORM_CMP_MSVC) || BSLS_PLATFORM_CMP_VERSION > 0x1800
// The following 6 tests fail for MS Visual C++ (tested up to VC 2013).
// Suspect the optimizer is creating a temporary, rather than truly
// passing by reference, when given a fundamental/primitive type.
testForwardToTargetRef<Enum &&>(native_std::move(e));
testForwardToTargetRef<double &&>(native_std::move(d));
testForwardToTargetRef<double *&&>(native_std::move(p));
testForwardToTargetRef<PF &&>(native_std::move(f_p));
testForwardToTargetRef<Pm &&>(native_std::move(m_p));
testForwardToTargetRef<Pmf &&>(native_std::move(mf_p));
#endif
testForwardToTargetRef<Enum const&&>(native_std::move(e));
testForwardToTargetRef<Struct const&&>(native_std::move(s));
testForwardToTargetRef<Union const&&>(native_std::move(u));
testForwardToTargetRef<Class const&&>(native_std::move(c));
testForwardToTargetRef<double const&&>(native_std::move(d));
testForwardToTargetRef<double * const&&>(native_std::move(p));
testForwardToTargetRef<PF const&&>(native_std::move(f_p));
testForwardToTargetRef<Pm const&&>(native_std::move(m_p));
testForwardToTargetRef<Pmf const&&>(native_std::move(mf_p));
// Do not test volatile rvalue references. They have no real uses and
// would require distortions in the test that could result in missing
// actual errors.
#endif
// Test function type
{
typedef bslmf::ForwardingType<F>::Type FwdType;
typedef bslmf::ForwardingTypeUtil<F>::TargetType TargetType;
ASSERT_SAME(F&, TargetType);
FwdType fwdRef = func;
ASSERT(&func ==
bslmf::ForwardingTypeUtil<F>::forwardToTarget(fwdRef));
}
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING 'bslmf::ForwardingType<TYPE>::Type'
//
// Concerns:
//: 1 The forwarding type for "*basic* type cvq 'TP'" is the same as
//: 'TP' with the cv-qualification removed.
//: 2 The forwarding type for "*class* *or* *union* type cvq 'TP'" is
//: 'const vq TP&', where 'vq' is 'volatile' if 'TP' is
//: volatile-qualified and is empty otherwise.
//: 3 The forwarding type for "function of type 'F'" or "reference to
//: function of type 'F'" is "reference to function of type
//: 'F'". The forwarding type for "pointer to function of type 'F'"
//: is the same pointer type, 'F*'.
//: 4 The forwarding type for "array of cvq 'TP'" or "(lvalue or
//: rvalue) reference to array of cvq 'TP'" is "cvq 'TP*'",
//: regardless of whether the array size is known.
//: 5 The forwarding type for "lvalue reference to type cvq 'TP'" is
//: the same "lvalue reference to cvq 'TP', for non-function and
//: non-array types.
//: 6 (C++11 and newer only) The forwarding type for "rvalue reference
//: to cvq type 'TP'" for non-function and non-array 'TP' is 'const
//: vq TP&', where 'vq' is 'volatile' if 'TP' is volatile-qualified
//: and 'vq' is empty otherwise.
//
// Test Plan:
//: 1 For concern 1, instantiate 'ForwardingType' for fundamental,
//: pointer, and enumeration types, both cv-qualified and
//: unqualified, and verify that the resulting 'Type' member is
//: the parameter type without cv qualification.
//: 2 For concern 2, instantiate 'ForwardingType' for class and union
//: type, both unqualified and cv-qualified, and verify that the
//: resulting 'Type' member is the expected const lvalue reference
//: type.
//: 3 For concern 3, instantiate 'ForwardingType' for a small number
//: of function, reference-to-function, and pointer-to-function
//: parameters and verify that the resulting 'Type' member is the
//: expected type.
//: 3 For concern 4, instantiate 'ForwardingType' for a small number of
//: array types, lvalue-reference-to-array types, and
//: rvalue-reference-to-array types, both sized and unsized, and
//: both cv-qualified and unqualified, and verify that the resulting
//: 'Type' member is the expected pointer type.
//: 5 For concern 5, instantiate 'ForwardingType' for *lvalue*
//: reference to fundamental, pointer, enumeration, class, and union
//: types, both cv-qualified and unqualified, and verify that the
//: resulting 'Type' member is the same as the parameter type.
//: 6 For concern 6, instantiate 'ForwardingType' for *rvalue*
//: reference to fundamental, pointer, enumeration, class, and union
//: types, both cv-qualified and unqualified, and verify that the
//: resulting 'Type' member is the expected const lvalue reference
//: type.
//
// Testing:
// ForwardingType<TYPE>::Type
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING 'bslmf::ForwardingType<TYPE>::Type'"
"\n===========================================\n");
#define TEST_FWD_TYPE(T, EXP) ASSERT_SAME(bslmf::ForwardingType<T>::Type, EXP)
#define TEST_FWD_TYPE_UNCHANGED(T) TEST_FWD_TYPE(T, T)
if (veryVerbose) printf("Basic types\n");
TEST_FWD_TYPE(int , int);
TEST_FWD_TYPE(int * , int *);
TEST_FWD_TYPE(int Class::* , int Class::*);
TEST_FWD_TYPE(int (*)(float) , int (*)(float));
TEST_FWD_TYPE(int (Class::*)(char) , int (Class::*)(char));
TEST_FWD_TYPE(Enum , Enum);
TEST_FWD_TYPE(const int , int);
TEST_FWD_TYPE(int *const , int *);
TEST_FWD_TYPE(const int * , const int *);
TEST_FWD_TYPE(int Class::* const , int Class::*);
TEST_FWD_TYPE(int (* const)(float) , int (*)(float));
TEST_FWD_TYPE(int (Class::* const)(char) , int (Class::*)(char));
TEST_FWD_TYPE(const Enum , Enum);
TEST_FWD_TYPE(volatile int , int);
TEST_FWD_TYPE(int *volatile , int *);
TEST_FWD_TYPE(volatile int * , volatile int *);
TEST_FWD_TYPE(int Class::* volatile , int Class::*);
TEST_FWD_TYPE(int (* volatile)(float) , int (*)(float));
TEST_FWD_TYPE(volatile Enum , Enum);
TEST_FWD_TYPE(const volatile int , int);
TEST_FWD_TYPE(int *const volatile , int *);
TEST_FWD_TYPE(const volatile int * , const volatile int *);
TEST_FWD_TYPE(int Class::* const volatile, int Class::*);
TEST_FWD_TYPE(const volatile Enum , Enum);
if (veryVerbose) printf("Class and union types\n");
TEST_FWD_TYPE(Class , const Class&);
TEST_FWD_TYPE(Struct , const Struct&);
TEST_FWD_TYPE(Union , const Union&);
TEST_FWD_TYPE(const Class , const Class&);
TEST_FWD_TYPE(const Struct , const Struct&);
TEST_FWD_TYPE(const Union , const Union&);
TEST_FWD_TYPE(volatile Class , const volatile Class&);
TEST_FWD_TYPE(volatile Struct , const volatile Struct&);
TEST_FWD_TYPE(volatile Union , const volatile Union&);
TEST_FWD_TYPE(const volatile Class , const volatile Class&);
TEST_FWD_TYPE(const volatile Struct , const volatile Struct&);
TEST_FWD_TYPE(const volatile Union , const volatile Union&);
if (veryVerbose) printf("Function types\n");
#if (!defined(BSLS_PLATFORM_CMP_MSVC) || (BSLS_PLATFORM_CMP_VERSION < 0x1700))\
|| (!defined(BSLS_PLATFORM_CMP_IBM) || (BSLS_PLATFORM_CMP_VERSION < 0x0800))
// xlc-8 seems to have problems with function types. Similarly, older
// MS Visual C++ compilers have problem binding functions types to
// function references, rather than decaying to function pointers.
TEST_FWD_TYPE(void() , void(&)());
TEST_FWD_TYPE(int(int) , int(&)(int));
TEST_FWD_TYPE(void(int&) , void(&)(int&));
#endif
TEST_FWD_TYPE(void(&)() , void(&)());
TEST_FWD_TYPE(int(&)(int) , int(&)(int));
TEST_FWD_TYPE(void(&)(int&) , void(&)(int&));
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
TEST_FWD_TYPE(void(&&)() , void(&)());
TEST_FWD_TYPE(int(&&)(int) , int(&)(int));
TEST_FWD_TYPE(void(&&)(int&), void(&)(int&));
#endif
TEST_FWD_TYPE(void(*)() , void(*)());
TEST_FWD_TYPE(int(*)(int) , int(*)(int));
TEST_FWD_TYPE(void(*)(int&) , void(*)(int&));
if (veryVerbose) printf("Array types\n");
TEST_FWD_TYPE(int[5] , int* );
TEST_FWD_TYPE(int*[5] , int** );
TEST_FWD_TYPE(int[5][6] , int(*)[6] );
TEST_FWD_TYPE(int(&)[5] , int* );
TEST_FWD_TYPE(int *const(&)[5] , int *const * );
TEST_FWD_TYPE(int(&)[5][6] , int(*)[6] );
TEST_FWD_TYPE(int *const[5] , int *const * );
TEST_FWD_TYPE(const int[5][6] , const int(*)[6] );
TEST_FWD_TYPE(const int(&)[5] , const int* );
TEST_FWD_TYPE(volatile int[5] , volatile int* );
TEST_FWD_TYPE(volatile int[5][6] , volatile int(*)[6] );
TEST_FWD_TYPE(volatile int(&)[5] , volatile int* );
TEST_FWD_TYPE(const volatile int[5] , const volatile int* );
TEST_FWD_TYPE(const volatile int[5][6] , const volatile int(*)[6]);
TEST_FWD_TYPE(const volatile int(&)[5] , const volatile int* );
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
TEST_FWD_TYPE(Class[] , Class* );
TEST_FWD_TYPE(Struct[][6] , Struct(*)[6] );
TEST_FWD_TYPE(Class(&)[] , Class* );
TEST_FWD_TYPE(Struct(&)[][6] , Struct(*)[6] );
TEST_FWD_TYPE(const int[] , const int* );
TEST_FWD_TYPE(const int[][6] , const int(*)[6] );
TEST_FWD_TYPE(volatile int[] , volatile int* );
TEST_FWD_TYPE(volatile int[][6] , volatile int(*)[6] );
TEST_FWD_TYPE(const volatile int[] , const volatile int* );
TEST_FWD_TYPE(const volatile int[][6] , const volatile int(*)[6]);
#endif
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
TEST_FWD_TYPE(int *const(&&)[5] , int *const * );
TEST_FWD_TYPE(int(&&)[5] , int* );
TEST_FWD_TYPE(int(&&)[5][6] , int(*)[6] );
# if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
TEST_FWD_TYPE(Class(&&)[] , Class* );
TEST_FWD_TYPE(Struct(&&)[][6] , Struct(*)[6] );
# endif
TEST_FWD_TYPE(const int(&&)[5] , const int* );
TEST_FWD_TYPE(volatile int(&&)[5] , volatile int* );
TEST_FWD_TYPE(const volatile int(&&)[5], const volatile int* );
#endif
if (veryVerbose) printf("Lvalue references\n");
TEST_FWD_TYPE_UNCHANGED(int& );
TEST_FWD_TYPE_UNCHANGED(int *& );
TEST_FWD_TYPE_UNCHANGED(int Class::*& );
TEST_FWD_TYPE_UNCHANGED(int (*&)(float) );
TEST_FWD_TYPE_UNCHANGED(int (Class::*&)(char) );
TEST_FWD_TYPE_UNCHANGED(Enum& );
TEST_FWD_TYPE_UNCHANGED(Class& );
TEST_FWD_TYPE_UNCHANGED(Struct& );
TEST_FWD_TYPE_UNCHANGED(Union& );
TEST_FWD_TYPE_UNCHANGED(const int& );
TEST_FWD_TYPE_UNCHANGED(int *const& );
TEST_FWD_TYPE_UNCHANGED(const int *& );
TEST_FWD_TYPE_UNCHANGED(int Class::* const& );
TEST_FWD_TYPE_UNCHANGED(int (* const&)(float) );
TEST_FWD_TYPE_UNCHANGED(int (Class::* const&)(char) );
TEST_FWD_TYPE_UNCHANGED(const Enum& );
TEST_FWD_TYPE_UNCHANGED(const Class& );
TEST_FWD_TYPE_UNCHANGED(const Struct& );
TEST_FWD_TYPE_UNCHANGED(const Union& );
TEST_FWD_TYPE_UNCHANGED(volatile int& );
TEST_FWD_TYPE_UNCHANGED(int *volatile& );
TEST_FWD_TYPE_UNCHANGED(volatile int *& );
TEST_FWD_TYPE_UNCHANGED(int Class::* volatile& );
TEST_FWD_TYPE_UNCHANGED(int (* volatile&)(float) );
TEST_FWD_TYPE_UNCHANGED(volatile Enum& );
TEST_FWD_TYPE_UNCHANGED(volatile Class& );
TEST_FWD_TYPE_UNCHANGED(volatile Struct& );
TEST_FWD_TYPE_UNCHANGED(volatile Union& );
TEST_FWD_TYPE_UNCHANGED(const volatile int& );
TEST_FWD_TYPE_UNCHANGED(int *const volatile& );
TEST_FWD_TYPE_UNCHANGED(const volatile int *& );
TEST_FWD_TYPE_UNCHANGED(int Class::* const volatile&);
TEST_FWD_TYPE_UNCHANGED(const volatile Enum& );
TEST_FWD_TYPE_UNCHANGED(const volatile Class& );
TEST_FWD_TYPE_UNCHANGED(const volatile Struct& );
TEST_FWD_TYPE_UNCHANGED(const volatile Union& );
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
if (veryVerbose) printf("Rvalue references\n");
TEST_FWD_TYPE(int&& , const int&);
TEST_FWD_TYPE(int *&& , int *const &);
TEST_FWD_TYPE(const int *&& , const int *const &);
TEST_FWD_TYPE(volatile int *&& , volatile int *const &);
TEST_FWD_TYPE(const volatile int *&& , const volatile int *const &);
TEST_FWD_TYPE(int Class::*&& , int Class::* const&);
TEST_FWD_TYPE(int (*&&)(float) , int (*const &)(float));
TEST_FWD_TYPE(int (Class::*&&)(char) , int (Class::*const &)(char));
TEST_FWD_TYPE(Enum&& , const Enum&);
TEST_FWD_TYPE(Class&& , const Class&);
TEST_FWD_TYPE(Struct&& , const Struct&);
TEST_FWD_TYPE(Union&& , const Union&);
TEST_FWD_TYPE(const int&& , const int&);
TEST_FWD_TYPE(int *const&& , int *const &);
TEST_FWD_TYPE(const int *const && , const int *const &);
TEST_FWD_TYPE(int Class::* const&& , int Class::* const &);
TEST_FWD_TYPE(int (* const&&)(float) , int (* const&)(float));
TEST_FWD_TYPE(int (Class::* const&&)(char)
, int (Class::* const&)(char));
TEST_FWD_TYPE(const Enum&& , const Enum&);
TEST_FWD_TYPE(const Class&& , const Class&);
TEST_FWD_TYPE(const Struct&& , const Struct&);
TEST_FWD_TYPE(const Union&& , const Union&);
TEST_FWD_TYPE(volatile int&& , const volatile int&);
TEST_FWD_TYPE(int *volatile&& , int *const volatile&);
TEST_FWD_TYPE(int Class::* volatile&&, int Class::* const volatile&);
TEST_FWD_TYPE(int (* volatile&&)(float)
, int (* const volatile&)(float));
TEST_FWD_TYPE(volatile Enum&& , const volatile Enum&);
TEST_FWD_TYPE(volatile Class&& , const volatile Class&);
TEST_FWD_TYPE(volatile Struct&& , const volatile Struct&);
TEST_FWD_TYPE(volatile Union&& , const volatile Union&);
TEST_FWD_TYPE(const volatile int&& , const volatile int&);
TEST_FWD_TYPE(int *const volatile&& , int *const volatile&);
TEST_FWD_TYPE(int Class::* const volatile&&
, int Class::* const volatile&);
TEST_FWD_TYPE(const volatile Enum&& , const volatile Enum&);
TEST_FWD_TYPE(const volatile Class&& , const volatile Class&);
TEST_FWD_TYPE(const volatile Struct&&, const volatile Struct&);
TEST_FWD_TYPE(const volatile Union&& , const volatile Union&);
#endif // defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
} break;
case 1: {
// --------------------------------------------------------------------
// TESTING TEST INFRASTRUCTURE
//
// Concerns:
//: 1 For 'crm' of type 'CvRefMatch<T>', 'crm(v)' returns the correct
//: enumerator indicating whether 'v' is an lvalue, const lvalue,
//: volatile lvalue, const volatile lvalue, rvalue, const rvalue,
//: volatile rvalue, or const volatile rvalue.
//: 2 For 'cam' of type 'CvArrayMatch<T>' and 'a' of type array-of-T,
//: 'cam(a)' returns the number of elements of 'a' or '0' if 'a' has
//: unknown bounds.
//: 3 For 'cam' of type 'CvArrayMatch<T>' and 'p' of type
//: pointer-to-T, 'cam(p)' returns 0.
//: 4 Concerns 2 and 3 apply regardless of the cv qualification of 'a'
//: or 'p'.
//: 5 For 'cam' of type 'CvArrayMatch<T>' and 'a' of type
//: rvalue-reference-to-array-of-T, 'CvArrayMatch<T>' returns the
//: same value as if 'a' were not an rvalue reference.
//: 6 For 'fm' of type 'FuncMatch<F>', 'fm(f)' returns
//: 'k_FUNC_REFERENCE' if 'f' is of type 'F' or 'F&' and
//: 'k_FUNC_POINTER' if 'f' is of type 'F*'.
//
// Plan:
//: 1 For concern 1, create a variable, 'crm' of type
//: 'CvRefMatch<int>'. Call 'crm(v)' for variables 'v' of type cvq
//: 'int' correct lvalue enumeration value is returned. In C++11 or
//: later mode, test with 'std::move(v)' and verify that the correct
//: lvalue enumeration is returned. Also test with a literal integer
//: and verify that the return value is 'k_RVALUE_REF' in C++11 mode
//: or 'k_CONST_LVALUE_REF' in C++03 mode.
//: 2 For concerns 2 and 3, create a variable, 'cam' of type
//: 'CvArrayMatch<int>'. Define variables of type array-of-int,
//: with both known and unknown sizes. Verify that 'cam(v)' returns
//: the correct size (or 0) for each array variable, 'v'.
//: 3 For concern 4, repeat step 2 for variables of each cvq
//: combination.
//: 4 For concern 5 (C++11 or later), repeat steps 2 and 3 using
//: 'cam(std::move(v))'.
//: 6 For concern 6, create a variable, 'fm', of type
//: 'FuncMatch<F>'. Call 'fm(f)' for arguments 'f' of type 'void()',
//: 'void(&)()', and 'void(*)()', and verify that the correct
//: enumeration value is returned.
//
// Testing:
// CvRefMatch<T>::operator()()
// CvArrayMatch<T>::operator()()
// FuncMatch<F>::operator()()
// --------------------------------------------------------------------
if (verbose) printf("\nTESTING TEST INFRASTRUCTURE"
"\n===========================\n");
if (veryVerbose) printf("CvRefMatch\n");
int i = 0;
const int ci = 1;
volatile int vi = 2;
const volatile int cvi = 3;
volatile int &rvi = vi;
CvRefMatch<int> crm;
ASSERT(k_LVALUE == crm( i));
ASSERT(k_CONST_LVALUE == crm( ci));
ASSERT(k_VOLATILE_LVALUE == crm( vi));
ASSERT(k_CONST_VOLATILE_LVALUE == crm(cvi));
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
ASSERT(k_RVALUE == crm(native_std::move( i)));
ASSERT(k_CONST_RVALUE == crm(native_std::move( ci)));
ASSERT(k_VOLATILE_RVALUE == crm(native_std::move( vi)));
ASSERT(k_CONST_VOLATILE_RVALUE == crm(native_std::move(cvi)));
#endif
#if defined(BSLS_COMPILERFEATURES_SUPPORT_RVALUE_REFERENCES)
ASSERT(k_RVALUE == crm(5));
ASSERT(k_RVALUE == crm(toRvalue(rvi)));
#else
ASSERT(k_CONST_LVALUE == crm(5));
ASSERT(k_CONST_LVALUE == crm(toRvalue(rvi)));
#endif
if (veryVerbose) printf("CvArrayMatch\n");
int a[1] = { 1 };
const int ca[2] = { 1, 2 };
volatile int va[3] = { 1, 2, 3 };
const volatile int cva[4] = { 1, 2, 3, 4};
int (*pa)[] = reinterpret_cast<int (*)[]>(a);
const int (*cpa)[] = pa;
volatile int (*vpa)[] = pa;
const volatile int (*cvpa)[] = pa;
int *p;
const int *cp;
volatile int *vp;
const volatile int *cvp;
CvArrayMatch<int> cam;
CvArrayMatch<const int> camc;
CvArrayMatch<volatile int> camv;
CvArrayMatch<const volatile int> camcv;
ASSERT(1 == cam ( a));
ASSERT(2 == camc ( ca));
ASSERT(3 == camv ( va));
ASSERT(4 == camcv(cva));
#if !defined(BSLMF_FORWARDINGTYPE_NO_ARRAY_OF_UNKNOWN_BOUND)
ASSERT(0 == cam (* pa));
ASSERT(0 == camc (* cpa));
ASSERT(0 == camv (* vpa));
ASSERT(0 == camcv(*cvpa));
#endif
ASSERT(0 == cam ( p));
ASSERT(0 == camc ( cp));
ASSERT(0 == camv ( vp));
ASSERT(0 == camcv(cvp));
if (veryVerbose) printf("FuncMatch\n");
FuncMatch<F> fm;
F& func_r = func;
F* func_p = func;
ASSERT(k_FUNC_REFERENCE == fm(func));
ASSERT(k_FUNC_REFERENCE == fm(func_r));
ASSERT(k_FUNC_POINTER == fm(&func));
ASSERT(k_FUNC_POINTER == fm(func_p));
} break;
default: {
fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test);
testStatus = -1;
}
}
if (testStatus > 0) {
fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus);
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| apache-2.0 |
andreagenso/java2scala | test/J2s/java/openjdk-6-src-b27/jdk/src/share/native/java/lang/fdlibm/src/w_gamma_r.c | 4 | 1952 |
/*
* Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* wrapper double gamma_r(double x, int *signgamp)
*/
#include "fdlibm.h"
#ifdef __STDC__
double gamma_r(double x, int *signgamp) /* wrapper lgamma_r */
#else
double gamma_r(x,signgamp) /* wrapper lgamma_r */
double x; int *signgamp;
#endif
{
#ifdef _IEEE_LIBM
return __ieee754_gamma_r(x,signgamp);
#else
double y;
y = __ieee754_gamma_r(x,signgamp);
if(_LIB_VERSION == _IEEE_) return y;
if(!finite(y)&&finite(x)) {
if(floor(x)==x&&x<=0.0)
return __kernel_standard(x,x,41); /* gamma pole */
else
return __kernel_standard(x,x,40); /* gamma overflow */
} else
return y;
#endif
}
| apache-2.0 |
google/google-ctf | third_party/edk2/Vlv2TbltDevicePkg/Feature/Capsule/SystemFirmwareDescriptor/SystemFirmwareDescriptorPei.c | 6 | 2142 | /** @file
System Firmware descriptor producer.
Copyright (c) 2016, Intel Corporation. All rights reserved.<BR>
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 <PiPei.h>
#include <Library/PcdLib.h>
#include <Library/PeiServicesLib.h>
#include <Library/DebugLib.h>
#include <Protocol/FirmwareManagement.h>
#include <Guid/EdkiiSystemFmpCapsule.h>
/**
Entrypoint for SystemFirmwareDescriptor PEIM.
@param[in] FileHandle Handle of the file being invoked.
@param[in] PeiServices Describes the list of possible PEI Services.
@retval EFI_SUCCESS PPI successfully installed.
**/
EFI_STATUS
EFIAPI
SystemFirmwareDescriptorPeimEntry (
IN EFI_PEI_FILE_HANDLE FileHandle,
IN CONST EFI_PEI_SERVICES **PeiServices
)
{
EFI_STATUS Status;
EDKII_SYSTEM_FIRMWARE_IMAGE_DESCRIPTOR *Descriptor;
UINTN Size;
UINTN Index;
UINT32 AuthenticationStatus;
//
// Search RAW section.
//
Index = 0;
while (TRUE) {
Status = PeiServicesFfsFindSectionData3(EFI_SECTION_RAW, Index, FileHandle, (VOID **)&Descriptor, &AuthenticationStatus);
if (EFI_ERROR(Status)) {
// Should not happen, must something wrong in FDF.
ASSERT(FALSE);
return EFI_NOT_FOUND;
}
if (Descriptor->Signature == EDKII_SYSTEM_FIRMWARE_IMAGE_DESCRIPTOR_SIGNATURE) {
break;
}
Index++;
}
DEBUG((DEBUG_INFO, "EDKII_SYSTEM_FIRMWARE_IMAGE_DESCRIPTOR size - 0x%x\n", Descriptor->Length));
Size = Descriptor->Length;
PcdSetPtrS (PcdEdkiiSystemFirmwareImageDescriptor, &Size, Descriptor);
return EFI_SUCCESS;
}
| apache-2.0 |
osubboo/bde | groups/btl/btlmt/btlmt_channelstatus.cpp | 6 | 2441 | // btlmt_channelstatus.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <btlmt_channelstatus.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(btlmt_channelstatus_cpp,"$Id$ $CSID$")
#include <bdlb_print.h>
#include <bsl_ostream.h>
namespace BloombergLP {
namespace btlmt {
// --------------------
// struct ChannelStatus
// --------------------
// CLASS METHODS
bsl::ostream& ChannelStatus::print(bsl::ostream& stream,
ChannelStatus::Enum value,
int level,
int spacesPerLevel)
{
bdlb::Print::indent(stream, level, spacesPerLevel);
stream << ChannelStatus::toAscii(value);
if (spacesPerLevel >= 0) {
stream << '\n';
}
return stream;
}
const char *ChannelStatus::toAscii(ChannelStatus::Enum value)
{
#define CASE(X) case(e_ ## X): return #X;
switch (value) {
CASE(SUCCESS)
CASE(CACHE_OVERFLOW)
CASE(CACHE_HIGHWATER)
CASE(READ_CHANNEL_DOWN)
CASE(WRITE_CHANNEL_DOWN)
CASE(ENQUEUE_HIGHWATER)
CASE(UNKNOWN_ID)
default: return "(* UNKNOWN *)";
}
#undef CASE
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| apache-2.0 |
jaracil/esp-idf | components/wpa_supplicant/src/fast_crypto/fast_aes-wrap.c | 8 | 2304 | // 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
//
// Hardware crypto support Copyright 2017 Espressif Systems (Shanghai) PTE LTD
//
// 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 "crypto/includes.h"
#include "crypto/common.h"
#include "crypto/aes.h"
#include "crypto/aes_wrap.h"
#include "mbedtls/aes.h"
/**
* fast_aes_wrap - Wrap keys with AES Key Wrap Algorithm (128-bit KEK) (RFC3394)
* @kek: 16-octet Key encryption key (KEK)
* @n: Length of the plaintext key in 64-bit units; e.g., 2 = 128-bit = 16
* bytes
* @plain: Plaintext key to be wrapped, n * 64 bits
* @cipher: Wrapped key, (n + 1) * 64 bits
* Returns: 0 on success, -1 on failure
*/
int fast_aes_wrap(const uint8_t *kek, int n, const uint8_t *plain, uint8_t *cipher)
{
uint8_t *a, *r, b[16];
int32_t i, j;
int32_t ret = 0;
mbedtls_aes_context ctx;
a = cipher;
r = cipher + 8;
/* 1) Initialize variables. */
os_memset(a, 0xa6, 8);
os_memcpy(r, plain, 8 * n);
mbedtls_aes_init(&ctx);
ret = mbedtls_aes_setkey_enc(&ctx, kek, 128);
if (ret < 0) {
mbedtls_aes_free(&ctx);
return ret;
}
/* 2) Calculate intermediate values.
* For j = 0 to 5
* For i=1 to n
* B = AES(K, A | R[i])
* A = MSB(64, B) ^ t where t = (n*j)+i
* R[i] = LSB(64, B)
*/
for (j = 0; j <= 5; j++) {
r = cipher + 8;
for (i = 1; i <= n; i++) {
os_memcpy(b, a, 8);
os_memcpy(b + 8, r, 8);
mbedtls_aes_encrypt(&ctx, b, b);
os_memcpy(a, b, 8);
a[7] ^= n * j + i;
os_memcpy(r, b + 8, 8);
r += 8;
}
}
mbedtls_aes_free(&ctx);
/* 3) Output the results.
*
* These are already in @cipher due to the location of temporary
* variables.
*/
return 0;
}
| apache-2.0 |
jeongchanKim/TizenRT | os/arch/arm/src/armv7-m/up_releasepending.c | 8 | 5661 | /****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/****************************************************************************
* arch/arm/src/armv7-m/up_releasepending.c
*
* Copyright (C) 2007-2009, 2012 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* 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 <tinyara/config.h>
#include <sched.h>
#include <debug.h>
#include <tinyara/arch.h>
#include "sched/sched.h"
#include "up_internal.h"
#ifdef CONFIG_TASK_SCHED_HISTORY
#include <tinyara/debug/sysdbg.h>
#endif
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_release_pending
*
* Description:
* Release and ready-to-run tasks that have
* collected in the pending task list. This can call a
* context switch if a new task is placed at the head of
* the ready to run list.
*
****************************************************************************/
void up_release_pending(void)
{
struct tcb_s *rtcb = this_task();
sllvdbg("From TCB=%p\n", rtcb);
/* Merge the g_pendingtasks list into the g_readytorun task list */
/* sched_lock(); */
if (sched_mergepending()) {
/* The currently active task has changed! We will need to switch
* contexts. First check if we are operating in interrupt context.
*/
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();
sllvdbg("New Active Task TCB=%p\n", rtcb);
/* Restore rtcb data for context switching */
up_restoretask(rtcb);
/* 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.
*/
}
}
}
| apache-2.0 |
llvm-mirror/libcxx | test/libcxx/extensions/hash/specializations.pass.cpp | 9 | 1268 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// NOTE: Undefined __DEPRECATED to prevent this test from failing with -Werror
#undef __DEPRECATED
#include <assert.h>
#include <ext/hash_map>
#include <string>
#include "test_macros.h"
int main(int, char**)
{
char str[] = "test";
assert(__gnu_cxx::hash<const char *>()("test") ==
std::hash<std::string>()("test"));
assert(__gnu_cxx::hash<char *>()(str) == std::hash<std::string>()("test"));
assert(__gnu_cxx::hash<char>()(42) == 42);
assert(__gnu_cxx::hash<signed char>()(42) == 42);
assert(__gnu_cxx::hash<unsigned char>()(42) == 42);
assert(__gnu_cxx::hash<short>()(42) == 42);
assert(__gnu_cxx::hash<unsigned short>()(42) == 42);
assert(__gnu_cxx::hash<int>()(42) == 42);
assert(__gnu_cxx::hash<unsigned int>()(42) == 42);
assert(__gnu_cxx::hash<long>()(42) == 42);
assert(__gnu_cxx::hash<unsigned long>()(42) == 42);
return 0;
}
| apache-2.0 |
atrick/swift | lib/AST/Parameter.cpp | 9 | 4156 | //===--- Parameter.cpp - Functions & closures parameters ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the Parameter class, the ParameterList class and support
// logic.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ParameterList.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Types.h"
using namespace swift;
/// TODO: unique and reuse the () parameter list in ASTContext, it is common to
/// many methods. Other parameter lists cannot be uniqued because the decls
/// within them are always different anyway (they have different DeclContext's).
ParameterList *
ParameterList::create(const ASTContext &C, SourceLoc LParenLoc,
ArrayRef<ParamDecl*> params, SourceLoc RParenLoc) {
assert(LParenLoc.isValid() == RParenLoc.isValid() &&
"Either both paren locs are valid or neither are");
auto byteSize = totalSizeToAlloc<ParamDecl *>(params.size());
auto rawMem = C.Allocate(byteSize, alignof(ParameterList));
// Placement initialize the ParameterList and the Parameter's.
auto PL = ::new (rawMem) ParameterList(LParenLoc, params.size(), RParenLoc);
std::uninitialized_copy(params.begin(), params.end(), PL->getArray().begin());
return PL;
}
/// Change the DeclContext of any contained parameters to the specified
/// DeclContext.
void ParameterList::setDeclContextOfParamDecls(DeclContext *DC) {
for (auto P : *this)
P->setDeclContext(DC);
}
/// Make a duplicate copy of this parameter list. This allocates copies of
/// the ParamDecls, so they can be reparented into a new DeclContext.
ParameterList *ParameterList::clone(const ASTContext &C,
OptionSet<CloneFlags> options) const {
// TODO(distributed): copy types thanks to flag in options
// If this list is empty, don't actually bother with a copy.
if (size() == 0)
return const_cast<ParameterList*>(this);
SmallVector<ParamDecl*, 8> params(begin(), end());
// Remap the ParamDecls inside of the ParameterList.
for (auto &decl : params) {
auto defaultArgKind = decl->getDefaultArgumentKind();
decl = ParamDecl::cloneWithoutType(C, decl);
if (options & Implicit)
decl->setImplicit();
// If the argument isn't named, give the parameter a name so that
// silgen will produce a value for it.
if (decl->getName().empty() && (options & NamedArguments))
decl->setName(C.getIdentifier("argument"));
// If we're inheriting a default argument, mark it as such.
// FIXME: Figure out how to clone default arguments as well.
if (options & Inherited) {
switch (defaultArgKind) {
case DefaultArgumentKind::Normal:
case DefaultArgumentKind::StoredProperty:
decl->setDefaultArgumentKind(DefaultArgumentKind::Inherited);
break;
default:
break;
}
} else {
decl->setDefaultArgumentKind(DefaultArgumentKind::None);
}
}
return create(C, params);
}
void ParameterList::getParams(
SmallVectorImpl<AnyFunctionType::Param> ¶ms) const {
for (auto P : *this)
params.push_back(P->toFunctionParam());
}
/// Return the full source range of this parameter list.
SourceRange ParameterList::getSourceRange() const {
// If we have locations for the parens, then they define our range.
if (LParenLoc.isValid())
return { LParenLoc, RParenLoc };
// Otherwise, try the first and last parameter.
if (size() != 0) {
auto Start = get(0)->getStartLoc();
auto End = getArray().back()->getEndLoc();
if (Start.isValid() && End.isValid())
return { Start, End };
}
return SourceRange();
}
| apache-2.0 |
mpeuster/son-examples | vnfs/sonata-vtc-vnf-docker/nDPI/src/lib/protocols/socrates.c | 9 | 2925 | /*
* socrates.c
*
* Copyright (C) 2009-2011 by ipoque GmbH
* Copyright (C) 2011-15 - ntop.org
*
* This file is part of nDPI, an open source deep packet inspection
* library based on the OpenDPI and PACE technology by ipoque GmbH
*
* nDPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nDPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with nDPI. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ndpi_protocols.h"
#ifdef NDPI_PROTOCOL_SOCRATES
static void ndpi_socrates_add_connection(struct ndpi_detection_module_struct
*ndpi_struct, struct ndpi_flow_struct *flow)
{
ndpi_int_add_connection(ndpi_struct, flow, NDPI_PROTOCOL_SOCRATES, NDPI_REAL_PROTOCOL);
}
void ndpi_search_socrates(struct ndpi_detection_module_struct
*ndpi_struct, struct ndpi_flow_struct *flow)
{
struct ndpi_packet_struct *packet = &flow->packet;
// struct ndpi_id_struct *src=ndpi_struct->src;
// struct ndpi_id_struct *dst=ndpi_struct->dst;
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "search socrates.\n");
if (packet->udp != NULL) {
if (packet->payload_packet_len > 9 && packet->payload[0] == 0xfe
&& packet->payload[packet->payload_packet_len - 1] == 0x05) {
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "found fe.\n");
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "len match.\n");
if (memcmp(&packet->payload[2], "socrates", 8) == 0) {
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "found socrates udp.\n");
ndpi_socrates_add_connection(ndpi_struct, flow);
}
}
} else if (packet->tcp != NULL) {
if (packet->payload_packet_len > 13 && packet->payload[0] == 0xfe
&& packet->payload[packet->payload_packet_len - 1] == 0x05) {
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "found fe.\n");
if (packet->payload_packet_len == ntohl(get_u_int32_t(packet->payload, 2))) {
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "len match.\n");
if (memcmp(&packet->payload[6], "socrates", 8) == 0) {
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "found socrates tcp.\n");
ndpi_socrates_add_connection(ndpi_struct, flow);
}
}
}
}
NDPI_LOG(NDPI_PROTOCOL_SOCRATES, ndpi_struct, NDPI_LOG_DEBUG, "exclude socrates.\n");
NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_SOCRATES);
}
#endif
| apache-2.0 |
graetzer/arangodb | 3rdParty/boost/1.71.0/libs/type_traits/test/is_pointer_test.cpp | 10 | 2859 |
// (C) Copyright John Maddock 2000.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifdef TEST_STD
# include <type_traits>
#else
# include <boost/type_traits/is_pointer.hpp>
#endif
#include "test.hpp"
#include "check_integral_constant.hpp"
TT_TEST_BEGIN(is_pointer)
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int&>::value, false);
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int&&>::value, false);
#endif
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int*>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<const int*>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<volatile int*>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<non_pointer*>::value, true);
// these were false in previous versions (JM 20 Dec 2000):
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int*const>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int*volatile>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int*const volatile>::value, true);
// JM 02 Oct 2000:
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<non_pointer>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int*&>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int(&)[2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int[2]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<char[sizeof(void*)]>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<void>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<f1>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<f2>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<f3>::value, true);
// Steve: was 'true', should be 'false', via 3.9.2p3
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<mf1>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<mf2>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<mf3>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<mf4>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<test_abc1>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<foo0_t>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<foo1_t>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<foo2_t>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<foo3_t>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<foo4_t>::value, false);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<int(*const)()>::value, true);
BOOST_CHECK_INTEGRAL_CONSTANT(::tt::is_pointer<test_abc1>::value, false);
TT_TEST_END
| apache-2.0 |
wasn-lab/visual-positioning | symbian/QZXing/examples/QQrDecoder/button.cpp | 10 | 4272 | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the demonstration applications 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 Nokia Corporation 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 "button.h"
#include <QMouseEvent>
#include <QPainter>
#include <QTimer>
Button::Button(QWidget *parent, Qt::WindowFlags f) :
QLabel(parent, f)
{
m_downPixmap = 0;
m_disabled = false;
m_toggled = false;
m_toggle_enabled = false;
}
Button::~Button()
{
}
void Button::disableBtn(bool b)
{
m_disabled = b;
setPressed(m_disabled);
}
void Button::mousePressEvent(QMouseEvent *event)
{
if (!m_disabled) {
event->accept();
setPixmap(m_downPixmap);
repaint();
// Lift button back to up after 300ms
if(m_toggle_enabled)
{
m_toggled = !m_toggled;
setPressed(m_toggled);
emit pressed();
}
else
QTimer::singleShot(300, this, SLOT(backToUp()));
}
}
void Button::backToUp()
{
setPixmap(m_upPixmap);
repaint();
emit pressed();
}
void Button::setPixmap(const QPixmap& p)
{
// Set up and down picture for the button
// Set pixmap
if (!p.isNull())
QLabel::setPixmap(p);
// Make down pixmap if it does not exists
if (m_downPixmap.isNull()) {
// Store up pixmap
m_upPixmap = *pixmap();
// Create down pixmap
// Make m_downPixmap as a transparent m_upPixmap
QPixmap transparent(m_upPixmap.size());
transparent.fill(Qt::transparent);
QPainter painter(&transparent);
painter.setCompositionMode(QPainter::CompositionMode_Source);
painter.drawPixmap(0, 0, m_upPixmap);
painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
painter.fillRect(transparent.rect(), QColor(0, 0, 0, 150));
painter.end();
m_downPixmap = transparent;
}
}
void Button::enableToggle(bool enable)
{
m_toggle_enabled = enable;
}
void Button::setPressed(bool isPressed)
{
if(isPressed)
{
m_toggled = true;
setPixmap(m_downPixmap);
}
else
{
m_toggled = false;
setPixmap(m_upPixmap);
}
}
bool Button::isPressed()
{
return m_toggled;
}
| apache-2.0 |
qbit/es-operating-system | os/kernel/port/syscall.cpp | 12 | 18933 | /*
* Copyright 2008, 2009 Google Inc.
* Copyright 2006, 2007 Nintendo Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <stddef.h>
#include <es.h>
#include <es/any.h>
#include <es/broker.h>
#include <es/exception.h>
#include <es/handle.h>
#include <es/reflect.h>
#include <es/base/ISelectable.h>
#include <es/net/IInternetAddress.h>
#include <es/net/IInternetConfig.h>
#include <es/net/ISocket.h>
#include <es/net/IResolver.h>
#include "core.h"
#include "interfaceStore.h"
#include "process.h"
// #define VERBOSE
extern es::Stream* esReportStream();
typedef long long (*Method)(void* self, ...);
bool SyscallProxy::set(void* object, const char* iid, bool used)
{
if (ref.addRef() != 1)
{
ref.release();
return false;
}
this->object = object;
this->iid = es::getUniqueIdentifier(iid);
use.exchange(used ? 1 : 0);
return true;
}
unsigned int SyscallProxy::addRef()
{
return ref.addRef();
}
unsigned int SyscallProxy::release()
{
unsigned int count = ref.release();
if (count == 0)
{
Object* object(static_cast<Object*>(getObject()));
if (object)
{
#ifdef VERBOSE
Reflect::Interface interface = es::getInterface(iid);
esReport("SyscallProxy::%s %s %p\n", __func__, interface.getName().c_str(), object);
#endif
this->object = 0;
object->release();
}
}
return count;
}
long SyscallProxy::addUser()
{
long count = use.increment();
if (count == 1)
{
addRef();
}
return count;
}
long SyscallProxy::releaseUser()
{
long count = use.decrement();
if (count == 0)
{
release();
}
return count;
}
long long Process::
systemCall(void** self, unsigned methodNumber, va_list paramv, void** base)
{
bool log = this->log;
int* paramp = reinterpret_cast<int*>(paramv);
#ifdef VERBOSE
log = true;
#endif
if (base)
{
// Note base is zero if a system call is called from the "C" runtime.
if (reinterpret_cast<int>(base) & (sizeof(void*) - 1))
{
throw SystemException<EBADF>();
}
ipt = base;
}
//
// Determine the type of interface and which method is being invoked.
//
if (reinterpret_cast<long>(self) & (sizeof(void*) - 1))
{
throw SystemException<EBADF>();
}
unsigned interfaceNumber = self - base;
Any* variant = 0;
if (INTERFACE_POINTER_MAX <= interfaceNumber)
{
// self could be a pointer to a Any value when the method returns a Any.
variant = reinterpret_cast<Any*>(self);
if (!isValid(variant, sizeof(Any)))
{
throw SystemException<EBADF>();
}
if (!isValid(paramp, sizeof(void*)))
{
throw SystemException<EBADF>();
}
self = *reinterpret_cast<void***>(paramp);
++paramp;
interfaceNumber = self - base;
if (INTERFACE_POINTER_MAX <= interfaceNumber) {
throw SystemException<EBADF>();
}
}
Handle<SyscallProxy> proxy(&syscallTable[interfaceNumber], true);
if (!proxy->isValid())
{
throw SystemException<EBADF>();
}
Reflect::Interface interface = es::getInterface(proxy->iid); // XXX Should cache the result.
// Suppress unwanted trace outputs.
if (proxy->getObject() == esReportStream() ||
interfaceNumber == 0 && methodNumber == 15) // es::Process::getNow()
{
log = false;
}
if (log)
{
esReport("system call[%d:%p]: %s", interfaceNumber, this, interface.getName().c_str());
}
// If this interface inherits another interface,
// methodNumber is checked accordingly.
if (interface.getInheritedMethodCount() + interface.getMethodCount() <= methodNumber)
{
if (log)
{
esReport("\n");
}
throw SystemException<ENOSYS>();
}
unsigned baseMethodCount;
Reflect::Interface super(interface);
for (;;)
{
baseMethodCount = super.getInheritedMethodCount();
if (baseMethodCount <= methodNumber)
{
break;
}
super = es::getInterface(super.getQualifiedSuperName().c_str());
}
Reflect::Method method(super.getMethod(methodNumber - baseMethodCount));
Reflect::Type returnType = method.getReturnType();
if (variant && returnType.getType() != Reflect::kAny ||
!variant && returnType.getType() == Reflect::kAny)
{
throw SystemException<EBADF>();
}
if (log)
{
esReport("::%s(", method.getName().c_str());
}
// Process addRef() and release() locally
bool stringIsInterfaceName = false;
if (super.getQualifiedSuperName() == "")
{
unsigned long count;
switch (methodNumber - baseMethodCount)
{
case 0: // queryInterface
stringIsInterfaceName = true;
break;
case 1: // addRef
count = proxy->addUser();
if (log)
{
esReport("%p) : %d;\n", proxy.get(), count);
}
return count;
break;
case 2: // release
count = proxy->releaseUser();
if (log)
{
esReport("%p) : %d;\n", proxy.get(), count);
}
return count;
break;
}
}
//
// Set up parameters
//
Any argv[9];
Any* argp = argv;
void* ptr;
int count;
Handle<SyscallProxy> inputProxies[8];
Handle<UpcallProxy> upcallProxies[8];
const char* iid = Object::iid();
// Set this
Method** object = reinterpret_cast<Method**>(proxy->getObject());
*argp++ = Any(reinterpret_cast<intptr_t>(object));
switch (returnType.getType())
{
case Reflect::kAny:
// Any op(void* buf, int len);
case Reflect::kString:
// const char* op(char* buf, int len, ...);
if (!isValid(reinterpret_cast<void**>(paramp), sizeof(void*)))
{
throw SystemException<EFAULT>();
}
ptr = *reinterpret_cast<void**>(paramp);
*argp++ = Any(reinterpret_cast<intptr_t>(ptr));
++paramp;
if (!isValid(paramp, sizeof(int32_t)))
{
throw SystemException<EFAULT>();
}
count = *paramp;
*argp++ = Any(static_cast<int32_t>(count));
++paramp;
break;
case Reflect::kSequence:
// int op(xxx* buf, int len, ...);
if (!isValid(reinterpret_cast<void**>(paramp), sizeof(void*)))
{
throw SystemException<EFAULT>();
}
ptr = *reinterpret_cast<void**>(paramp);
*argp++ = Any(reinterpret_cast<intptr_t>(ptr));
++paramp;
if ((count = returnType.getSize()) == 0)
{
if (!isValid(paramp, sizeof(int32_t)))
{
throw SystemException<EFAULT>();
}
Reflect::Sequence seq(returnType);
*argp++ = Any(static_cast<int32_t>(*paramp));
count = *paramp * seq.getType().getSize();
++paramp;
}
break;
case Reflect::kArray:
// void op(xxx[x] buf, ...);
if (!isValid(reinterpret_cast<void**>(paramp), sizeof(void*)))
{
throw SystemException<EFAULT>();
}
ptr = *reinterpret_cast<void**>(paramp);
*argp++ = Any(reinterpret_cast<intptr_t>(ptr));
count = returnType.getSize();
++paramp;
break;
default:
ptr = 0;
count = 0;
break;
}
if (ptr && !isValid(ptr, count))
{
throw SystemException<EFAULT>();
}
Reflect::Parameter param = method.listParameter();
for (int i = 0;
param.next();
++argp, ++i)
{
Reflect::Type type(param.getType());
const void* ptr = 0;
int count = 0;
char entType = type.getType();
u32 stackBytes;
switch (entType)
{
case Reflect::kLongLong:
case Reflect::kUnsignedLongLong:
case Reflect::kDouble:
case Reflect::kSequence: // TODO: stackBytes is 4 for a fixed length sequence
stackBytes = 8;
break;
case Reflect::kAny:
stackBytes = sizeof(AnyBase);
break;
default:
stackBytes = 4;
break;
}
if (!isValid(paramp, stackBytes))
{
throw SystemException<EFAULT>();
}
switch (entType)
{
case Reflect::kAny:
*argp = Any(*reinterpret_cast<AnyBase*>(paramp));
paramp += sizeof(AnyBase) / sizeof(int);
switch (argp->getType())
{
case Any::TypeString:
ptr = static_cast<const char*>(*argp);
count = sizeof(char); // XXX check string length?
break;
case Any::TypeObject:
if (void** ip = *reinterpret_cast<void***>(static_cast<Object*>(*argp)))
{
if (base <= ip && ip < base + INTERFACE_POINTER_MAX)
{
unsigned interfaceNumber(ip - base);
Handle<SyscallProxy> proxy(&syscallTable[interfaceNumber], true);
if (!proxy->isValid())
{
throw SystemException<EINVAL>();
}
inputProxies[i] = proxy;
*argp = Any(static_cast<Object*>(inputProxies[i]->getObject()));
}
else // XXX Check range
{
// Allocate an entry in the upcall table and set the
// interface pointer to the broker for the upcall table.
int n = set(this, (Object*) ip, iid, false);
if (n < 0)
{
throw SystemException<ENFILE>();
}
// Note the reference count of the created upcall proxy must
// be decremented by one at the end of this system call.
upcallProxies[i] = &upcallTable[n];
*argp = Any(reinterpret_cast<Object*>(&(broker.getInterfaceTable())[n]));
}
}
else
{
*argp = Any(static_cast<Object*>(0));
}
argp->makeVariant();
break;
}
break;
case Reflect::kBoolean:
*argp = Any(static_cast<bool>(*paramp++));
break;
case Reflect::kPointer:
*argp = Any(static_cast<uint32_t>(*paramp++)); // x86 only
break;
case Reflect::kShort:
*argp = Any(static_cast<int16_t>(*paramp++));
break;
case Reflect::kLong:
*argp = Any(static_cast<int32_t>(*paramp++));
break;
case Reflect::kOctet:
*argp = Any(static_cast<uint8_t>(*paramp++));
break;
case Reflect::kUnsignedShort:
*argp = Any(static_cast<uint16_t>(*paramp++));
break;
case Reflect::kUnsignedLong:
*argp = Any(static_cast<uint32_t>(*paramp++));
break;
case Reflect::kLongLong:
*argp = Any(*reinterpret_cast<int64_t*>(paramp));
paramp += 2;
break;
case Reflect::kUnsignedLongLong:
*argp = Any(*reinterpret_cast<uint64_t*>(paramp));
paramp += 2;
break;
case Reflect::kFloat:
*argp = Any(*reinterpret_cast<float*>(paramp++));
break;
case Reflect::kDouble:
*argp = Any(*reinterpret_cast<double*>(paramp));
paramp += 2;
break;
case Reflect::kString:
ptr = *reinterpret_cast<void**>(paramp);
if (stringIsInterfaceName)
{
iid = static_cast<const char*>(ptr);
}
*argp = Any(static_cast<const char*>(ptr));
++paramp;
count = sizeof(char); // XXX check string length?
break;
case Reflect::kSequence:
// xxx* buf, int len, ...
ptr = *reinterpret_cast<void**>(paramp);
*argp++ = Any(reinterpret_cast<intptr_t>(ptr));
++paramp;
if ((count = type.getSize()) == 0)
{
Reflect::Sequence seq(type);
*argp = Any(static_cast<int32_t>(*paramp));
count = *paramp * seq.getType().getSize();
++paramp;
}
break;
case Reflect::kArray: // xxx[x] buf, ...
ptr = *reinterpret_cast<void**>(paramp);
*argp = Any(reinterpret_cast<intptr_t>(ptr));
count = type.getSize();
++paramp;
break;
case Reflect::kObject:
if (void** ip = *reinterpret_cast<void***>(paramp++))
{
if (base <= ip && ip < base + INTERFACE_POINTER_MAX)
{
unsigned interfaceNumber(ip - base);
Handle<SyscallProxy> proxy(&syscallTable[interfaceNumber], true);
if (!proxy->isValid())
{
throw SystemException<EINVAL>();
}
inputProxies[i] = proxy;
*argp = Any(static_cast<Object*>(inputProxies[i]->getObject()));
}
else // XXX Check range
{
// Allocate an entry in the upcall table and set the
// interface pointer to the broker for the upcall table.
int n = set(this, (Object*) ip, stringIsInterfaceName ? iid : type.getQualifiedName().c_str(), false);
if (n < 0)
{
throw SystemException<ENFILE>();
}
// Note the reference count of the created upcall proxy must
// be decremented by one at the end of this system call.
upcallProxies[i] = &upcallTable[n];
*argp = Any(reinterpret_cast<Object*>(&(broker.getInterfaceTable())[n]));
}
}
else
{
*argp = Any(static_cast<Object*>(0));
}
break;
default:
break;
}
// Check range
if (ptr && !isValid(ptr, count))
{
throw SystemException<EFAULT>();
}
if (log && i + 1 < method.getParameterCount())
{
esReport(", ");
}
}
if (log)
{
esReport(");\n");
}
// Invoke method
int argc = argp - argv;
Any result;
void* ip = 0;
switch (returnType.getType())
{
case Reflect::kAny:
*variant = apply(argc, argv, (Any (*)()) ((*object)[methodNumber]));
result = Any(reinterpret_cast<intptr_t>(variant));
if (variant->getType() == Any::TypeObject) {
ip = static_cast<Object*>(*variant);
}
break;
case Reflect::kBoolean:
result = apply(argc, argv, (bool (*)()) ((*object)[methodNumber]));
break;
case Reflect::kOctet:
result = apply(argc, argv, (uint8_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kShort:
result = apply(argc, argv, (int16_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kUnsignedShort:
result = apply(argc, argv, (uint16_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kLong:
result = apply(argc, argv, (int32_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kPointer: // XXX x86 specific
case Reflect::kUnsignedLong:
result = apply(argc, argv, (uint32_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kLongLong:
result = apply(argc, argv, (int64_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kUnsignedLongLong:
result = apply(argc, argv, (uint64_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kFloat:
result = apply(argc, argv, (float (*)()) ((*object)[methodNumber]));
break;
case Reflect::kDouble:
result = apply(argc, argv, (double (*)()) ((*object)[methodNumber]));
break;
case Reflect::kString:
result = apply(argc, argv, (const char* (*)()) ((*object)[methodNumber]));
// TODO: If the returned string resides in the kernel space, it must be copied out.
break;
case Reflect::kSequence:
result = apply(argc, argv, (int32_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kArray:
case Reflect::kVoid:
apply(argc, argv, (int32_t (*)()) ((*object)[methodNumber]));
break;
case Reflect::kObject:
result = apply(argc, argv, (Object* (*)()) ((*object)[methodNumber]));
ip = static_cast<Object*>(result);
break;
}
// Process the returned interface pointer
if (ip)
{
int n = set(syscallTable, ip, stringIsInterfaceName ? iid : returnType.getQualifiedName().c_str(), true);
if (0 <= n)
{
result = Any(reinterpret_cast<Object*>(&base[n]));
}
else
{
Object* object(static_cast<Object*>(ip));
object->release();
result = Any(static_cast<Object*>(0));
throw SystemException<EMFILE>();
}
}
// Process addRef() and release() locally
if (interface.getQualifiedName() == es::Monitor::iid())
{
unsigned long count;
switch (methodNumber)
{
case 3: // lock
count = proxy->addUser();
break;
case 4: // tryLock
if (static_cast<bool>(result))
{
count = proxy->addUser();
}
break;
case 5: // unlock
count = proxy->releaseUser();
break;
}
}
return evaluate(result);
}
| apache-2.0 |
ldts/zephyr | ext/hal/st/stm32cube/stm32mp1xx/drivers/src/stm32mp1xx_hal_crc.c | 12 | 17115 | /**
******************************************************************************
* @file stm32mp1xx_hal_crc.c
* @author MCD Application Team
* @brief CRC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Cyclic Redundancy Check (CRC) peripheral:
* + Initialization and de-initialization functions
* + Peripheral Control functions
* + Peripheral State functions
*
@verbatim
===============================================================================
##### How to use this driver #####
===============================================================================
[..]
(+) Enable CRC AHB clock using __HAL_RCC_CRC_CLK_ENABLE();
(+) Initialize CRC calculator
(++) specify generating polynomial (peripheral default or non-default one)
(++) specify initialization value (peripheral default or non-default one)
(++) specify input data format
(++) specify input or output data inversion mode if any
(+) Use HAL_CRC_Accumulate() function to compute the CRC value of the
input data buffer starting with the previously computed CRC as
initialization value
(+) Use HAL_CRC_Calculate() function to compute the CRC value of the
input data buffer starting with the defined initialization value
(default or non-default) to initiate CRC calculation
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32mp1xx_hal.h"
/** @addtogroup STM32MP1xx_HAL_Driver
* @{
*/
/** @defgroup CRC CRC
* @brief CRC HAL module driver.
* @{
*/
#ifdef HAL_CRC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup CRC_Private_Functions CRC Private Functions
* @{
*/
static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength);
static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup CRC_Exported_Functions CRC Exported Functions
* @{
*/
/** @defgroup CRC_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions.
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize the CRC according to the specified parameters
in the CRC_InitTypeDef and create the associated handle
(+) DeInitialize the CRC peripheral
(+) Initialize the CRC MSP (MCU Specific Package)
(+) DeInitialize the CRC MSP
@endverbatim
* @{
*/
/**
* @brief Initialize the CRC according to the specified
* parameters in the CRC_InitTypeDef and create the associated handle.
* @param hcrc CRC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc)
{
/* Check the CRC handle allocation */
if (hcrc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance));
if (hcrc->State == HAL_CRC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hcrc->Lock = HAL_UNLOCKED;
/* Init the low level hardware */
HAL_CRC_MspInit(hcrc);
}
hcrc->State = HAL_CRC_STATE_BUSY;
/* check whether or not non-default generating polynomial has been
* picked up by user */
assert_param(IS_DEFAULT_POLYNOMIAL(hcrc->Init.DefaultPolynomialUse));
if (hcrc->Init.DefaultPolynomialUse == DEFAULT_POLYNOMIAL_ENABLE)
{
/* initialize peripheral with default generating polynomial */
WRITE_REG(hcrc->Instance->POL, DEFAULT_CRC32_POLY);
MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, CRC_POLYLENGTH_32B);
}
else
{
/* initialize CRC peripheral with generating polynomial defined by user */
if (HAL_CRCEx_Polynomial_Set(hcrc, hcrc->Init.GeneratingPolynomial, hcrc->Init.CRCLength) != HAL_OK)
{
return HAL_ERROR;
}
}
/* check whether or not non-default CRC initial value has been
* picked up by user */
assert_param(IS_DEFAULT_INIT_VALUE(hcrc->Init.DefaultInitValueUse));
if (hcrc->Init.DefaultInitValueUse == DEFAULT_INIT_VALUE_ENABLE)
{
WRITE_REG(hcrc->Instance->INIT, DEFAULT_CRC_INITVALUE);
}
else
{
WRITE_REG(hcrc->Instance->INIT, hcrc->Init.InitValue);
}
/* set input data inversion mode */
assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(hcrc->Init.InputDataInversionMode));
MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, hcrc->Init.InputDataInversionMode);
/* set output data inversion mode */
assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(hcrc->Init.OutputDataInversionMode));
MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, hcrc->Init.OutputDataInversionMode);
/* makes sure the input data format (bytes, halfwords or words stream)
* is properly specified by user */
assert_param(IS_CRC_INPUTDATA_FORMAT(hcrc->InputDataFormat));
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief DeInitialize the CRC peripheral.
* @param hcrc CRC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc)
{
/* Check the CRC handle allocation */
if (hcrc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance));
/* Check the CRC peripheral state */
if (hcrc->State == HAL_CRC_STATE_BUSY)
{
return HAL_BUSY;
}
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_BUSY;
/* Reset CRC calculation unit */
__HAL_CRC_DR_RESET(hcrc);
/* Reset IDR register content */
CLEAR_BIT(hcrc->Instance->IDR, CRC_IDR_IDR);
/* DeInit the low level hardware */
HAL_CRC_MspDeInit(hcrc);
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_RESET;
/* Process unlocked */
__HAL_UNLOCK(hcrc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the CRC MSP.
* @param hcrc CRC handle
* @retval None
*/
__weak void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcrc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_CRC_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitialize the CRC MSP.
* @param hcrc CRC handle
* @retval None
*/
__weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hcrc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_CRC_MspDeInit can be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup CRC_Exported_Functions_Group2 Peripheral Control functions
* @brief management functions.
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer
using combination of the previous CRC value and the new one.
[..] or
(+) compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer
independently of the previous CRC value.
@endverbatim
* @{
*/
/**
* @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer
* starting with the previously computed CRC as initialization value.
* @param hcrc CRC handle
* @param pBuffer pointer to the input data buffer, exact input data format is
* provided by hcrc->InputDataFormat.
* @param BufferLength input data buffer length (number of bytes if pBuffer
* type is * uint8_t, number of half-words if pBuffer type is * uint16_t,
* number of words if pBuffer type is * uint32_t).
* @note By default, the API expects a uint32_t pointer as input buffer parameter.
* Input buffer pointers with other types simply need to be cast in uint32_t
* and the API will internally adjust its input data processing based on the
* handle field hcrc->InputDataFormat.
* @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits)
*/
uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength)
{
uint32_t index; /* CRC input data buffer index */
uint32_t temp = 0U; /* CRC output (read from hcrc->Instance->DR register) */
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_BUSY;
switch (hcrc->InputDataFormat)
{
case CRC_INPUTDATA_FORMAT_WORDS:
/* Enter Data to the CRC calculator */
for (index = 0U; index < BufferLength; index++)
{
hcrc->Instance->DR = pBuffer[index];
}
temp = hcrc->Instance->DR;
break;
case CRC_INPUTDATA_FORMAT_BYTES:
temp = CRC_Handle_8(hcrc, (uint8_t *)pBuffer, BufferLength);
break;
case CRC_INPUTDATA_FORMAT_HALFWORDS:
temp = CRC_Handle_16(hcrc, (uint16_t *)(void *)pBuffer, BufferLength); /* Derogation MisraC2012 R.11.5 */
break;
default:
break;
}
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_READY;
/* Return the CRC computed value */
return temp;
}
/**
* @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer
* starting with hcrc->Instance->INIT as initialization value.
* @param hcrc CRC handle
* @param pBuffer pointer to the input data buffer, exact input data format is
* provided by hcrc->InputDataFormat.
* @param BufferLength input data buffer length (number of bytes if pBuffer
* type is * uint8_t, number of half-words if pBuffer type is * uint16_t,
* number of words if pBuffer type is * uint32_t).
* @note By default, the API expects a uint32_t pointer as input buffer parameter.
* Input buffer pointers with other types simply need to be cast in uint32_t
* and the API will internally adjust its input data processing based on the
* handle field hcrc->InputDataFormat.
* @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits)
*/
uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength)
{
uint32_t index; /* CRC input data buffer index */
uint32_t temp = 0U; /* CRC output (read from hcrc->Instance->DR register) */
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_BUSY;
/* Reset CRC Calculation Unit (hcrc->Instance->INIT is
* written in hcrc->Instance->DR) */
__HAL_CRC_DR_RESET(hcrc);
switch (hcrc->InputDataFormat)
{
case CRC_INPUTDATA_FORMAT_WORDS:
/* Enter 32-bit input data to the CRC calculator */
for (index = 0U; index < BufferLength; index++)
{
hcrc->Instance->DR = pBuffer[index];
}
temp = hcrc->Instance->DR;
break;
case CRC_INPUTDATA_FORMAT_BYTES:
/* Specific 8-bit input data handling */
temp = CRC_Handle_8(hcrc, (uint8_t *)pBuffer, BufferLength);
break;
case CRC_INPUTDATA_FORMAT_HALFWORDS:
/* Specific 16-bit input data handling */
temp = CRC_Handle_16(hcrc, (uint16_t *)(void *)pBuffer, BufferLength); /* Derogation MisraC2012 R.11.5 */
break;
default:
break;
}
/* Change CRC peripheral state */
hcrc->State = HAL_CRC_STATE_READY;
/* Return the CRC computed value */
return temp;
}
/**
* @}
*/
/** @defgroup CRC_Exported_Functions_Group3 Peripheral State functions
* @brief Peripheral State functions.
*
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..]
This subsection permits to get in run-time the status of the peripheral.
@endverbatim
* @{
*/
/**
* @brief Return the CRC handle state.
* @param hcrc CRC handle
* @retval HAL state
*/
HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc)
{
/* Return CRC handle state */
return hcrc->State;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup CRC_Private_Functions
* @{
*/
/**
* @brief Enter 8-bit input data to the CRC calculator.
* Specific data handling to optimize processing time.
* @param hcrc CRC handle
* @param pBuffer pointer to the input data buffer
* @param BufferLength input data buffer length
* @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits)
*/
static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength)
{
uint32_t i; /* input data buffer index */
uint16_t data;
__IO uint16_t *pReg;
/* Processing time optimization: 4 bytes are entered in a row with a single word write,
* last bytes must be carefully fed to the CRC calculator to ensure a correct type
* handling by the peripheral */
for (i = 0U; i < (BufferLength / 4U); i++)
{
hcrc->Instance->DR = ((uint32_t)pBuffer[4U * i] << 24U) | \
((uint32_t)pBuffer[(4U * i) + 1U] << 16U) | \
((uint32_t)pBuffer[(4U * i) + 2U] << 8U) | \
(uint32_t)pBuffer[(4U * i) + 3U];
}
/* last bytes specific handling */
if ((BufferLength % 4U) != 0U)
{
if ((BufferLength % 4U) == 1U)
{
*(__IO uint8_t *)(__IO void *)(&hcrc->Instance->DR) = pBuffer[4U * i]; /* Derogation MisraC2012 R.11.5 */
}
if ((BufferLength % 4U) == 2U)
{
data = ((uint16_t)(pBuffer[4U * i]) << 8U) | (uint16_t)pBuffer[(4U * i) + 1U];
pReg = (__IO uint16_t *)(__IO void *)(&hcrc->Instance->DR); /* Derogation MisraC2012 R.11.5 */
*pReg = data;
}
if ((BufferLength % 4U) == 3U)
{
data = ((uint16_t)(pBuffer[4U * i]) << 8U) | (uint16_t)pBuffer[(4U * i) + 1U];
pReg = (__IO uint16_t *)(__IO void *)(&hcrc->Instance->DR); /* Derogation MisraC2012 R.11.5 */
*pReg = data;
*(__IO uint8_t *)(__IO void *)(&hcrc->Instance->DR) = pBuffer[(4U * i) + 2U]; /* Derogation MisraC2012 R.11.5 */
}
}
/* Return the CRC computed value */
return hcrc->Instance->DR;
}
/**
* @brief Enter 16-bit input data to the CRC calculator.
* Specific data handling to optimize processing time.
* @param hcrc CRC handle
* @param pBuffer pointer to the input data buffer
* @param BufferLength input data buffer length
* @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits)
*/
static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength)
{
uint32_t i; /* input data buffer index */
__IO uint16_t *pReg;
/* Processing time optimization: 2 HalfWords are entered in a row with a single word write,
* in case of odd length, last HalfWord must be carefully fed to the CRC calculator to ensure
* a correct type handling by the peripheral */
for (i = 0U; i < (BufferLength / 2U); i++)
{
hcrc->Instance->DR = ((uint32_t)pBuffer[2U * i] << 16U) | (uint32_t)pBuffer[(2U * i) + 1U];
}
if ((BufferLength % 2U) != 0U)
{
pReg = (__IO uint16_t *)(__IO void *)(&hcrc->Instance->DR); /* Derogation MisraC2012 R.11.5 */
*pReg = pBuffer[2U * i];
}
/* Return the CRC computed value */
return hcrc->Instance->DR;
}
/**
* @}
*/
#endif /* HAL_CRC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
hkernbach/arangodb | 3rdParty/boost/1.62.0/libs/test/test/framework-ts/result-report-test.cpp | 14 | 5636 | // (C) Copyright Gennadiy Rozental 2001-2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : tests Unit Test Framework reporting facilities against
// pattern file
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/results_reporter.hpp>
#include <boost/test/tools/output_test_stream.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/unit_test_parameters.hpp>
#include <boost/test/utils/nullstream.hpp>
typedef boost::onullstream onullstream_type;
// BOOST
#include <boost/lexical_cast.hpp>
// STL
#include <iostream>
using boost::test_tools::output_test_stream;
using namespace boost::unit_test;
//____________________________________________________________________________//
void good_foo() {}
void almost_good_foo() { BOOST_TEST_WARN( 2>3 ); }
void bad_foo() {
onullstream_type null_out;
unit_test_log.set_stream( null_out );
BOOST_ERROR( "" );
unit_test_log.set_stream( std::cout );
}
struct log_guard {
~log_guard()
{
unit_test_log.set_stream( std::cout );
}
};
void very_bad_foo() {
log_guard lg;
ut_detail::ignore_unused_variable_warning( lg );
onullstream_type null_out;
unit_test_log.set_stream( null_out );
BOOST_FAIL( "" );
}
//____________________________________________________________________________//
void check( output_test_stream& output, output_format report_format, test_unit_id id )
{
results_reporter::set_format( report_format );
results_reporter::confirmation_report( id );
output << "*************************************************************************\n";
BOOST_TEST( output.match_pattern() );
results_reporter::short_report( id );
output << "*************************************************************************\n";
BOOST_TEST( output.match_pattern() );
results_reporter::detailed_report( id );
output << "*************************************************************************\n";
BOOST_TEST( output.match_pattern() );
}
//____________________________________________________________________________//
void check( output_test_stream& output, test_suite* ts )
{
ts->p_default_status.value = test_unit::RS_ENABLED;
framework::finalize_setup_phase( ts->p_id );
framework::run( ts );
check( output, OF_CLF, ts->p_id );
check( output, OF_XML, ts->p_id );
}
//____________________________________________________________________________//
struct guard {
~guard()
{
results_reporter::set_stream( std::cerr );
results_reporter::set_format( runtime_config::get<output_format>(
runtime_config::REPORT_FORMAT ) );
}
};
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_result_reports )
{
guard G;
ut_detail::ignore_unused_variable_warning( G );
#define PATTERN_FILE_NAME "result_report_test.pattern"
std::string pattern_file_name(
framework::master_test_suite().argc == 1
? (runtime_config::save_pattern() ? PATTERN_FILE_NAME : "./baseline-outputs/" PATTERN_FILE_NAME )
: framework::master_test_suite().argv[1] );
output_test_stream test_output( pattern_file_name, !runtime_config::save_pattern() );
results_reporter::set_stream( test_output );
test_suite* ts_0 = BOOST_TEST_SUITE( "0 test cases inside" );
test_suite* ts_1 = BOOST_TEST_SUITE( "1 test cases inside" );
ts_1->add( BOOST_TEST_CASE( good_foo ) );
test_suite* ts_1b = BOOST_TEST_SUITE( "1 bad test case inside" );
ts_1b->add( BOOST_TEST_CASE( bad_foo ), 1 );
test_suite* ts_1c = BOOST_TEST_SUITE( "1 almost good test case inside" );
ts_1c->add( BOOST_TEST_CASE( almost_good_foo ) );
test_suite* ts_2 = BOOST_TEST_SUITE( "2 test cases inside" );
ts_2->add( BOOST_TEST_CASE( good_foo ) );
ts_2->add( BOOST_TEST_CASE( bad_foo ), 1 );
test_suite* ts_3 = BOOST_TEST_SUITE( "3 test cases inside" );
ts_3->add( BOOST_TEST_CASE( bad_foo ) );
test_case* tc1 = BOOST_TEST_CASE( very_bad_foo );
ts_3->add( tc1 );
test_case* tc2 = BOOST_TEST_CASE( bad_foo );
ts_3->add( tc2 );
tc2->depends_on( tc1 );
test_suite* ts_main = BOOST_TEST_SUITE( "Fake Test Suite Hierarchy" );
ts_main->add( ts_0 );
ts_main->add( ts_1 );
ts_main->add( ts_2 );
ts_main->add( ts_3 );
test_suite* ts_char_escaping = BOOST_TEST_SUITE( "Char escaping" );
ts_char_escaping->add( BOOST_TEST_CASE( good_foo ) );
test_case * i_have_problems = BOOST_TEST_CASE( bad_foo );
i_have_problems->p_name.set("bad_foo<h>");
ts_char_escaping->add( i_have_problems );
check( test_output, ts_1 );
check( test_output, ts_1b );
check( test_output, ts_1c );
check( test_output, ts_2 );
check( test_output, ts_3 );
ts_1->add( BOOST_TEST_CASE( bad_foo ) );
ts_3->depends_on( ts_1 );
check( test_output, ts_main );
check( test_output, ts_char_escaping );
results_reporter::set_stream( std::cout );
}
//____________________________________________________________________________//
// EOF
| apache-2.0 |
nolanamy/zxing | cpp/core/tests/src/qrcode/FormatInformationTest.cpp | 15 | 3156 | /*
* FormatInformationTest.cpp
* zxing
*
* Created by Christian Brunschen on 19/05/2008.
* Copyright 2008 ZXing authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "FormatInformationTest.h"
#include "ErrorCorrectionLevelTest.h"
#include <zxing/ReaderException.h>
#include <zxing/qrcode/FormatInformation.h>
#include <zxing/qrcode/ErrorCorrectionLevel.h>
namespace zxing {
namespace qrcode {
CPPUNIT_TEST_SUITE_REGISTRATION(FormatInformationTest);
static const int MASKED_TEST_FORMAT_INFO = 0x2BED;
static const int UNMASKED_TEST_FORMAT_INFO = MASKED_TEST_FORMAT_INFO ^ 0x5412;
static void assertEquals(Ref<FormatInformation> a,
Ref<FormatInformation> b) {
if (a == NULL || b == NULL)
{
CPPUNIT_ASSERT_EQUAL(a, b);
}
else
{
FormatInformation &aa = *a;
FormatInformation &bb = *b;
CPPUNIT_ASSERT_EQUAL(aa, bb);
}
}
void FormatInformationTest::testBitsDiffering() {
CPPUNIT_ASSERT_EQUAL(0, FormatInformation::numBitsDiffering(1, 1));
CPPUNIT_ASSERT_EQUAL(1, FormatInformation::numBitsDiffering(0, 2));
CPPUNIT_ASSERT_EQUAL(2, FormatInformation::numBitsDiffering(1, 2));
CPPUNIT_ASSERT_EQUAL(32, FormatInformation::numBitsDiffering(0xffffffff,
0));
}
void FormatInformationTest::testDecode() {
// Normal case
Ref<FormatInformation> expected =
FormatInformation::decodeFormatInformation(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO);
CPPUNIT_ASSERT_EQUAL((unsigned char) 0x07, expected->getDataMask());
CPPUNIT_ASSERT_EQUAL(&ErrorCorrectionLevel::Q,
&expected->getErrorCorrectionLevel());
// where the code forgot the mask!
assertEquals(expected,
FormatInformation::decodeFormatInformation(UNMASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO));
//TODO separate tests as in Java?
// 1,2,3,4 bits difference
assertEquals(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x01, MASKED_TEST_FORMAT_INFO ^ 0x01));
assertEquals(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO ^ 0x03));
assertEquals(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x07, MASKED_TEST_FORMAT_INFO ^ 0x07));
Ref<FormatInformation> expectedNull(NULL);
assertEquals(expectedNull, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x0F, MASKED_TEST_FORMAT_INFO ^ 0x0F));
// WithMisread
assertEquals(expected, FormatInformation::decodeFormatInformation(
MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO ^ 0x0F));
}
}
}
| apache-2.0 |
HeadsUpDisplayInc/mbed | targets/TARGET_STM/TARGET_STM32L4/device/stm32l4xx_hal_irda.c | 21 | 79659 | /**
******************************************************************************
* @file stm32l4xx_hal_irda.c
* @author MCD Application Team
* @version V1.7.1
* @date 21-April-2017
* @brief IRDA HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the IrDA (Infrared Data Association) Peripheral
* (IRDA)
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and Errors functions
* + Peripheral Control functions
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The IRDA HAL driver can be used as follows:
(#) Declare a IRDA_HandleTypeDef handle structure (eg. IRDA_HandleTypeDef hirda).
(#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API
in setting the associated USART or UART in IRDA mode:
(++) Enable the USARTx/UARTx interface clock.
(++) USARTx/UARTx pins configuration:
(+++) Enable the clock for the USARTx/UARTx GPIOs.
(+++) Configure these USARTx/UARTx pins (TX as alternate function pull-up, RX as alternate function Input).
(++) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT()
and HAL_IRDA_Receive_IT() APIs):
(+++) Configure the USARTx/UARTx interrupt priority.
(+++) Enable the NVIC USARTx/UARTx IRQ handle.
(+++) The specific IRDA interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process.
(++) DMA Configuration if you need to use DMA process (HAL_IRDA_Transmit_DMA()
and HAL_IRDA_Receive_DMA() APIs):
(+++) Declare a DMA handle structure for the Tx/Rx channel.
(+++) Enable the DMAx interface clock.
(+++) Configure the declared DMA handle structure with the required Tx/Rx parameters.
(+++) Configure the DMA Tx/Rx channel.
(+++) Associate the initialized DMA handle to the IRDA DMA Tx/Rx handle.
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx channel.
(#) Program the Baud Rate, Word Length and Parity and Mode(Receiver/Transmitter),
the normal or low power mode and the clock prescaler in the hirda handle Init structure.
(#) Initialize the IRDA registers by calling the HAL_IRDA_Init() API:
(++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
by calling the customized HAL_IRDA_MspInit() API.
-@@- The specific IRDA interrupts (Transmission complete interrupt,
RXNE interrupt and Error Interrupts) will be managed using the macros
__HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process.
(#) Three operation modes are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Send an amount of data in blocking mode using HAL_IRDA_Transmit()
(+) Receive an amount of data in blocking mode using HAL_IRDA_Receive()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Send an amount of data in non-blocking mode using HAL_IRDA_Transmit_IT()
(+) At transmission end of transfer HAL_IRDA_TxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxCpltCallback()
(+) Receive an amount of data in non-blocking mode using HAL_IRDA_Receive_IT()
(+) At reception end of transfer HAL_IRDA_RxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxCpltCallback()
(+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_IRDA_ErrorCallback()
*** DMA mode IO operation ***
==============================
[..]
(+) Send an amount of data in non-blocking mode (DMA) using HAL_IRDA_Transmit_DMA()
(+) At transmission half of transfer HAL_IRDA_TxHalfCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxHalfCpltCallback()
(+) At transmission end of transfer HAL_IRDA_TxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_TxCpltCallback()
(+) Receive an amount of data in non-blocking mode (DMA) using HAL_IRDA_Receive_DMA()
(+) At reception half of transfer HAL_IRDA_RxHalfCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxHalfCpltCallback()
(+) At reception end of transfer HAL_IRDA_RxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_IRDA_RxCpltCallback()
(+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_IRDA_ErrorCallback()
*** IRDA HAL driver macros list ***
====================================
[..]
Below the list of most used macros in IRDA HAL driver.
(+) __HAL_IRDA_ENABLE: Enable the IRDA peripheral
(+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral
(+) __HAL_IRDA_GET_FLAG : Check whether the specified IRDA flag is set or not
(+) __HAL_IRDA_CLEAR_FLAG : Clear the specified IRDA pending flag
(+) __HAL_IRDA_ENABLE_IT: Enable the specified IRDA interrupt
(+) __HAL_IRDA_DISABLE_IT: Disable the specified IRDA interrupt
(+) __HAL_IRDA_GET_IT_SOURCE: Check whether or not the specified IRDA interrupt is enabled
[..]
(@) You can refer to the IRDA HAL driver header file for more useful macros
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32l4xx_hal.h"
/** @addtogroup STM32L4xx_HAL_Driver
* @{
*/
/** @defgroup IRDA IRDA
* @brief HAL IRDA module driver
* @{
*/
#ifdef HAL_IRDA_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup IRDA_Private_Constants IRDA Private Constants
* @{
*/
#define IRDA_TEACK_REACK_TIMEOUT 1000 /*!< IRDA TX or RX enable acknowledge time-out value */
#define IRDA_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE \
| USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) /*!< UART or USART CR1 fields of parameters set by IRDA_SetConfig API */
/**
* @}
*/
/* Private macros ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup IRDA_Private_Functions
* @{
*/
static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout);
static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda);
static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda);
static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma);
static void IRDA_DMAError(DMA_HandleTypeDef *hdma);
static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma);
static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma);
static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma);
static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda);
static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup IRDA_Exported_Functions IRDA Exported Functions
* @{
*/
/** @defgroup IRDA_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
==============================================================================
##### Initialization and Configuration functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to initialize the USARTx
in asynchronous IRDA mode.
(+) For the asynchronous mode only these parameters can be configured:
(++) Baud Rate
(++) Word Length
(++) Parity: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
(++) Power mode
(++) Prescaler setting
(++) Receiver/transmitter modes
[..]
The HAL_IRDA_Init() API follows the USART asynchronous configuration procedures
(details for the procedures are available in reference manual).
@endverbatim
Depending on the frame length defined by the M1 and M0 bits (7-bit,
8-bit or 9-bit), the possible IRDA frame formats are listed in the
following table.
Table 1. IRDA frame format.
+-----------------------------------------------------------------------+
| M1 bit | M0 bit | PCE bit | IRDA frame |
|---------|---------|-----------|---------------------------------------|
| 0 | 0 | 0 | | SB | 8 bit data | STB | |
|---------|---------|-----------|---------------------------------------|
| 0 | 0 | 1 | | SB | 7 bit data | PB | STB | |
|---------|---------|-----------|---------------------------------------|
| 0 | 1 | 0 | | SB | 9 bit data | STB | |
|---------|---------|-----------|---------------------------------------|
| 0 | 1 | 1 | | SB | 8 bit data | PB | STB | |
|---------|---------|-----------|---------------------------------------|
| 1 | 0 | 0 | | SB | 7 bit data | STB | |
|---------|---------|-----------|---------------------------------------|
| 1 | 0 | 1 | | SB | 6 bit data | PB | STB | |
+-----------------------------------------------------------------------+
* @{
*/
/**
* @brief Initialize the IRDA mode according to the specified
* parameters in the IRDA_InitTypeDef and initialize the associated handle.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda)
{
/* Check the IRDA handle allocation */
if(hirda == NULL)
{
return HAL_ERROR;
}
/* Check the USART/UART associated to the IRDA handle */
assert_param(IS_IRDA_INSTANCE(hirda->Instance));
if(hirda->gState == HAL_IRDA_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hirda->Lock = HAL_UNLOCKED;
/* Init the low level hardware : GPIO, CLOCK */
HAL_IRDA_MspInit(hirda);
}
hirda->gState = HAL_IRDA_STATE_BUSY;
/* Disable the Peripheral to update the configuration registers */
__HAL_IRDA_DISABLE(hirda);
/* Set the IRDA Communication parameters */
if (IRDA_SetConfig(hirda) == HAL_ERROR)
{
return HAL_ERROR;
}
/* In IRDA mode, the following bits must be kept cleared:
- LINEN, STOP and CLKEN bits in the USART_CR2 register,
- SCEN and HDSEL bits in the USART_CR3 register.*/
CLEAR_BIT(hirda->Instance->CR2, (USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP));
CLEAR_BIT(hirda->Instance->CR3, (USART_CR3_SCEN | USART_CR3_HDSEL));
/* set the UART/USART in IRDA mode */
hirda->Instance->CR3 |= USART_CR3_IREN;
/* Enable the Peripheral */
__HAL_IRDA_ENABLE(hirda);
/* TEACK and/or REACK to check before moving hirda->gState and hirda->RxState to Ready */
return (IRDA_CheckIdleState(hirda));
}
/**
* @brief DeInitialize the IRDA peripheral.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda)
{
/* Check the IRDA handle allocation */
if(hirda == NULL)
{
return HAL_ERROR;
}
/* Check the USART/UART associated to the IRDA handle */
assert_param(IS_IRDA_INSTANCE(hirda->Instance));
hirda->gState = HAL_IRDA_STATE_BUSY;
/* DeInit the low level hardware */
HAL_IRDA_MspDeInit(hirda);
/* Disable the Peripheral */
__HAL_IRDA_DISABLE(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_RESET;
hirda->RxState = HAL_IRDA_STATE_RESET;
/* Process Unlock */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Initialize the IRDA MSP.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_MspInit can be implemented in the user file
*/
}
/**
* @brief DeInitialize the IRDA MSP.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE: This function should not be modified, when the callback is needed,
the HAL_IRDA_MspDeInit can be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup IRDA_Exported_Functions_Group2 IO operation functions
* @brief IRDA Transmit and Receive functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the IRDA data transfers.
[..]
IrDA is a half duplex communication protocol. If the Transmitter is busy, any data
on the IrDA receive line will be ignored by the IrDA decoder and if the Receiver
is busy, data on the TX from the USART to IrDA will not be encoded by IrDA.
While receiving data, transmission should be avoided as the data to be transmitted
could be corrupted.
(#) There are two mode of transfer:
(++) Blocking mode: the communication is performed in polling mode.
The HAL status of all data processing is returned by the same function
after finishing transfer.
(++) Non-Blocking mode: the communication is performed using Interrupts
or DMA, these API's return the HAL status.
The end of the data processing will be indicated through the
dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
The HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxCpltCallback() user callbacks
will be executed respectively at the end of the Transmit or Receive process
The HAL_IRDA_ErrorCallback() user callback will be executed when a communication error is detected
(#) Blocking mode APIs are :
(++) HAL_IRDA_Transmit()
(++) HAL_IRDA_Receive()
(#) Non Blocking mode APIs with Interrupt are :
(++) HAL_IRDA_Transmit_IT()
(++) HAL_IRDA_Receive_IT()
(++) HAL_IRDA_IRQHandler()
(#) Non Blocking mode functions with DMA are :
(++) HAL_IRDA_Transmit_DMA()
(++) HAL_IRDA_Receive_DMA()
(++) HAL_IRDA_DMAPause()
(++) HAL_IRDA_DMAResume()
(++) HAL_IRDA_DMAStop()
(#) A set of Transfer Complete Callbacks are provided in Non Blocking mode:
(++) HAL_IRDA_TxHalfCpltCallback()
(++) HAL_IRDA_TxCpltCallback()
(++) HAL_IRDA_RxHalfCpltCallback()
(++) HAL_IRDA_RxCpltCallback()
(++) HAL_IRDA_ErrorCallback()
(#) Non-Blocking mode transfers could be aborted using Abort API's :
(+) HAL_IRDA_Abort()
(+) HAL_IRDA_AbortTransmit()
(+) HAL_IRDA_AbortReceive()
(+) HAL_IRDA_Abort_IT()
(+) HAL_IRDA_AbortTransmit_IT()
(+) HAL_IRDA_AbortReceive_IT()
(#) For Abort services based on interrupts (HAL_IRDA_Abortxxx_IT), a set of Abort Complete Callbacks are provided:
(+) HAL_IRDA_AbortCpltCallback()
(+) HAL_IRDA_AbortTransmitCpltCallback()
(+) HAL_IRDA_AbortReceiveCpltCallback()
(#) In Non-Blocking mode transfers, possible errors are split into 2 categories.
Errors are handled as follows :
(+) Error is considered as Recoverable and non blocking : Transfer could go till end, but error severity is
to be evaluated by user : this concerns Frame Error, Parity Error or Noise Error in Interrupt mode reception .
Received character is then retrieved and stored in Rx buffer, Error code is set to allow user to identify error type,
and HAL_IRDA_ErrorCallback() user callback is executed. Transfer is kept ongoing on IRDA side.
If user wants to abort it, Abort services should be called by user.
(+) Error is considered as Blocking : Transfer could not be completed properly and is aborted.
This concerns Overrun Error In Interrupt mode reception and all errors in DMA mode.
Error code is set to allow user to identify error type, and HAL_IRDA_ErrorCallback() user callback is executed.
@endverbatim
* @{
*/
/**
* @brief Send an amount of data in blocking mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer.
* @param Size Amount of data to be sent.
* @param Timeout Specify timeout value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t* tmp;
uint32_t tickstart = 0;
/* Check that a Tx process is not already ongoing */
if(hirda->gState == HAL_IRDA_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_BUSY_TX;
/* Init tickstart for timeout managment*/
tickstart = HAL_GetTick();
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
while(hirda->TxXferCount > 0)
{
hirda->TxXferCount--;
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
tmp = (uint16_t*) pData;
hirda->Instance->TDR = (*tmp & (uint16_t)0x01FF);
pData += 2;
}
else
{
hirda->Instance->TDR = (*pData++ & (uint8_t)0xFF);
}
}
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* At end of Tx process, restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in blocking mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer.
* @param Size Amount of data to be received.
* @param Timeout Specify timeout value.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t* tmp;
uint16_t uhMask;
uint32_t tickstart = 0;
/* Check that a Rx process is not already ongoing */
if(hirda->RxState == HAL_IRDA_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->RxState = HAL_IRDA_STATE_BUSY_RX;
/* Init tickstart for timeout managment*/
tickstart = HAL_GetTick();
hirda->RxXferSize = Size;
hirda->RxXferCount = Size;
/* Computation of the mask to apply to RDR register
of the UART associated to the IRDA */
IRDA_MASK_COMPUTATION(hirda);
uhMask = hirda->Mask;
/* Check data remaining to be received */
while(hirda->RxXferCount > 0)
{
hirda->RxXferCount--;
if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, tickstart, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
tmp = (uint16_t*) pData ;
*tmp = (uint16_t)(hirda->Instance->RDR & uhMask);
pData +=2;
}
else
{
*pData++ = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask);
}
}
/* At end of Rx process, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Send an amount of data in interrupt mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer.
* @param Size Amount of data to be sent.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
/* Check that a Tx process is not already ongoing */
if(hirda->gState == HAL_IRDA_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pTxBuffPtr = pData;
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_BUSY_TX;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the IRDA Transmit Data Register Empty Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_TXEIE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in interrupt mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer.
* @param Size Amount of data to be received.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
/* Check that a Rx process is not already ongoing */
if(hirda->RxState == HAL_IRDA_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pRxBuffPtr = pData;
hirda->RxXferSize = Size;
hirda->RxXferCount = Size;
/* Computation of the mask to apply to the RDR register
of the UART associated to the IRDA */
IRDA_MASK_COMPUTATION(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->RxState = HAL_IRDA_STATE_BUSY_RX;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the IRDA Parity Error and Data Register not empty Interrupts */
SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE| USART_CR1_RXNEIE);
/* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(hirda->Instance->CR3, USART_CR3_EIE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Send an amount of data in DMA mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData pointer to data buffer.
* @param Size amount of data to be sent.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
/* Check that a Tx process is not already ongoing */
if(hirda->gState == HAL_IRDA_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pTxBuffPtr = pData;
hirda->TxXferSize = Size;
hirda->TxXferCount = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->gState = HAL_IRDA_STATE_BUSY_TX;
/* Set the IRDA DMA transfer complete callback */
hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt;
/* Set the IRDA DMA half transfer complete callback */
hirda->hdmatx->XferHalfCpltCallback = IRDA_DMATransmitHalfCplt;
/* Set the DMA error callback */
hirda->hdmatx->XferErrorCallback = IRDA_DMAError;
/* Set the DMA abort callback */
hirda->hdmatx->XferAbortCallback = NULL;
/* Enable the IRDA transmit DMA channel */
HAL_DMA_Start_IT(hirda->hdmatx, (uint32_t)hirda->pTxBuffPtr, (uint32_t)&hirda->Instance->TDR, Size);
/* Clear the TC flag in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_TCF);
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the DMA transfer for transmit request by setting the DMAT bit
in the USART CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in DMA mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param pData Pointer to data buffer.
* @param Size Amount of data to be received.
* @note When the IRDA parity is enabled (PCE = 1), the received data contains
* the parity bit (MSB position).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size)
{
/* Check that a Rx process is not already ongoing */
if(hirda->RxState == HAL_IRDA_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hirda);
hirda->pRxBuffPtr = pData;
hirda->RxXferSize = Size;
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
hirda->RxState = HAL_IRDA_STATE_BUSY_RX;
/* Set the IRDA DMA transfer complete callback */
hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt;
/* Set the IRDA DMA half transfer complete callback */
hirda->hdmarx->XferHalfCpltCallback = IRDA_DMAReceiveHalfCplt;
/* Set the DMA error callback */
hirda->hdmarx->XferErrorCallback = IRDA_DMAError;
/* Set the DMA abort callback */
hirda->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->RDR, (uint32_t)hirda->pRxBuffPtr, Size);
/* Process Unlocked */
__HAL_UNLOCK(hirda);
/* Enable the UART Parity Error Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
SET_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Enable the DMA transfer for the receiver request by setting the DMAR bit
in the USART CR3 register */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Pause the DMA Transfer.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAPause(IRDA_HandleTypeDef *hirda)
{
/* Process Locked */
__HAL_LOCK(hirda);
if ((hirda->gState == HAL_IRDA_STATE_BUSY_TX) &&
(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)))
{
/* Disable the IRDA DMA Tx request */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
}
if ((hirda->RxState == HAL_IRDA_STATE_BUSY_RX) &&
(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)))
{
/* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Rx request */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Resume the DMA Transfer.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAResume(IRDA_HandleTypeDef *hirda)
{
/* Process Locked */
__HAL_LOCK(hirda);
if(hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
/* Enable the IRDA DMA Tx request */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
}
if(hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
/* Clear the Overrun flag before resuming the Rx transfer*/
__HAL_IRDA_CLEAR_OREFLAG(hirda);
/* Reenable PE and ERR (Frame error, noise error, overrun error) interrupts */
SET_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
SET_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Enable the IRDA DMA Rx request */
SET_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
}
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Stop the DMA Transfer.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_DMAStop(IRDA_HandleTypeDef *hirda)
{
/* The Lock is not implemented on this API to allow the user application
to call the HAL IRDA API under callbacks HAL_IRDA_TxCpltCallback() / HAL_IRDA_RxCpltCallback() /
HAL_IRDA_TxHalfCpltCallback / HAL_IRDA_RxHalfCpltCallback:
indeed, when HAL_DMA_Abort() API is called, the DMA TX/RX Transfer or Half Transfer complete
interrupt is generated if the DMA transfer interruption occurs at the middle or at the end of
the stream and the corresponding call back is executed. */
/* Stop IRDA DMA Tx request if ongoing */
if ((hirda->gState == HAL_IRDA_STATE_BUSY_TX) &&
(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel */
if(hirda->hdmatx != NULL)
{
HAL_DMA_Abort(hirda->hdmatx);
}
IRDA_EndTxTransfer(hirda);
}
/* Stop IRDA DMA Rx request if ongoing */
if ((hirda->RxState == HAL_IRDA_STATE_BUSY_RX) &&
(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel */
if(hirda->hdmarx != NULL)
{
HAL_DMA_Abort(hirda->hdmarx);
}
IRDA_EndRxTransfer(hirda);
}
return HAL_OK;
}
/**
* @brief Abort ongoing transfers (blocking mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx and Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode)
* - Set handle State to READY
* @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Abort(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */
if(hirda->hdmatx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmatx->XferAbortCallback = NULL;
HAL_DMA_Abort(hirda->hdmatx);
}
}
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */
if(hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = NULL;
HAL_DMA_Abort(hirda->hdmarx);
}
}
/* Reset Tx and Rx transfer counters */
hirda->TxXferCount = 0;
hirda->RxXferCount = 0;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Reset Handle ErrorCode to No Error */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
return HAL_OK;
}
/**
* @brief Abort ongoing Transmit transfer (blocking mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode)
* - Set handle State to READY
* @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortTransmit(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE and TCIE interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE));
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use blocking DMA Abort API (no callback) */
if(hirda->hdmatx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmatx->XferAbortCallback = NULL;
HAL_DMA_Abort(hirda->hdmatx);
}
}
/* Reset Tx transfer counter */
hirda->TxXferCount = 0;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
return HAL_OK;
}
/**
* @brief Abort ongoing Receive transfer (blocking mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort (in case of transfer in DMA mode)
* - Set handle State to READY
* @note This procedure is executed in blocking mode : when exiting function, Abort is considered as completed.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortReceive(IRDA_HandleTypeDef *hirda)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use blocking DMA Abort API (no callback) */
if(hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback to Null.
No call back execution at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = NULL;
HAL_DMA_Abort(hirda->hdmarx);
}
}
/* Reset Rx transfer counter */
hirda->RxXferCount = 0;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
return HAL_OK;
}
/**
* @brief Abort ongoing transfers (Interrupt mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx and Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode)
* - Set handle State to READY
* - At abort completion, call user abort complete callback
* @note This procedure is executed in Interrupt mode, meaning that abort procedure could be
* considered as completed only when user abort complete callback is executed (not when exiting function).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_Abort_IT(IRDA_HandleTypeDef *hirda)
{
uint32_t abortcplt = 1;
/* Disable TXEIE, TCIE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE | USART_CR1_TCIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* If DMA Tx and/or DMA Rx Handles are associated to IRDA Handle, DMA Abort complete callbacks should be initialised
before any call to DMA Abort functions */
/* DMA Tx Handle is valid */
if(hirda->hdmatx != NULL)
{
/* Set DMA Abort Complete callback if IRDA DMA Tx request if enabled.
Otherwise, set it to NULL */
if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
hirda->hdmatx->XferAbortCallback = IRDA_DMATxAbortCallback;
}
else
{
hirda->hdmatx->XferAbortCallback = NULL;
}
}
/* DMA Rx Handle is valid */
if(hirda->hdmarx != NULL)
{
/* Set DMA Abort Complete callback if IRDA DMA Rx request if enabled.
Otherwise, set it to NULL */
if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
hirda->hdmarx->XferAbortCallback = IRDA_DMARxAbortCallback;
}
else
{
hirda->hdmarx->XferAbortCallback = NULL;
}
}
/* Disable the IRDA DMA Tx request if enabled */
if(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
/* Disable DMA Tx at UART level */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */
if(hirda->hdmatx != NULL)
{
/* IRDA Tx DMA Abort callback has already been initialised :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
/* Abort DMA TX */
if(HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK)
{
hirda->hdmatx->XferAbortCallback = NULL;
}
else
{
abortcplt = 0;
}
}
}
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */
if(hirda->hdmarx != NULL)
{
/* IRDA Rx DMA Abort callback has already been initialised :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
/* Abort DMA RX */
if(HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK)
{
hirda->hdmarx->XferAbortCallback = NULL;
abortcplt = 1;
}
else
{
abortcplt = 0;
}
}
}
/* if no DMA abort complete callback execution is required => call user Abort Complete callback */
if (abortcplt == 1)
{
/* Reset Tx and Rx transfer counters */
hirda->TxXferCount = 0;
hirda->RxXferCount = 0;
/* Reset errorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
HAL_IRDA_AbortCpltCallback(hirda);
}
return HAL_OK;
}
/**
* @brief Abort ongoing Transmit transfer (Interrupt mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Tx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Tx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode)
* - Set handle State to READY
* - At abort completion, call user abort complete callback
* @note This procedure is executed in Interrupt mode, meaning that abort procedure could be
* considered as completed only when user abort complete callback is executed (not when exiting function).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortTransmit_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE and TCIE interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE));
/* Disable the IRDA DMA Tx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Abort the IRDA DMA Tx channel : use non blocking DMA Abort API (callback) */
if(hirda->hdmatx != NULL)
{
/* Set the IRDA DMA Abort callback :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
hirda->hdmatx->XferAbortCallback = IRDA_DMATxOnlyAbortCallback;
/* Abort DMA TX */
if(HAL_DMA_Abort_IT(hirda->hdmatx) != HAL_OK)
{
/* Call Directly hirda->hdmatx->XferAbortCallback function in case of error */
hirda->hdmatx->XferAbortCallback(hirda->hdmatx);
}
}
else
{
/* Reset Tx transfer counter */
hirda->TxXferCount = 0;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
HAL_IRDA_AbortTransmitCpltCallback(hirda);
}
}
else
{
/* Reset Tx transfer counter */
hirda->TxXferCount = 0;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
HAL_IRDA_AbortTransmitCpltCallback(hirda);
}
return HAL_OK;
}
/**
* @brief Abort ongoing Receive transfer (Interrupt mode).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @note This procedure could be used for aborting any ongoing Rx transfer started in Interrupt or DMA mode.
* This procedure performs following operations :
* - Disable IRDA Interrupts (Rx)
* - Disable the DMA transfer in the peripheral register (if enabled)
* - Abort DMA transfer by calling HAL_DMA_Abort_IT (in case of transfer in DMA mode)
* - Set handle State to READY
* - At abort completion, call user abort complete callback
* @note This procedure is executed in Interrupt mode, meaning that abort procedure could be
* considered as completed only when user abort complete callback is executed (not when exiting function).
* @retval HAL status
*/
HAL_StatusTypeDef HAL_IRDA_AbortReceive_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel : use non blocking DMA Abort API (callback) */
if(hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback :
will lead to call HAL_IRDA_AbortCpltCallback() at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = IRDA_DMARxOnlyAbortCallback;
/* Abort DMA RX */
if(HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK)
{
/* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */
hirda->hdmarx->XferAbortCallback(hirda->hdmarx);
}
}
else
{
/* Reset Rx transfer counter */
hirda->RxXferCount = 0;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
HAL_IRDA_AbortReceiveCpltCallback(hirda);
}
}
else
{
/* Reset Rx transfer counter */
hirda->RxXferCount = 0;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* As no DMA to be aborted, call directly user Abort complete callback */
HAL_IRDA_AbortReceiveCpltCallback(hirda);
}
return HAL_OK;
}
/**
* @brief Handle IRDA interrupt request.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda)
{
uint32_t isrflags = READ_REG(hirda->Instance->ISR);
uint32_t cr1its = READ_REG(hirda->Instance->CR1);
uint32_t cr3its;
uint32_t errorflags;
/* If no error occurs */
errorflags = (isrflags & (uint32_t)(USART_ISR_PE | USART_ISR_FE | USART_ISR_ORE | USART_ISR_NE));
if (errorflags == RESET)
{
/* IRDA in mode Receiver ---------------------------------------------------*/
if(((isrflags & USART_ISR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
IRDA_Receive_IT(hirda);
return;
}
}
/* If some errors occur */
cr3its = READ_REG(hirda->Instance->CR3);
if( (errorflags != RESET)
&& ( ((cr3its & USART_CR3_EIE) != RESET)
|| ((cr1its & (USART_CR1_RXNEIE | USART_CR1_PEIE)) != RESET)) )
{
/* IRDA parity error interrupt occurred -------------------------------------*/
if(((isrflags & USART_ISR_PE) != RESET) && ((cr1its & USART_CR1_PEIE) != RESET))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_PEF);
hirda->ErrorCode |= HAL_IRDA_ERROR_PE;
}
/* IRDA frame error interrupt occurred --------------------------------------*/
if(((isrflags & USART_ISR_FE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_FEF);
hirda->ErrorCode |= HAL_IRDA_ERROR_FE;
}
/* IRDA noise error interrupt occurred --------------------------------------*/
if(((isrflags & USART_ISR_NE) != RESET) && ((cr3its & USART_CR3_EIE) != RESET))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_NEF);
hirda->ErrorCode |= HAL_IRDA_ERROR_NE;
}
/* IRDA Over-Run interrupt occurred -----------------------------------------*/
if(((isrflags & USART_ISR_ORE) != RESET) &&
(((cr1its & USART_CR1_RXNEIE) != RESET) || ((cr3its & USART_CR3_EIE) != RESET)))
{
__HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_OREF);
hirda->ErrorCode |= HAL_IRDA_ERROR_ORE;
}
/* Call IRDA Error Call back function if need be --------------------------*/
if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE)
{
/* IRDA in mode Receiver ---------------------------------------------------*/
if(((isrflags & USART_ISR_RXNE) != RESET) && ((cr1its & USART_CR1_RXNEIE) != RESET))
{
IRDA_Receive_IT(hirda);
}
/* If Overrun error occurs, or if any error occurs in DMA mode reception,
consider error as blocking */
if (((hirda->ErrorCode & HAL_IRDA_ERROR_ORE) != RESET) ||
(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)))
{
/* Blocking error : transfer is aborted
Set the IRDA state ready to be able to start again the process,
Disable Rx Interrupts, and disable Rx DMA request, if ongoing */
IRDA_EndRxTransfer(hirda);
/* Disable the IRDA DMA Rx request if enabled */
if (HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR))
{
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* Abort the IRDA DMA Rx channel */
if(hirda->hdmarx != NULL)
{
/* Set the IRDA DMA Abort callback :
will lead to call HAL_IRDA_ErrorCallback() at end of DMA abort procedure */
hirda->hdmarx->XferAbortCallback = IRDA_DMAAbortOnError;
/* Abort DMA RX */
if(HAL_DMA_Abort_IT(hirda->hdmarx) != HAL_OK)
{
/* Call Directly hirda->hdmarx->XferAbortCallback function in case of error */
hirda->hdmarx->XferAbortCallback(hirda->hdmarx);
}
}
else
{
/* Call user error callback */
HAL_IRDA_ErrorCallback(hirda);
}
}
else
{
/* Call user error callback */
HAL_IRDA_ErrorCallback(hirda);
}
}
else
{
/* Non Blocking error : transfer could go on.
Error is notified to user through user error callback */
HAL_IRDA_ErrorCallback(hirda);
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
}
}
return;
} /* End if some error occurs */
/* IRDA in mode Transmitter ------------------------------------------------*/
if(((isrflags & USART_ISR_TXE) != RESET) && ((cr1its & USART_CR1_TXEIE) != RESET))
{
IRDA_Transmit_IT(hirda);
return;
}
/* IRDA in mode Transmitter (transmission end) -----------------------------*/
if(((isrflags & USART_ISR_TC) != RESET) && ((cr1its & USART_CR1_TCIE) != RESET))
{
IRDA_EndTransmit_IT(hirda);
return;
}
}
/**
* @brief Tx Transfer completed callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_TxCpltCallback can be implemented in the user file.
*/
}
/**
* @brief Tx Half Transfer completed callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified USART module.
* @retval None
*/
__weak void HAL_IRDA_TxHalfCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_TxHalfCpltCallback can be implemented in the user file.
*/
}
/**
* @brief Rx Transfer completed callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_RxCpltCallback can be implemented in the user file.
*/
}
/**
* @brief Rx Half Transfer complete callback.
* @param hirda: Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_RxHalfCpltCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_RxHalfCpltCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA error callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_ErrorCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA Abort Complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_AbortCpltCallback (IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_AbortCpltCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA Abort Complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_AbortTransmitCpltCallback (IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_AbortTransmitCpltCallback can be implemented in the user file.
*/
}
/**
* @brief IRDA Abort Receive Complete callback.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
__weak void HAL_IRDA_AbortReceiveCpltCallback (IRDA_HandleTypeDef *hirda)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hirda);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_IRDA_AbortReceiveCpltCallback can be implemented in the user file.
*/
}
/**
* @}
*/
/** @defgroup IRDA_Exported_Functions_Group4 Peripheral State and Error functions
* @brief IRDA State and Errors functions
*
@verbatim
==============================================================================
##### Peripheral State and Error functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to return the State of IrDA
communication process and also return Peripheral Errors occurred during communication process
(+) HAL_IRDA_GetState() API can be helpful to check in run-time the state
of the IRDA peripheral handle.
(+) HAL_IRDA_GetError() checks in run-time errors that could occur during
communication.
@endverbatim
* @{
*/
/**
* @brief Return the IRDA handle state.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL state
*/
HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda)
{
/* Return IRDA handle state */
uint32_t temp1= 0x00, temp2 = 0x00;
temp1 = hirda->gState;
temp2 = hirda->RxState;
return (HAL_IRDA_StateTypeDef)(temp1 | temp2);
}
/**
* @brief Return the IRDA handle error code.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval IRDA Error Code
*/
uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda)
{
return hirda->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup IRDA_Private_Functions IRDA Private Functions
* @{
*/
/**
* @brief Configure the IRDA peripheral.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda)
{
uint32_t tmpreg = 0x00000000;
IRDA_ClockSourceTypeDef clocksource = IRDA_CLOCKSOURCE_UNDEFINED;
HAL_StatusTypeDef ret = HAL_OK;
/* Check the communication parameters */
assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate));
assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength));
assert_param(IS_IRDA_PARITY(hirda->Init.Parity));
assert_param(IS_IRDA_TX_RX_MODE(hirda->Init.Mode));
assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler));
assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode));
/*-------------------------- USART CR1 Configuration -----------------------*/
/* Configure the IRDA Word Length, Parity and transfer Mode:
Set the M bits according to hirda->Init.WordLength value
Set PCE and PS bits according to hirda->Init.Parity value
Set TE and RE bits according to hirda->Init.Mode value */
tmpreg = (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode ;
MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg);
/*-------------------------- USART CR3 Configuration -----------------------*/
MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode);
/*-------------------------- USART GTPR Configuration ----------------------*/
MODIFY_REG(hirda->Instance->GTPR, USART_GTPR_PSC, hirda->Init.Prescaler);
/*-------------------------- USART BRR Configuration -----------------------*/
IRDA_GETCLOCKSOURCE(hirda, clocksource);
switch (clocksource)
{
case IRDA_CLOCKSOURCE_PCLK1:
hirda->Instance->BRR = (uint16_t)((HAL_RCC_GetPCLK1Freq() + (hirda->Init.BaudRate/2)) / hirda->Init.BaudRate);
break;
case IRDA_CLOCKSOURCE_PCLK2:
hirda->Instance->BRR = (uint16_t)((HAL_RCC_GetPCLK2Freq() + (hirda->Init.BaudRate/2)) / hirda->Init.BaudRate);
break;
case IRDA_CLOCKSOURCE_HSI:
hirda->Instance->BRR = (uint16_t)((HSI_VALUE + (hirda->Init.BaudRate/2)) / hirda->Init.BaudRate);
break;
case IRDA_CLOCKSOURCE_SYSCLK:
hirda->Instance->BRR = (uint16_t)((HAL_RCC_GetSysClockFreq() + (hirda->Init.BaudRate/2)) / hirda->Init.BaudRate);
break;
case IRDA_CLOCKSOURCE_LSE:
hirda->Instance->BRR = (uint16_t)((LSE_VALUE + (hirda->Init.BaudRate/2)) / hirda->Init.BaudRate);
break;
case IRDA_CLOCKSOURCE_UNDEFINED:
default:
ret = HAL_ERROR;
break;
}
return ret;
}
/**
* @brief Check the IRDA Idle State.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda)
{
uint32_t tickstart = 0;
/* Initialize the IRDA ErrorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Init tickstart for timeout managment*/
tickstart = HAL_GetTick();
/* Check if the Transmitter is enabled */
if((hirda->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE)
{
/* Wait until TEACK flag is set */
if(IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_TEACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK)
{
/* Timeout occurred */
return HAL_TIMEOUT;
}
}
/* Check if the Receiver is enabled */
if((hirda->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE)
{
/* Wait until REACK flag is set */
if(IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_REACK, RESET, tickstart, IRDA_TEACK_REACK_TIMEOUT) != HAL_OK)
{
/* Timeout occurred */
return HAL_TIMEOUT;
}
}
/* Initialize the IRDA state*/
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_OK;
}
/**
* @brief Handle IRDA Communication Timeout.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @param Flag Specifies the IRDA flag to check.
* @param Status Flag status (SET or RESET)
* @param Tickstart Tick start value
* @param Timeout Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Tickstart, uint32_t Timeout)
{
/* Wait until flag is set */
while((__HAL_IRDA_GET_FLAG(hirda, Flag) ? SET : RESET) == Status)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0) || ((HAL_GetTick()-Tickstart) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE | USART_CR1_TXEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hirda);
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @brief End ongoing Tx transfer on IRDA peripheral (following error detection or Transmit completion).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_EndTxTransfer(IRDA_HandleTypeDef *hirda)
{
/* Disable TXEIE and TCIE interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_TXEIE | USART_CR1_TCIE));
/* At end of Tx process, restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
}
/**
* @brief End ongoing Rx transfer on UART peripheral (following error detection or Reception completion).
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval None
*/
static void IRDA_EndRxTransfer(IRDA_HandleTypeDef *hirda)
{
/* Disable RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* At end of Rx process, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
}
/**
* @brief DMA IRDA transmit process complete callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
/* DMA Normal mode */
if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) )
{
hirda->TxXferCount = 0;
/* Disable the DMA transfer for transmit request by resetting the DMAT bit
in the IRDA CR3 register */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAT);
/* Enable the IRDA Transmit Complete Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE);
}
/* DMA Circular mode */
else
{
HAL_IRDA_TxCpltCallback(hirda);
}
}
/**
* @brief DMA IRDA transmit process half complete callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMATransmitHalfCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
HAL_IRDA_TxHalfCpltCallback(hirda);
}
/**
* @brief DMA IRDA receive process complete callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
/* DMA Normal mode */
if ( HAL_IS_BIT_CLR(hdma->Instance->CCR, DMA_CCR_CIRC) )
{
hirda->RxXferCount = 0;
/* Disable PE and ERR (Frame error, noise error, overrun error) interrupts */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_PEIE);
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Disable the DMA transfer for the receiver request by resetting the DMAR bit
in the IRDA CR3 register */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_DMAR);
/* At end of Rx process, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
}
HAL_IRDA_RxCpltCallback(hirda);
}
/**
* @brief DMA IRDA receive process half complete callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAReceiveHalfCplt(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
HAL_IRDA_RxHalfCpltCallback(hirda);
}
/**
* @brief DMA IRDA communication error callback.
* @param hdma Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void IRDA_DMAError(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
/* Stop IRDA DMA Tx request if ongoing */
if ( (hirda->gState == HAL_IRDA_STATE_BUSY_TX)
&&(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAT)) )
{
hirda->TxXferCount = 0;
IRDA_EndTxTransfer(hirda);
}
/* Stop IRDA DMA Rx request if ongoing */
if ( (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
&&(HAL_IS_BIT_SET(hirda->Instance->CR3, USART_CR3_DMAR)) )
{
hirda->RxXferCount = 0;
IRDA_EndRxTransfer(hirda);
}
hirda->ErrorCode |= HAL_IRDA_ERROR_DMA;
HAL_IRDA_ErrorCallback(hirda);
}
/**
* @brief DMA IRDA communication abort callback, when initiated by HAL services on Error
* (To be called at end of DMA Abort procedure following error occurrence).
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMAAbortOnError(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
hirda->RxXferCount = 0;
hirda->TxXferCount = 0;
HAL_IRDA_ErrorCallback(hirda);
}
/**
* @brief DMA IRDA Tx communication abort callback, when initiated by user
* (To be called at end of DMA Tx Abort procedure following user abort request).
* @note When this callback is executed, User Abort complete call back is called only if no
* Abort still ongoing for Rx DMA Handle.
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMATxAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef* )(hdma->Parent);
hirda->hdmatx->XferAbortCallback = NULL;
/* Check if an Abort process is still ongoing */
if(hirda->hdmarx != NULL)
{
if(hirda->hdmarx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */
hirda->TxXferCount = 0;
hirda->RxXferCount = 0;
/* Reset errorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
HAL_IRDA_AbortCpltCallback(hirda);
}
/**
* @brief DMA IRDA Rx communication abort callback, when initiated by user
* (To be called at end of DMA Rx Abort procedure following user abort request).
* @note When this callback is executed, User Abort complete call back is called only if no
* Abort still ongoing for Tx DMA Handle.
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMARxAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef* )(hdma->Parent);
hirda->hdmarx->XferAbortCallback = NULL;
/* Check if an Abort process is still ongoing */
if(hirda->hdmatx != NULL)
{
if(hirda->hdmatx->XferAbortCallback != NULL)
{
return;
}
}
/* No Abort process still ongoing : All DMA channels are aborted, call user Abort Complete callback */
hirda->TxXferCount = 0;
hirda->RxXferCount = 0;
/* Reset errorCode */
hirda->ErrorCode = HAL_IRDA_ERROR_NONE;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->gState and hirda->RxState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
hirda->RxState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
HAL_IRDA_AbortCpltCallback(hirda);
}
/**
* @brief DMA IRDA Tx communication abort callback, when initiated by user by a call to
* HAL_IRDA_AbortTransmit_IT API (Abort only Tx transfer)
* (This callback is executed at end of DMA Tx Abort procedure following user abort request,
* and leads to user Tx Abort Complete callback execution).
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMATxOnlyAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = (IRDA_HandleTypeDef*)(hdma->Parent);
hirda->TxXferCount = 0;
/* Restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
HAL_IRDA_AbortTransmitCpltCallback(hirda);
}
/**
* @brief DMA IRDA Rx communication abort callback, when initiated by user by a call to
* HAL_IRDA_AbortReceive_IT API (Abort only Rx transfer)
* (This callback is executed at end of DMA Rx Abort procedure following user abort request,
* and leads to user Rx Abort Complete callback execution).
* @param hdma DMA handle.
* @retval None
*/
static void IRDA_DMARxOnlyAbortCallback(DMA_HandleTypeDef *hdma)
{
IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
hirda->RxXferCount = 0;
/* Clear the Error flags in the ICR register */
__HAL_IRDA_CLEAR_FLAG(hirda, IRDA_CLEAR_OREF | IRDA_CLEAR_NEF | IRDA_CLEAR_PEF | IRDA_CLEAR_FEF);
/* Restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
/* Call user Abort complete callback */
HAL_IRDA_AbortReceiveCpltCallback(hirda);
}
/**
* @brief Send an amount of data in interrupt mode.
* @note Function is called under interruption only, once
* interruptions have been enabled by HAL_IRDA_Transmit_IT().
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda)
{
uint16_t* tmp;
/* Check that a Tx process is ongoing */
if(hirda->gState == HAL_IRDA_STATE_BUSY_TX)
{
if(hirda->TxXferCount == 0)
{
/* Disable the IRDA Transmit Data Register Empty Interrupt */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TXEIE);
/* Enable the IRDA Transmit Complete Interrupt */
SET_BIT(hirda->Instance->CR1, USART_CR1_TCIE);
return HAL_OK;
}
else
{
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
tmp = (uint16_t*) hirda->pTxBuffPtr;
hirda->Instance->TDR = (*tmp & (uint16_t)0x01FF);
hirda->pTxBuffPtr += 2;
}
else
{
hirda->Instance->TDR = (uint8_t)(*hirda->pTxBuffPtr++ & (uint8_t)0xFF);
}
hirda->TxXferCount--;
return HAL_OK;
}
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Wrap up transmission in non-blocking mode.
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_EndTransmit_IT(IRDA_HandleTypeDef *hirda)
{
/* Disable the IRDA Transmit Complete Interrupt */
CLEAR_BIT(hirda->Instance->CR1, USART_CR1_TCIE);
/* Tx process is ended, restore hirda->gState to Ready */
hirda->gState = HAL_IRDA_STATE_READY;
HAL_IRDA_TxCpltCallback(hirda);
return HAL_OK;
}
/**
* @brief Receive an amount of data in interrupt mode.
* @note Function is called under interruption only, once
* interruptions have been enabled by HAL_IRDA_Receive_IT()
* @param hirda Pointer to a IRDA_HandleTypeDef structure that contains
* the configuration information for the specified IRDA module.
* @retval HAL status
*/
static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda)
{
uint16_t* tmp;
uint16_t uhMask = hirda->Mask;
uint16_t uhdata;
/* Check that a Rx process is ongoing */
if (hirda->RxState == HAL_IRDA_STATE_BUSY_RX)
{
uhdata = (uint16_t) READ_REG(hirda->Instance->RDR);
if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE))
{
tmp = (uint16_t*) hirda->pRxBuffPtr ;
*tmp = (uint16_t)(uhdata & uhMask);
hirda->pRxBuffPtr +=2;
}
else
{
*hirda->pRxBuffPtr++ = (uint8_t)(uhdata & (uint8_t)uhMask);
}
if(--hirda->RxXferCount == 0)
{
/* Disable the IRDA Parity Error Interrupt and RXNE interrupt */
CLEAR_BIT(hirda->Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));
/* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */
CLEAR_BIT(hirda->Instance->CR3, USART_CR3_EIE);
/* Rx process is completed, restore hirda->RxState to Ready */
hirda->RxState = HAL_IRDA_STATE_READY;
HAL_IRDA_RxCpltCallback(hirda);
return HAL_OK;
}
return HAL_OK;
}
else
{
/* Clear RXNE interrupt flag */
__HAL_IRDA_SEND_REQ(hirda, IRDA_RXDATA_FLUSH_REQUEST);
return HAL_BUSY;
}
}
/**
* @}
*/
#endif /* HAL_IRDA_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
Parkjihooni6186/TizenRT | external/libcoap/option.c | 22 | 11473 | /****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/*
* option.c -- helpers for handling options in CoAP PDUs
*
* Copyright (C) 2010-2013 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include <protocols/libcoap/config.h>
#if defined(HAVE_ASSERT_H) && !defined(assert)
#include <assert.h>
#endif
#include <stdio.h>
#include <string.h>
#include <protocols/libcoap/option.h>
#include <protocols/libcoap/debug.h>
coap_opt_t *options_start(coap_pdu_t *pdu, coap_transport_t transport)
{
if (pdu && pdu->hdr) {
if (COAP_UDP == transport &&
(pdu->transport_hdr->udp.token + pdu->transport_hdr->udp.token_length < (unsigned char *)pdu->hdr + pdu->length)) {
coap_opt_t *opt = pdu->transport_hdr->udp.token + pdu->transport_hdr->udp.token_length;
return (*opt == COAP_PAYLOAD_START) ? NULL : opt;
}
#ifdef WITH_TCP
else if (COAP_TCP == transport &&
(pdu->transport_hdr->tcp.token + ((pdu->transport_hdr->tcp.header_data[0]) & 0x0f)
< (unsigned char *)pdu->hdr + pdu->length)) {
coap_opt_t *opt = pdu->transport_hdr->tcp.token + ((pdu->transport_hdr->tcp.header_data[0]) & 0x0f);
return (*opt == COAP_PAYLOAD_START) ? NULL : opt;
}
#endif
return NULL;
} else {
return NULL;
}
}
size_t coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *result)
{
const coap_opt_t *opt_start = opt; /* store where parsing starts */
assert(opt);
assert(result);
#define ADVANCE_OPT(o,e,step) if ((e) < step) { \
debug("cannot advance opt past end\n"); \
return 0; \
} else { \
(e) -= step; \
(o) = ((unsigned char *)(o)) + step; \
}
if (length < 1) {
return 0;
}
result->delta = (*opt & 0xf0) >> 4;
result->length = *opt & 0x0f;
switch (result->delta) {
case 15:
if (*opt != COAP_PAYLOAD_START) {
debug("ignored reserved option delta 15\n");
}
return 0;
case 14:
/* Handle two-byte value: First, the MSB + 269 is stored as delta value.
* After that, the option pointer is advanced to the LSB which is handled
* just like case delta == 13. */
ADVANCE_OPT(opt, length, 1);
result->delta = ((*opt & 0xff) << 8) + 269;
if (result->delta < 269) {
debug("delta too large\n");
return 0;
}
/* fall through */
case 13:
ADVANCE_OPT(opt, length, 1);
result->delta += *opt & 0xff;
break;
default:
;
}
switch (result->length) {
case 15:
debug("found reserved option length 15\n");
return 0;
case 14:
/* Handle two-byte value: First, the MSB + 269 is stored as delta value.
* After that, the option pointer is advanced to the LSB which is handled
* just like case delta == 13. */
ADVANCE_OPT(opt, length, 1);
result->length = ((*opt & 0xff) << 8) + 269;
/* fall through */
case 13:
ADVANCE_OPT(opt, length, 1);
result->length += *opt & 0xff;
break;
default:
;
}
ADVANCE_OPT(opt, length, 1);
/* opt now points to value, if present */
result->value = (unsigned char *)opt;
if (length < result->length) {
debug("invalid option length\n");
return 0;
}
#undef ADVANCE_OPT
return (opt + result->length) - opt_start;
}
coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t filter)
{
return coap_option_iterator_init2(pdu, oi, filter, COAP_UDP);
}
coap_opt_iterator_t *coap_option_iterator_init2(coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t filter, coap_transport_t transport)
{
assert(pdu);
assert(pdu->hdr);
assert(oi);
memset(oi, 0, sizeof(coap_opt_iterator_t));
unsigned int token_length;
unsigned int headerSize;
switch (transport) {
case COAP_UDP:
token_length = (pdu->transport_hdr->udp.token_length);
headerSize = COAP_UDP_HEADER;
break;
#ifdef WITH_TCP
case COAP_TCP:
token_length = (pdu->transport_hdr->tcp.header_data[0]) & 0x0f;
headerSize = COAP_TCP_HEADER_NO_FIELD;
break;
case COAP_TCP_8BIT:
token_length = (pdu->transport_hdr->tcp_8bit.header_data[0]) & 0x0f;
headerSize = COAP_TCP_HEADER_8_BIT;
break;
case COAP_TCP_16BIT:
token_length = (pdu->transport_hdr->tcp_16bit.header_data[0]) & 0x0f;
headerSize = COAP_TCP_HEADER_16_BIT;
break;
case COAP_TCP_32BIT:
token_length = pdu->transport_hdr->tcp_32bit.header_data[0] & 0x0f;
headerSize = COAP_TCP_HEADER_32_BIT;
break;
#endif
default:
token_length = pdu->transport_hdr->udp.token_length;
headerSize = sizeof(pdu->transport_hdr->udp);
break;
}
oi->next_option = (unsigned char *)pdu->hdr + headerSize + token_length;
if (COAP_UDP == transport) {
if ((unsigned char *)&(pdu->transport_hdr->udp) + pdu->length <= oi->next_option) {
oi->bad = 1;
return NULL;
}
}
#ifdef WITH_TCP
else {
if ((unsigned char *)&(pdu->transport_hdr->tcp) + pdu->length <= oi->next_option) {
oi->bad = 1;
return NULL;
}
}
#endif
if ((headerSize + token_length) > pdu->length) {
//assert((headerSize + token_length) <= pdu->length);
printf("coap_option_iterator_init2 : invalid length of pdu, headerSize %d token_length %d pdu->length %d\n", headerSize, token_length, pdu->length);
return NULL;
}
oi->length = pdu->length - (headerSize + token_length);
if (filter) {
memcpy(oi->filter, filter, sizeof(coap_opt_filter_t));
oi->filtered = 1;
}
return oi;
}
static inline int opt_finished(coap_opt_iterator_t *oi)
{
assert(oi);
if (oi->bad || oi->length == 0 || !oi->next_option || *oi->next_option == COAP_PAYLOAD_START) {
oi->bad = 1;
}
return oi->bad;
}
coap_opt_t *coap_option_next(coap_opt_iterator_t *oi)
{
coap_option_t option;
coap_opt_t *current_opt = NULL;
size_t optsize;
int b; /* to store result of coap_option_getb() */
assert(oi);
if (opt_finished(oi)) {
return NULL;
}
while (1) {
/* oi->option always points to the next option to deliver; as
* opt_finished() filters out any bad conditions, we can assume that
* oi->option is valid. */
current_opt = oi->next_option;
/* Advance internal pointer to next option, skipping any option that
* is not included in oi->filter. */
optsize = coap_opt_parse(oi->next_option, oi->length, &option);
if (optsize) {
assert(optsize <= oi->length);
oi->next_option += optsize;
oi->length -= optsize;
oi->type += option.delta;
} else { /* current option is malformed */
oi->bad = 1;
return NULL;
}
/* Exit the while loop when:
* - no filtering is done at all
* - the filter matches for the current option
* - the filter is too small for the current option number
*/
if (!oi->filtered || (b = coap_option_getb(oi->filter, oi->type)) > 0) {
break;
} else if (b < 0) { /* filter too small, cannot proceed */
oi->bad = 1;
return NULL;
}
}
return current_opt;
}
coap_opt_t *coap_check_option2(coap_pdu_t *pdu, unsigned char type, coap_opt_iterator_t *oi, coap_transport_t transport)
{
coap_opt_filter_t f;
coap_option_filter_clear(f);
coap_option_setb(f, type);
coap_option_iterator_init2(pdu, oi, f, transport);
return coap_option_next(oi);
}
coap_opt_t *coap_check_option(coap_pdu_t *pdu, unsigned char type, coap_opt_iterator_t *oi)
{
return coap_check_option2(pdu, type, oi, COAP_UDP);
}
unsigned short coap_opt_delta(const coap_opt_t *opt)
{
unsigned short n;
n = (*opt++ & 0xf0) >> 4;
switch (n) {
case 15: /* error */
warn("coap_opt_delta: illegal option delta\n");
/* This case usually should not happen, hence we do not have a
* proper way to indicate an error. */
return 0;
case 14:
/* Handle two-byte value: First, the MSB + 269 is stored as delta value.
* After that, the option pointer is advanced to the LSB which is handled
* just like case delta == 13. */
n = ((*opt++ & 0xff) << 8) + 269;
/* fall through */
case 13:
n += *opt & 0xff;
break;
default: /* n already contains the actual delta value */
;
}
return n;
}
unsigned short coap_opt_length(const coap_opt_t *opt)
{
unsigned short length;
length = *opt & 0x0f;
switch (*opt & 0xf0) {
case 0xf0:
debug("illegal option delta\n");
return 0;
case 0xe0:
++opt;
/* fall through to skip another byte */
case 0xd0:
++opt;
/* fall through to skip another byte */
default:
++opt;
}
switch (length) {
case 0x0f:
debug("illegal option length\n");
return 0;
case 0x0e:
length = (*opt++ << 8) + 269;
/* fall through */
case 0x0d:
length += *opt++;
break;
default:
;
}
return length;
}
unsigned char *coap_opt_value(coap_opt_t *opt)
{
size_t ofs = 1;
switch (*opt & 0xf0) {
case 0xf0:
debug("illegal option delta\n");
return 0;
case 0xe0:
++ofs;
/* fall through */
case 0xd0:
++ofs;
break;
default:
;
}
switch (*opt & 0x0f) {
case 0x0f:
debug("illegal option length\n");
return 0;
case 0x0e:
++ofs;
/* fall through */
case 0x0d:
++ofs;
break;
default:
;
}
return (unsigned char *)opt + ofs;
}
size_t coap_opt_size(const coap_opt_t *opt)
{
coap_option_t option;
/* we must assume that opt is encoded correctly */
return coap_opt_parse(opt, (size_t) - 1, &option);
}
size_t coap_opt_setheader(coap_opt_t *opt, size_t maxlen, unsigned short delta, size_t length)
{
size_t skip = 0;
assert(opt);
if (maxlen == 0) { /* need at least one byte */
return 0;
}
if (delta < 13) {
opt[0] = delta << 4;
} else if (delta < 270) {
if (maxlen < 2) {
debug("insufficient space to encode option delta %d", delta);
return 0;
}
opt[0] = 0xd0;
opt[++skip] = delta - 13;
} else {
if (maxlen < 3) {
debug("insufficient space to encode option delta %d", delta);
return 0;
}
opt[0] = 0xe0;
opt[++skip] = ((delta - 269) >> 8) & 0xff;
opt[++skip] = (delta - 269) & 0xff;
}
if (length < 13) {
opt[0] |= length & 0x0f;
} else if (length < 270) {
if (maxlen < skip + 1) {
debug("insufficient space to encode option length %d", length);
return 0;
}
opt[0] |= 0x0d;
opt[++skip] = length - 13;
} else {
if (maxlen < skip + 2) {
debug("insufficient space to encode option delta %d", delta);
return 0;
}
opt[0] |= 0x0e;
opt[++skip] = ((length - 269) >> 8) & 0xff;
opt[++skip] = (length - 269) & 0xff;
}
return skip + 1;
}
size_t coap_opt_encode(coap_opt_t *opt, size_t maxlen, unsigned short delta, const unsigned char *val, size_t length)
{
size_t l = 1;
l = coap_opt_setheader(opt, maxlen, delta, length);
assert(l <= maxlen);
if (!l) {
debug("coap_opt_encode: cannot set option header\n");
return 0;
}
maxlen -= l;
opt += l;
if (maxlen < length) {
debug("coap_opt_encode: option too large for buffer\n");
return 0;
}
if (val) { /* better be safe here */
memcpy(opt, val, length);
}
return l + length;
}
| apache-2.0 |
catiedev/mbed-os | targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_KL43Z/drivers/fsl_gpio.c | 535 | 5670 | /*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of Freescale Semiconductor, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fsl_gpio.h"
/*******************************************************************************
* Variables
******************************************************************************/
static PORT_Type *const s_portBases[] = PORT_BASE_PTRS;
static GPIO_Type *const s_gpioBases[] = GPIO_BASE_PTRS;
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief Gets the GPIO instance according to the GPIO base
*
* @param base GPIO peripheral base pointer(PTA, PTB, PTC, etc.)
* @retval GPIO instance
*/
static uint32_t GPIO_GetInstance(GPIO_Type *base);
/*******************************************************************************
* Code
******************************************************************************/
static uint32_t GPIO_GetInstance(GPIO_Type *base)
{
uint32_t instance;
/* Find the instance index from base address mappings. */
for (instance = 0; instance < FSL_FEATURE_SOC_GPIO_COUNT; instance++)
{
if (s_gpioBases[instance] == base)
{
break;
}
}
assert(instance < FSL_FEATURE_SOC_GPIO_COUNT);
return instance;
}
void GPIO_PinInit(GPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config)
{
assert(config);
if (config->pinDirection == kGPIO_DigitalInput)
{
base->PDDR &= ~(1U << pin);
}
else
{
GPIO_WritePinOutput(base, pin, config->outputLogic);
base->PDDR |= (1U << pin);
}
}
uint32_t GPIO_GetPinsInterruptFlags(GPIO_Type *base)
{
uint8_t instance;
PORT_Type *portBase;
instance = GPIO_GetInstance(base);
portBase = s_portBases[instance];
return portBase->ISFR;
}
void GPIO_ClearPinsInterruptFlags(GPIO_Type *base, uint32_t mask)
{
uint8_t instance;
PORT_Type *portBase;
instance = GPIO_GetInstance(base);
portBase = s_portBases[instance];
portBase->ISFR = mask;
}
#if defined(FSL_FEATURE_SOC_FGPIO_COUNT) && FSL_FEATURE_SOC_FGPIO_COUNT
/*******************************************************************************
* Variables
******************************************************************************/
static FGPIO_Type *const s_fgpioBases[] = FGPIO_BASE_PTRS;
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief Gets the FGPIO instance according to the GPIO base
*
* @param base FGPIO peripheral base pointer(PTA, PTB, PTC, etc.)
* @retval FGPIO instance
*/
static uint32_t FGPIO_GetInstance(FGPIO_Type *base);
/*******************************************************************************
* Code
******************************************************************************/
static uint32_t FGPIO_GetInstance(FGPIO_Type *base)
{
uint32_t instance;
/* Find the instance index from base address mappings. */
for (instance = 0; instance < FSL_FEATURE_SOC_FGPIO_COUNT; instance++)
{
if (s_fgpioBases[instance] == base)
{
break;
}
}
assert(instance < FSL_FEATURE_SOC_FGPIO_COUNT);
return instance;
}
void FGPIO_PinInit(FGPIO_Type *base, uint32_t pin, const gpio_pin_config_t *config)
{
assert(config);
if (config->pinDirection == kGPIO_DigitalInput)
{
base->PDDR &= ~(1U << pin);
}
else
{
FGPIO_WritePinOutput(base, pin, config->outputLogic);
base->PDDR |= (1U << pin);
}
}
uint32_t FGPIO_GetPinsInterruptFlags(FGPIO_Type *base)
{
uint8_t instance;
instance = FGPIO_GetInstance(base);
PORT_Type *portBase;
portBase = s_portBases[instance];
return portBase->ISFR;
}
void FGPIO_ClearPinsInterruptFlags(FGPIO_Type *base, uint32_t mask)
{
uint8_t instance;
instance = FGPIO_GetInstance(base);
PORT_Type *portBase;
portBase = s_portBases[instance];
portBase->ISFR = mask;
}
#endif /* FSL_FEATURE_SOC_FGPIO_COUNT */
| apache-2.0 |
spxtr/bazel | third_party/grpc/src/core/iomgr/closure.c | 24 | 3292 | /*
*
* Copyright 2015-2016, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "src/core/iomgr/closure.h"
#include <grpc/support/alloc.h>
void grpc_closure_init(grpc_closure *closure, grpc_iomgr_cb_func cb,
void *cb_arg) {
closure->cb = cb;
closure->cb_arg = cb_arg;
closure->final_data = 0;
}
void grpc_closure_list_add(grpc_closure_list *closure_list,
grpc_closure *closure, bool success) {
if (closure == NULL) return;
closure->final_data = (success != 0);
if (closure_list->head == NULL) {
closure_list->head = closure;
} else {
closure_list->tail->final_data |= (uintptr_t)closure;
}
closure_list->tail = closure;
}
bool grpc_closure_list_empty(grpc_closure_list closure_list) {
return closure_list.head == NULL;
}
void grpc_closure_list_move(grpc_closure_list *src, grpc_closure_list *dst) {
if (src->head == NULL) {
return;
}
if (dst->head == NULL) {
*dst = *src;
} else {
dst->tail->final_data |= (uintptr_t)src->head;
dst->tail = src->tail;
}
src->head = src->tail = NULL;
}
typedef struct {
grpc_iomgr_cb_func cb;
void *cb_arg;
grpc_closure wrapper;
} wrapped_closure;
static void closure_wrapper(grpc_exec_ctx *exec_ctx, void *arg, bool success) {
wrapped_closure *wc = arg;
grpc_iomgr_cb_func cb = wc->cb;
void *cb_arg = wc->cb_arg;
gpr_free(wc);
cb(exec_ctx, cb_arg, success);
}
grpc_closure *grpc_closure_create(grpc_iomgr_cb_func cb, void *cb_arg) {
wrapped_closure *wc = gpr_malloc(sizeof(*wc));
wc->cb = cb;
wc->cb_arg = cb_arg;
grpc_closure_init(&wc->wrapper, closure_wrapper, wc);
return &wc->wrapper;
}
grpc_closure *grpc_closure_next(grpc_closure *closure) {
return (grpc_closure *)(closure->final_data & ~(uintptr_t)1);
}
| apache-2.0 |
jhonj624/CTK | Libs/DICOM/Core/Testing/Cpp/ctkDICOMTesterTest2.cpp | 24 | 1506 | /*=========================================================================
Library: CTK
Copyright (c) Kitware 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.txt
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.
=========================================================================*/
// Qt includes
#include <QCoreApplication>
#include <QStringList>
// ctkDICOMCore includes
#include "ctkDICOMTester.h"
// STD includes
#include <iostream>
#include <cstdlib>
void ctkDICOMTesterTest2PrintUsage()
{
std::cout << " ctkDICOMTesterTest2 images" << std::endl;
}
int ctkDICOMTesterTest2(int argc, char * argv [])
{
QCoreApplication app(argc, argv);
QStringList arguments = app.arguments();
arguments.pop_front();
if (!arguments.count())
{
ctkDICOMTesterTest2PrintUsage();
return EXIT_FAILURE;
}
ctkDICOMTester tester;
tester.startDCMQRSCP();
bool res = tester.storeData(arguments);
if (!res)
{
std::cout << "Can't store data" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| apache-2.0 |
theom/otp | erts/emulator/beam/beam_debug.c | 26 | 17674 | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 1998-2013. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* %CopyrightEnd%
*/
/*
* Purpose: Basic debugging support.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "sys.h"
#include "erl_vm.h"
#include "global.h"
#include "erl_process.h"
#include "error.h"
#include "erl_driver.h"
#include "bif.h"
#include "big.h"
#include "external.h"
#include "beam_load.h"
#include "beam_bp.h"
#include "erl_binary.h"
#include "erl_thr_progress.h"
#ifdef ARCH_64
# define HEXF "%016bpX"
#else
# define HEXF "%08bpX"
#endif
#define TermWords(t) (((t) / (sizeof(BeamInstr)/sizeof(Eterm))) + !!((t) % (sizeof(BeamInstr)/sizeof(Eterm))))
void dbg_bt(Process* p, Eterm* sp);
void dbg_where(BeamInstr* addr, Eterm x0, Eterm* reg);
static int print_op(int to, void *to_arg, int op, int size, BeamInstr* addr);
BIF_RETTYPE
erts_debug_same_2(BIF_ALIST_2)
{
return (BIF_ARG_1 == BIF_ARG_2) ? am_true : am_false;
}
BIF_RETTYPE
erts_debug_flat_size_1(BIF_ALIST_1)
{
Process* p = BIF_P;
Eterm term = BIF_ARG_1;
Uint size = size_object(term);
if (IS_USMALL(0, size)) {
BIF_RET(make_small(size));
} else {
Eterm* hp = HAlloc(p, BIG_UINT_HEAP_SIZE);
BIF_RET(uint_to_big(size, hp));
}
}
BIF_RETTYPE
erts_debug_breakpoint_2(BIF_ALIST_2)
{
Process* p = BIF_P;
Eterm MFA = BIF_ARG_1;
Eterm bool = BIF_ARG_2;
Eterm* tp;
Eterm mfa[3];
int i;
int specified = 0;
Eterm res;
BpFunctions f;
if (bool != am_true && bool != am_false)
goto error;
if (is_not_tuple(MFA)) {
goto error;
}
tp = tuple_val(MFA);
if (*tp != make_arityval(3)) {
goto error;
}
mfa[0] = tp[1];
mfa[1] = tp[2];
mfa[2] = tp[3];
if (!is_atom(mfa[0]) || !is_atom(mfa[1]) ||
(!is_small(mfa[2]) && mfa[2] != am_Underscore)) {
goto error;
}
for (i = 0; i < 3 && mfa[i] != am_Underscore; i++, specified++) {
/* Empty loop body */
}
for (i = specified; i < 3; i++) {
if (mfa[i] != am_Underscore) {
goto error;
}
}
if (is_small(mfa[2])) {
mfa[2] = signed_val(mfa[2]);
}
if (!erts_try_seize_code_write_permission(BIF_P)) {
ERTS_BIF_YIELD2(bif_export[BIF_erts_debug_breakpoint_2],
BIF_P, BIF_ARG_1, BIF_ARG_2);
}
erts_smp_proc_unlock(p, ERTS_PROC_LOCK_MAIN);
erts_smp_thr_progress_block();
erts_bp_match_functions(&f, mfa, specified);
if (bool == am_true) {
erts_set_debug_break(&f);
erts_install_breakpoints(&f);
erts_commit_staged_bp();
} else {
erts_clear_debug_break(&f);
erts_commit_staged_bp();
erts_uninstall_breakpoints(&f);
}
erts_consolidate_bp_data(&f, 1);
res = make_small(f.matched);
erts_bp_free_matched_functions(&f);
erts_smp_thr_progress_unblock();
erts_smp_proc_lock(p, ERTS_PROC_LOCK_MAIN);
erts_release_code_write_permission();
return res;
error:
BIF_ERROR(p, BADARG);
}
#if 0 /* Kept for conveninence when hard debugging. */
void debug_dump_code(BeamInstr *I, int num)
{
BeamInstr *code_ptr = I;
BeamInstr *end = code_ptr + num;
erts_dsprintf_buf_t *dsbufp;
BeamInstr instr;
int i;
dsbufp = erts_create_tmp_dsbuf(0);
while (code_ptr < end) {
erts_print(ERTS_PRINT_DSBUF, (void *) dsbufp, HEXF ": ", code_ptr);
instr = (BeamInstr) code_ptr[0];
for (i = 0; i < NUM_SPECIFIC_OPS; i++) {
if (instr == (BeamInstr) BeamOp(i) && opc[i].name[0] != '\0') {
code_ptr += print_op(ERTS_PRINT_DSBUF, (void *) dsbufp,
i, opc[i].sz-1, code_ptr+1) + 1;
break;
}
}
if (i >= NUM_SPECIFIC_OPS) {
erts_print(ERTS_PRINT_DSBUF, (void *) dsbufp,
"unknown " HEXF "\n", instr);
code_ptr++;
}
}
dsbufp->str[dsbufp->str_len] = 0;
erts_fprintf(stderr,"%s", dsbufp->str);
erts_destroy_tmp_dsbuf(dsbufp);
}
#endif
BIF_RETTYPE
erts_debug_instructions_0(BIF_ALIST_0)
{
int i = 0;
Uint needed = num_instructions * 2;
Eterm* hp;
Eterm res = NIL;
for (i = 0; i < num_instructions; i++) {
needed += 2*strlen(opc[i].name);
}
hp = HAlloc(BIF_P, needed);
for (i = num_instructions-1; i >= 0; i--) {
Eterm s = erts_bld_string_n(&hp, 0, opc[i].name, strlen(opc[i].name));
res = erts_bld_cons(&hp, 0, s, res);
}
return res;
}
BIF_RETTYPE
erts_debug_disassemble_1(BIF_ALIST_1)
{
Process* p = BIF_P;
Eterm addr = BIF_ARG_1;
erts_dsprintf_buf_t *dsbufp;
Eterm* hp;
Eterm* tp;
Eterm bin;
Eterm mfa;
BeamInstr* funcinfo = NULL; /* Initialized to eliminate warning. */
BeamInstr* code_base;
BeamInstr* code_ptr = NULL; /* Initialized to eliminate warning. */
BeamInstr instr;
BeamInstr uaddr;
Uint hsz;
int i;
if (term_to_UWord(addr, &uaddr)) {
code_ptr = (BeamInstr *) uaddr;
if ((funcinfo = find_function_from_pc(code_ptr)) == NULL) {
BIF_RET(am_false);
}
} else if (is_tuple(addr)) {
ErtsCodeIndex code_ix;
Module* modp;
Eterm mod;
Eterm name;
Export* ep;
Sint arity;
int n;
tp = tuple_val(addr);
if (tp[0] != make_arityval(3)) {
error:
BIF_ERROR(p, BADARG);
}
mod = tp[1];
name = tp[2];
if (!is_atom(mod) || !is_atom(name) || !is_small(tp[3])) {
goto error;
}
arity = signed_val(tp[3]);
code_ix = erts_active_code_ix();
modp = erts_get_module(mod, code_ix);
/*
* Try the export entry first to allow disassembly of special functions
* such as erts_debug:apply/4. Then search for it in the module.
*/
if ((ep = erts_find_function(mod, name, arity, code_ix)) != NULL) {
/* XXX: add "&& ep->address != ep->code+3" condition?
* Consider a traced function.
* Its ep will have ep->address == ep->code+3.
* erts_find_function() will return the non-NULL ep.
* Below we'll try to derive a code_ptr from ep->address.
* But this code_ptr will point to the start of the Export,
* not the function's func_info instruction. BOOM !?
*/
code_ptr = ((BeamInstr *) ep->addressv[code_ix]) - 5;
funcinfo = code_ptr+2;
} else if (modp == NULL || (code_base = modp->curr.code) == NULL) {
BIF_RET(am_undef);
} else {
n = code_base[MI_NUM_FUNCTIONS];
for (i = 0; i < n; i++) {
code_ptr = (BeamInstr *) code_base[MI_FUNCTIONS+i];
if (code_ptr[3] == name && code_ptr[4] == arity) {
funcinfo = code_ptr+2;
break;
}
}
if (i == n) {
BIF_RET(am_undef);
}
}
} else {
goto error;
}
dsbufp = erts_create_tmp_dsbuf(0);
erts_print(ERTS_PRINT_DSBUF, (void *) dsbufp, HEXF ": ", code_ptr);
instr = (BeamInstr) code_ptr[0];
for (i = 0; i < NUM_SPECIFIC_OPS; i++) {
if (instr == (BeamInstr) BeamOp(i) && opc[i].name[0] != '\0') {
code_ptr += print_op(ERTS_PRINT_DSBUF, (void *) dsbufp,
i, opc[i].sz-1, code_ptr+1) + 1;
break;
}
}
if (i >= NUM_SPECIFIC_OPS) {
erts_print(ERTS_PRINT_DSBUF, (void *) dsbufp,
"unknown " HEXF "\n", instr);
code_ptr++;
}
bin = new_binary(p, (byte *) dsbufp->str, dsbufp->str_len);
erts_destroy_tmp_dsbuf(dsbufp);
hsz = 4+4;
(void) erts_bld_uword(NULL, &hsz, (BeamInstr) code_ptr);
hp = HAlloc(p, hsz);
addr = erts_bld_uword(&hp, NULL, (BeamInstr) code_ptr);
ASSERT(is_atom(funcinfo[0]) || funcinfo[0] == NIL);
ASSERT(is_atom(funcinfo[1]) || funcinfo[1] == NIL);
mfa = TUPLE3(hp, (Eterm) funcinfo[0], (Eterm) funcinfo[1], make_small((Eterm) funcinfo[2]));
hp += 4;
return TUPLE3(hp, addr, bin, mfa);
}
void
dbg_bt(Process* p, Eterm* sp)
{
Eterm* stack = STACK_START(p);
while (sp < stack) {
if (is_CP(*sp)) {
BeamInstr* addr = find_function_from_pc(cp_val(*sp));
if (addr)
erts_fprintf(stderr,
HEXF ": %T:%T/%bpu\n",
addr, (Eterm) addr[0], (Eterm) addr[1], addr[2]);
}
sp++;
}
}
void
dbg_where(BeamInstr* addr, Eterm x0, Eterm* reg)
{
BeamInstr* f = find_function_from_pc(addr);
if (f == NULL) {
erts_fprintf(stderr, "???\n");
} else {
int arity;
int i;
addr = f;
arity = addr[2];
erts_fprintf(stderr, HEXF ": %T:%T(", addr, (Eterm) addr[0], (Eterm) addr[1]);
for (i = 0; i < arity; i++)
erts_fprintf(stderr, i ? ", %T" : "%T", i ? reg[i] : x0);
erts_fprintf(stderr, ")\n");
}
}
static int
print_op(int to, void *to_arg, int op, int size, BeamInstr* addr)
{
int i;
BeamInstr tag;
char* sign;
char* start_prog; /* Start of program for packer. */
char* prog; /* Current position in packer program. */
BeamInstr stack[8]; /* Stack for packer. */
BeamInstr* sp = stack; /* Points to next free position. */
BeamInstr packed = 0; /* Accumulator for packed operations. */
BeamInstr args[8]; /* Arguments for this instruction. */
BeamInstr* ap; /* Pointer to arguments. */
BeamInstr* unpacked; /* Unpacked arguments */
start_prog = opc[op].pack;
if (start_prog[0] == '\0') {
/*
* There is no pack program.
* Avoid copying because instructions containing bignum operands
* are bigger than actually declared.
*/
ap = (BeamInstr *) addr;
} else {
/*
* Copy all arguments to a local buffer for the unpacking.
*/
ASSERT(size <= sizeof(args)/sizeof(args[0]));
ap = args;
for (i = 0; i < size; i++) {
*ap++ = addr[i];
}
/*
* Undo any packing done by the loader. This is easily done by running
* the packing program backwards and in reverse.
*/
prog = start_prog + strlen(start_prog);
while (start_prog < prog) {
prog--;
switch (*prog) {
case 'g':
*ap++ = *--sp;
break;
case 'i': /* Initialize packing accumulator. */
*ap++ = packed;
break;
case 's':
*ap++ = packed & 0x3ff;
packed >>= 10;
break;
case '0': /* Tight shift */
*ap++ = packed & (BEAM_TIGHT_MASK / sizeof(Eterm));
packed >>= BEAM_TIGHT_SHIFT;
break;
case '6': /* Shift 16 steps */
*ap++ = packed & BEAM_LOOSE_MASK;
packed >>= BEAM_LOOSE_SHIFT;
break;
#ifdef ARCH_64
case 'w': /* Shift 32 steps */
*ap++ = packed & BEAM_WIDE_MASK;
packed >>= BEAM_WIDE_SHIFT;
break;
#endif
case 'p':
*sp++ = *--ap;
break;
case 'P':
packed = *--sp;
break;
default:
ASSERT(0);
}
}
ap = args;
}
/*
* Print the name and all operands of the instructions.
*/
erts_print(to, to_arg, "%s ", opc[op].name);
sign = opc[op].sign;
while (*sign) {
switch (*sign) {
case 'r': /* x(0) */
erts_print(to, to_arg, "x(0)");
break;
case 'x': /* x(N) */
if (reg_index(ap[0]) == 0) {
erts_print(to, to_arg, "x[0]");
} else {
erts_print(to, to_arg, "x(%d)", reg_index(ap[0]));
}
ap++;
break;
case 'y': /* y(N) */
erts_print(to, to_arg, "y(%d)", reg_index(ap[0]) - CP_SIZE);
ap++;
break;
case 'n': /* Nil */
erts_print(to, to_arg, "[]");
break;
case 's': /* Any source (tagged constant or register) */
tag = beam_reg_tag(*ap);
if (tag == X_REG_DEF) {
if (reg_index(*ap) == 0) {
erts_print(to, to_arg, "x[0]");
} else {
erts_print(to, to_arg, "x(%d)", reg_index(*ap));
}
ap++;
break;
} else if (tag == Y_REG_DEF) {
erts_print(to, to_arg, "y(%d)", reg_index(*ap) - CP_SIZE);
ap++;
break;
} else if (tag == R_REG_DEF) {
erts_print(to, to_arg, "x(0)");
ap++;
break;
}
/*FALLTHROUGH*/
case 'a': /* Tagged atom */
case 'i': /* Tagged integer */
case 'c': /* Tagged constant */
case 'q': /* Tagged literal */
erts_print(to, to_arg, "%T", (Eterm) *ap);
ap++;
break;
case 'A':
erts_print(to, to_arg, "%d", arityval( (Eterm) ap[0]));
ap++;
break;
case 'd': /* Destination (x(0), x(N), y(N)) */
switch (beam_reg_tag(*ap)) {
case X_REG_DEF:
if (reg_index(*ap) == 0) {
erts_print(to, to_arg, "x[0]");
} else {
erts_print(to, to_arg, "x(%d)", reg_index(*ap));
}
break;
case Y_REG_DEF:
erts_print(to, to_arg, "y(%d)", reg_index(*ap) - CP_SIZE);
break;
case R_REG_DEF:
erts_print(to, to_arg, "x(0)");
break;
}
ap++;
break;
case 'I': /* Untagged integer. */
case 't':
erts_print(to, to_arg, "%d", *ap);
ap++;
break;
case 'f': /* Destination label */
{
BeamInstr* f = find_function_from_pc((BeamInstr *)*ap);
if (f+3 != (BeamInstr *) *ap) {
erts_print(to, to_arg, "f(" HEXF ")", *ap);
} else {
erts_print(to, to_arg, "%T:%T/%bpu", (Eterm) f[0], (Eterm) f[1], f[2]);
}
ap++;
}
break;
case 'p': /* Pointer (to label) */
{
BeamInstr* f = find_function_from_pc((BeamInstr *)*ap);
if (f+3 != (BeamInstr *) *ap) {
erts_print(to, to_arg, "p(" HEXF ")", *ap);
} else {
erts_print(to, to_arg, "%T:%T/%bpu", (Eterm) f[0], (Eterm) f[1], f[2]);
}
ap++;
}
break;
case 'j': /* Pointer (to label) */
erts_print(to, to_arg, "j(" HEXF ")", *ap);
ap++;
break;
case 'e': /* Export entry */
{
Export* ex = (Export *) *ap;
erts_print(to, to_arg,
"%T:%T/%bpu", (Eterm) ex->code[0], (Eterm) ex->code[1], ex->code[2]);
ap++;
}
break;
case 'F': /* Function definition */
break;
case 'b':
for (i = 0; i < BIF_SIZE; i++) {
BifFunction bif = (BifFunction) *ap;
if (bif == bif_table[i].f) {
break;
}
}
if (i == BIF_SIZE) {
erts_print(to, to_arg, "b(%d)", (Uint) *ap);
} else {
Eterm name = bif_table[i].name;
unsigned arity = bif_table[i].arity;
erts_print(to, to_arg, "%T/%u", name, arity);
}
ap++;
break;
case 'P': /* Byte offset into tuple (see beam_load.c) */
case 'Q': /* Like 'P', but packable */
erts_print(to, to_arg, "%d", (*ap / sizeof(Eterm)) - 1);
ap++;
break;
case 'l': /* fr(N) */
erts_print(to, to_arg, "fr(%d)", reg_index(ap[0]));
ap++;
break;
default:
erts_print(to, to_arg, "???");
ap++;
break;
}
erts_print(to, to_arg, " ");
sign++;
}
/*
* Print more information about certain instructions.
*/
unpacked = ap;
ap = addr + size;
switch (op) {
case op_i_select_val_lins_rfI:
case op_i_select_val_lins_xfI:
case op_i_select_val_lins_yfI:
{
int n = ap[-1];
int ix = n;
while (ix--) {
erts_print(to, to_arg, "%T ", (Eterm) ap[0]);
ap++;
size++;
}
ix = n;
while (ix--) {
erts_print(to, to_arg, "f(" HEXF ") ", (Eterm) ap[0]);
ap++;
size++;
}
}
break;
case op_i_select_val_bins_rfI:
case op_i_select_val_bins_xfI:
case op_i_select_val_bins_yfI:
{
int n = ap[-1];
while (n > 0) {
erts_print(to, to_arg, "%T f(" HEXF ") ", (Eterm) ap[0], ap[1]);
ap += 2;
size += 2;
n--;
}
}
break;
case op_i_select_tuple_arity_rfI:
case op_i_select_tuple_arity_xfI:
case op_i_select_tuple_arity_yfI:
{
int n = ap[-1];
int ix = n - 1; /* without sentinel */
while (ix--) {
Uint arity = arityval(ap[0]);
erts_print(to, to_arg, "{%d} ", arity, ap[1]);
ap++;
size++;
}
/* print sentinel */
erts_print(to, to_arg, "{%T} ", ap[0], ap[1]);
ap++;
size++;
ix = n;
while (ix--) {
erts_print(to, to_arg, "f(" HEXF ") ", ap[0]);
ap++;
size++;
}
}
break;
case op_i_jump_on_val_rfII:
case op_i_jump_on_val_xfII:
case op_i_jump_on_val_yfII:
{
int n;
for (n = ap[-2]; n > 0; n--) {
erts_print(to, to_arg, "f(" HEXF ") ", ap[0]);
ap++;
size++;
}
}
break;
case op_i_jump_on_val_zero_rfI:
case op_i_jump_on_val_zero_xfI:
case op_i_jump_on_val_zero_yfI:
{
int n;
for (n = ap[-1]; n > 0; n--) {
erts_print(to, to_arg, "f(" HEXF ") ", ap[0]);
ap++;
size++;
}
}
break;
case op_i_put_tuple_rI:
case op_i_put_tuple_xI:
case op_i_put_tuple_yI:
case op_new_map_dII:
case op_update_map_assoc_jsdII:
case op_update_map_exact_jsdII:
{
int n = unpacked[-1];
while (n > 0) {
if (!is_header(ap[0])) {
erts_print(to, to_arg, " %T", (Eterm) ap[0]);
} else {
switch ((ap[0] >> 2) & 0x03) {
case R_REG_DEF:
erts_print(to, to_arg, " x(0)");
break;
case X_REG_DEF:
erts_print(to, to_arg, " x(%d)", ap[0] >> 4);
break;
case Y_REG_DEF:
erts_print(to, to_arg, " y(%d)", ap[0] >> 4);
break;
}
}
ap++, size++, n--;
}
}
break;
case op_i_get_map_elements_fsI:
{
int n = unpacked[-1];
while (n > 0) {
if (n % 3 == 1) {
erts_print(to, to_arg, " %X", ap[0]);
} else if (!is_header(ap[0])) {
erts_print(to, to_arg, " %T", (Eterm) ap[0]);
} else {
switch ((ap[0] >> 2) & 0x03) {
case R_REG_DEF:
erts_print(to, to_arg, " x(0)");
break;
case X_REG_DEF:
erts_print(to, to_arg, " x(%d)", ap[0] >> 4);
break;
case Y_REG_DEF:
erts_print(to, to_arg, " y(%d)", ap[0] >> 4);
break;
}
}
ap++, size++, n--;
}
}
break;
}
erts_print(to, to_arg, "\n");
return size;
}
| apache-2.0 |
sernaleon/charlie | Raspberry/old/resto/mjpg-streamer/plugins/output_http/output_http.c | 28 | 8864 | /*******************************************************************************
# #
# MJPG-streamer allows to stream JPG frames from an input-plugin #
# to several output plugins #
# #
# Copyright (C) 2007 Tom Stöveken #
# #
# This program is free software; 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 #
# #
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <getopt.h>
#include <pthread.h>
#include <syslog.h>
#include "../../mjpg_streamer.h"
#include "../../utils.h"
#include "httpd.h"
#define OUTPUT_PLUGIN_NAME "HTTP output plugin"
/*
* keep context for each server
*/
context servers[MAX_OUTPUT_PLUGINS];
/******************************************************************************
Description.: print help for this plugin to stdout
Input Value.: -
Return Value: -
******************************************************************************/
void help(void)
{
fprintf(stderr, " ---------------------------------------------------------------\n" \
" Help for output plugin..: "OUTPUT_PLUGIN_NAME"\n" \
" ---------------------------------------------------------------\n" \
" The following parameters can be passed to this plugin:\n\n" \
" [-w | --www ]...........: folder that contains webpages in \n" \
" flat hierarchy (no subfolders)\n" \
" [-p | --port ]..........: TCP port for this HTTP server\n" \
" [-c | --credentials ]...: ask for \"username:password\" on connect\n" \
" [-n | --nocommands ]....: disable execution of commands\n"
" ---------------------------------------------------------------\n");
}
/*** plugin interface functions ***/
/******************************************************************************
Description.: Initialize this plugin.
parse configuration parameters,
store the parsed values in global variables
Input Value.: All parameters to work with.
Among many other variables the "param->id" is quite important -
it is used to distinguish between several server instances
Return Value: 0 if everything is OK, other values signal an error
******************************************************************************/
int output_init(output_parameter *param, int id)
{
int i;
int port;
char *credentials, *www_folder;
char nocommands;
DBG("output #%02d\n", param->id);
port = htons(8080);
credentials = NULL;
www_folder = NULL;
nocommands = 0;
param->argv[0] = OUTPUT_PLUGIN_NAME;
/* show all parameters for DBG purposes */
for(i = 0; i < param->argc; i++) {
DBG("argv[%d]=%s\n", i, param->argv[i]);
}
reset_getopt();
while(1) {
int option_index = 0, c = 0;
static struct option long_options[] = {
{"h", no_argument, 0, 0
},
{"help", no_argument, 0, 0},
{"p", required_argument, 0, 0},
{"port", required_argument, 0, 0},
{"c", required_argument, 0, 0},
{"credentials", required_argument, 0, 0},
{"w", required_argument, 0, 0},
{"www", required_argument, 0, 0},
{"n", no_argument, 0, 0},
{"nocommands", no_argument, 0, 0},
{0, 0, 0, 0}
};
c = getopt_long_only(param->argc, param->argv, "", long_options, &option_index);
/* no more options to parse */
if(c == -1) break;
/* unrecognized option */
if(c == '?') {
help();
return 1;
}
switch(option_index) {
/* h, help */
case 0:
case 1:
DBG("case 0,1\n");
help();
return 1;
break;
/* p, port */
case 2:
case 3:
DBG("case 2,3\n");
port = htons(atoi(optarg));
break;
/* c, credentials */
case 4:
case 5:
DBG("case 4,5\n");
credentials = strdup(optarg);
break;
/* w, www */
case 6:
case 7:
DBG("case 6,7\n");
www_folder = malloc(strlen(optarg) + 2);
strcpy(www_folder, optarg);
if(optarg[strlen(optarg)-1] != '/')
strcat(www_folder, "/");
break;
/* n, nocommands */
case 8:
case 9:
DBG("case 8,9\n");
nocommands = 1;
break;
}
}
servers[param->id].id = param->id;
servers[param->id].pglobal = param->global;
servers[param->id].conf.port = port;
servers[param->id].conf.credentials = credentials;
servers[param->id].conf.www_folder = www_folder;
servers[param->id].conf.nocommands = nocommands;
OPRINT("www-folder-path...: %s\n", (www_folder == NULL) ? "disabled" : www_folder);
OPRINT("HTTP TCP port.....: %d\n", ntohs(port));
OPRINT("username:password.: %s\n", (credentials == NULL) ? "disabled" : credentials);
OPRINT("commands..........: %s\n", (nocommands) ? "disabled" : "enabled");
return 0;
}
/******************************************************************************
Description.: this will stop the server thread, client threads
will not get cleaned properly, because they run detached and
no pointer is kept. This is not a huge issue, because this
funtion is intended to clean up the biggest mess on shutdown.
Input Value.: id determines which server instance to send commands to
Return Value: always 0
******************************************************************************/
int output_stop(int id)
{
DBG("will cancel server thread #%02d\n", id);
pthread_cancel(servers[id].threadID);
return 0;
}
/******************************************************************************
Description.: This creates and starts the server thread
Input Value.: id determines which server instance to send commands to
Return Value: always 0
******************************************************************************/
int output_run(int id)
{
DBG("launching server thread #%02d\n", id);
/* create thread and pass context to thread function */
pthread_create(&(servers[id].threadID), NULL, server_thread, &(servers[id]));
pthread_detach(servers[id].threadID);
return 0;
}
/******************************************************************************
Description.: This is just an example function, to show how the output
plugin could implement some special command.
If you want to control some GPIO Pin this is a good place to
implement it. Dont forget to add command types and a mapping.
Input Value.: cmd is the command type
id determines which server instance to send commands to
Return Value: 0 indicates success, other values indicate an error
******************************************************************************/
int output_cmd(int plugin, unsigned int control_id, unsigned int group, int value)
{
DBG("command (%d, value: %d) for group %d triggered for plugin instance #%02d\n", control_id, value, group, plugin);
return 0;
}
| apache-2.0 |
JeongJunSik/TizenRT | os/arch/arm/src/armv7-m/up_stackcheck.c | 31 | 5405 | /****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#ifdef CONFIG_ARMV7M_STACKCHECK
/* Support per function call stack checking.
* This code uses R10 to check for a stack overflow within function calls.
* This has a performance impact, but will be able to catch hard to find
* stack overflows.
*/
#include <stdint.h>
#include "up_arch.h"
#include "nvic.h"
/****************************************************************************
* Private Functions
****************************************************************************/
void __cyg_profile_func_enter(void *func, void *caller) __attribute__((naked, no_instrument_function));
void __cyg_profile_func_exit(void *func, void *caller) __attribute__((naked, no_instrument_function));
void __stack_overflow_trap(void) __attribute__((naked, no_instrument_function));
/****************************************************************************
* Name: __stack_overflow_trap
****************************************************************************/
void __stack_overflow_trap(void)
{
/* if we get here, the stack has overflowed */
uint32_t regval;
/* force hard fault */
regval = getreg32(NVIC_INTCTRL);
regval |= NVIC_INTCTRL_NMIPENDSET;
putreg32(regval, NVIC_INTCTRL);
/* XXX no need to trap it here, the fault handler gets to it */
}
/****************************************************************************
* Name: __cyg_profile_func_enter
****************************************************************************/
void __cyg_profile_func_enter(void *func, void *caller)
{
asm volatile
(
" mrs r2, ipsr \n" /* Check whether we are in interrupt mode */
" cmp r2, #0 \n" /* since we don't switch r10 on interrupt entry, we */
" bne 2f \n" /* can't detect overflow of the interrupt stack. */
" \n"
" sub r2, sp, #68 \n" /* compute stack pointer as though we just stacked a full frame */
" mrs r1, control \n" /* Test CONTROL.FPCA to see whether we also need room for the FP */
" tst r1, #4 \n" /* context. */
" beq 1f \n"
" sub r2, r2, #136 \n" /* subtract FP context frame size */
"1: \n"
" cmp r2, r10 \n" /* compare stack with limit */
" bgt 2f \n" /* stack is above limit and thus OK */
" b __stack_overflow_trap\n"
"2: \n"
" bx lr \n"
);
}
/****************************************************************************
* Name: __cyg_profile_func_exit
****************************************************************************/
void __cyg_profile_func_exit(void *func, void *caller)
{
asm volatile("bx lr");
}
#endif
| apache-2.0 |
kpurusho/mbed | libraries/mbed/targets/cmsis/TARGET_ARM_SSG/TARGET_MPS2_M7/system_CMSDK_CM7.c | 35 | 3439 | /* MPS2 CMSIS Library
*
* Copyright (c) 2006-2015 ARM Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************
* @file system_CMSDK_CM7.c
* @brief CMSIS Device System Source File for
* CMSDK_CM7 Device
* @version V1.00
* @date 27. August 2014
*
* @note
*
*******************************************************************************/
#if defined (CMSDK_CM7)
#include "CMSDK_CM7.h"
#elif defined (CMSDK_CM7_SP)
#include "CMSDK_CM7_SP.h"
#elif defined (CMSDK_CM7_DP)
#include "CMSDK_CM7_DP.h"
#else
#error device not specified!
#endif
/*----------------------------------------------------------------------------
Define clocks
*----------------------------------------------------------------------------*/
#define __XTAL (50000000UL) /* Oscillator frequency */
#define __SYSTEM_CLOCK (__XTAL / 2)
/*----------------------------------------------------------------------------
System Core Clock Variable
*----------------------------------------------------------------------------*/
uint32_t SystemCoreClock = __SYSTEM_CLOCK;/* System Core Clock Frequency */
/**
* Update SystemCoreClock variable
*
* @param none
* @return none
*
* @brief Updates the SystemCoreClock with current core Clock
* retrieved from cpu registers.
*/
void SystemCoreClockUpdate (void)
{
SystemCoreClock = __SYSTEM_CLOCK;
}
/**
* Initialize the system
*
* @param none
* @return none
*
* @brief Setup the microcontroller system.
* Initialize the System.
*/
void SystemInit (void)
{
#if (__FPU_USED == 1)
SCB->CPACR |= ((3UL << 10*2) | /* set CP10 Full Access */
(3UL << 11*2) ); /* set CP11 Full Access */
#endif
#ifdef UNALIGNED_SUPPORT_DISABLE
SCB->CCR |= SCB_CCR_UNALIGN_TRP_Msk;
#endif
SystemCoreClock = __SYSTEM_CLOCK;
}
| apache-2.0 |
monkiineko/mbed-os | targets/TARGET_STM/TARGET_STM32F0/device/stm32f0xx_hal_tsc.c | 36 | 25443 | /**
******************************************************************************
* @file stm32f0xx_hal_tsc.c
* @author MCD Application Team
* @version V1.5.0
* @date 04-November-2016
* @brief This file provides firmware functions to manage the following
* functionalities of the Touch Sensing Controller (TSC) peripheral:
* + Initialization and DeInitialization
* + Channel IOs, Shield IOs and Sampling IOs configuration
* + Start and Stop an acquisition
* + Read acquisition result
* + Interrupts and flags management
*
@verbatim
================================================================================
##### TSC specific features #####
================================================================================
[..]
(+) Proven and robust surface charge transfer acquisition principle
(+) Supports up to 3 capacitive sensing channels per group
(+) Capacitive sensing channels can be acquired in parallel offering a very good
response time
(+) Spread spectrum feature to improve system robustness in noisy environments
(+) Full hardware management of the charge transfer acquisition sequence
(+) Programmable charge transfer frequency
(+) Programmable sampling capacitor I/O pin
(+) Programmable channel I/O pin
(+) Programmable max count value to avoid long acquisition when a channel is faulty
(+) Dedicated end of acquisition and max count error flags with interrupt capability
(+) One sampling capacitor for up to 3 capacitive sensing channels to reduce the system
components
(+) Compatible with proximity, touchkey, linear and rotary touch sensor implementation
##### How to use this driver #####
================================================================================
[..]
(#) Enable the TSC interface clock using __HAL_RCC_TSC_CLK_ENABLE() macro.
(#) GPIO pins configuration
(++) Enable the clock for the TSC GPIOs using __HAL_RCC_GPIOx_CLK_ENABLE() macro.
(++) Configure the TSC pins used as sampling IOs in alternate function output Open-Drain mode,
and TSC pins used as channel/shield IOs in alternate function output Push-Pull mode
using HAL_GPIO_Init() function.
(++) Configure the alternate function on all the TSC pins using HAL_xxxx() function.
(#) Interrupts configuration
(++) Configure the NVIC (if the interrupt model is used) using HAL_xxx() function.
(#) TSC configuration
(++) Configure all TSC parameters and used TSC IOs using HAL_TSC_Init() function.
*** Acquisition sequence ***
===================================
[..]
(+) Discharge all IOs using HAL_TSC_IODischarge() function.
(+) Wait a certain time allowing a good discharge of all capacitors. This delay depends
of the sampling capacitor and electrodes design.
(+) Select the channel IOs to be acquired using HAL_TSC_IOConfig() function.
(+) Launch the acquisition using either HAL_TSC_Start() or HAL_TSC_Start_IT() function.
If the synchronized mode is selected, the acquisition will start as soon as the signal
is received on the synchro pin.
(+) Wait the end of acquisition using either HAL_TSC_PollForAcquisition() or
HAL_TSC_GetState() function or using WFI instruction for example.
(+) Check the group acquisition status using HAL_TSC_GroupGetStatus() function.
(+) Read the acquisition value using HAL_TSC_GroupGetValue() function.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* 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 "stm32f0xx_hal.h"
#ifdef HAL_TSC_MODULE_ENABLED
#if defined(STM32F051x8) || defined(STM32F071xB) || defined(STM32F091xC) || \
defined(STM32F042x6) || defined(STM32F072xB) || \
defined(STM32F048xx) || defined(STM32F058xx) || defined(STM32F078xx) || defined(STM32F098xx)
/** @addtogroup STM32F0xx_HAL_Driver
* @{
*/
/** @defgroup TSC TSC
* @brief TSC HAL module driver
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static uint32_t TSC_extract_groups(uint32_t iomask);
/* Exported functions ---------------------------------------------------------*/
/** @defgroup TSC_Exported_Functions TSC Exported Functions
* @{
*/
/** @defgroup TSC_Exported_Functions_Group1 Initialization/de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Initialize and configure the TSC.
(+) De-initialize the TSC.
@endverbatim
* @{
*/
/**
* @brief Initializes the TSC peripheral according to the specified parameters
* in the TSC_InitTypeDef structure.
* @param htsc: TSC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc)
{
/* Check TSC handle allocation */
if (htsc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_CTPH(htsc->Init.CTPulseHighLength));
assert_param(IS_TSC_CTPL(htsc->Init.CTPulseLowLength));
assert_param(IS_TSC_SS(htsc->Init.SpreadSpectrum));
assert_param(IS_TSC_SSD(htsc->Init.SpreadSpectrumDeviation));
assert_param(IS_TSC_SS_PRESC(htsc->Init.SpreadSpectrumPrescaler));
assert_param(IS_TSC_PG_PRESC(htsc->Init.PulseGeneratorPrescaler));
assert_param(IS_TSC_MCV(htsc->Init.MaxCountValue));
assert_param(IS_TSC_IODEF(htsc->Init.IODefaultMode));
assert_param(IS_TSC_SYNC_POL(htsc->Init.SynchroPinPolarity));
assert_param(IS_TSC_ACQ_MODE(htsc->Init.AcquisitionMode));
assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt));
if(htsc->State == HAL_TSC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
htsc->Lock = HAL_UNLOCKED;
}
/* Initialize the TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/* Init the low level hardware : GPIO, CLOCK, CORTEX */
HAL_TSC_MspInit(htsc);
/*--------------------------------------------------------------------------*/
/* Set TSC parameters */
/* Enable TSC */
htsc->Instance->CR = TSC_CR_TSCE;
/* Set all functions */
htsc->Instance->CR |= (htsc->Init.CTPulseHighLength |
htsc->Init.CTPulseLowLength |
(uint32_t)(htsc->Init.SpreadSpectrumDeviation << 17U) |
htsc->Init.SpreadSpectrumPrescaler |
htsc->Init.PulseGeneratorPrescaler |
htsc->Init.MaxCountValue |
htsc->Init.SynchroPinPolarity |
htsc->Init.AcquisitionMode);
/* Spread spectrum */
if (htsc->Init.SpreadSpectrum == ENABLE)
{
htsc->Instance->CR |= TSC_CR_SSE;
}
/* Disable Schmitt trigger hysteresis on all used TSC IOs */
htsc->Instance->IOHCR = (uint32_t)(~(htsc->Init.ChannelIOs | htsc->Init.ShieldIOs | htsc->Init.SamplingIOs));
/* Set channel and shield IOs */
htsc->Instance->IOCCR = (htsc->Init.ChannelIOs | htsc->Init.ShieldIOs);
/* Set sampling IOs */
htsc->Instance->IOSCR = htsc->Init.SamplingIOs;
/* Set the groups to be acquired */
htsc->Instance->IOGCSR = TSC_extract_groups(htsc->Init.ChannelIOs);
/* Clear interrupts */
htsc->Instance->IER &= (uint32_t)(~(TSC_IT_EOA | TSC_IT_MCE));
/* Clear flags */
htsc->Instance->ICR = (TSC_FLAG_EOA | TSC_FLAG_MCE);
/*--------------------------------------------------------------------------*/
/* Initialize the TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
* @brief Deinitializes the TSC peripheral registers to their default reset values.
* @param htsc: TSC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef* htsc)
{
/* Check TSC handle allocation */
if (htsc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Change TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/* DeInit the low level hardware */
HAL_TSC_MspDeInit(htsc);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_RESET;
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Initializes the TSC MSP.
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_MspInit could be implemented in the user file.
*/
}
/**
* @brief DeInitializes the TSC MSP.
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_MspDeInit could be implemented in the user file.
*/
}
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group2 IO operation functions
* @brief IO operation functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Start acquisition in polling mode.
(+) Start acquisition in interrupt mode.
(+) Stop conversion in polling mode.
(+) Stop conversion in interrupt mode.
(+) Get group acquisition status.
(+) Get group acquisition value.
@endverbatim
* @{
*/
/**
* @brief Starts the acquisition.
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/* Clear interrupts */
__HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE));
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Set touch sensing IOs not acquired to the specified IODefaultMode */
if (htsc->Init.IODefaultMode == TSC_IODEF_OUT_PP_LOW)
{
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
}
else
{
__HAL_TSC_SET_IODEF_INFLOAT(htsc);
}
/* Launch the acquisition */
__HAL_TSC_START_ACQ(htsc);
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Enables the interrupt and starts the acquisition
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status.
*/
HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt));
/* Process locked */
__HAL_LOCK(htsc);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_BUSY;
/* Enable end of acquisition interrupt */
__HAL_TSC_ENABLE_IT(htsc, TSC_IT_EOA);
/* Enable max count error interrupt (optional) */
if (htsc->Init.MaxCountInterrupt == ENABLE)
{
__HAL_TSC_ENABLE_IT(htsc, TSC_IT_MCE);
}
else
{
__HAL_TSC_DISABLE_IT(htsc, TSC_IT_MCE);
}
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Set touch sensing IOs not acquired to the specified IODefaultMode */
if (htsc->Init.IODefaultMode == TSC_IODEF_OUT_PP_LOW)
{
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
}
else
{
__HAL_TSC_SET_IODEF_INFLOAT(htsc);
}
/* Launch the acquisition */
__HAL_TSC_START_ACQ(htsc);
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the acquisition previously launched in polling mode
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Stop the acquisition */
__HAL_TSC_STOP_ACQ(htsc);
/* Set touch sensing IOs in low power mode (output push-pull) */
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Stops the acquisition previously launched in interrupt mode
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Stop the acquisition */
__HAL_TSC_STOP_ACQ(htsc);
/* Set touch sensing IOs in low power mode (output push-pull) */
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
/* Disable interrupts */
__HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE));
/* Clear flags */
__HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE));
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Gets the acquisition status for a group
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param gx_index: Index of the group
* @retval Group status
*/
TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_GROUP_INDEX(gx_index));
/* Return the group status */
return(__HAL_TSC_GET_GROUP_STATUS(htsc, gx_index));
}
/**
* @brief Gets the acquisition measure for a group
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param gx_index: Index of the group
* @retval Acquisition measure
*/
uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
assert_param(IS_GROUP_INDEX(gx_index));
/* Return the group acquisition counter */
return htsc->Instance->IOGXCR[gx_index];
}
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group3 Peripheral Control functions
* @brief Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..] This section provides functions allowing to:
(+) Configure TSC IOs
(+) Discharge TSC IOs
@endverbatim
* @{
*/
/**
* @brief Configures TSC IOs
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param config: pointer to the configuration structure.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Stop acquisition */
__HAL_TSC_STOP_ACQ(htsc);
/* Disable Schmitt trigger hysteresis on all used TSC IOs */
htsc->Instance->IOHCR = (uint32_t)(~(config->ChannelIOs | config->ShieldIOs | config->SamplingIOs));
/* Set channel and shield IOs */
htsc->Instance->IOCCR = (config->ChannelIOs | config->ShieldIOs);
/* Set sampling IOs */
htsc->Instance->IOSCR = config->SamplingIOs;
/* Set groups to be acquired */
htsc->Instance->IOGCSR = TSC_extract_groups(config->ChannelIOs);
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return function status */
return HAL_OK;
}
/**
* @brief Discharge TSC IOs
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @param choice: enable or disable
* @retval HAL status
*/
HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
if (choice == ENABLE)
{
__HAL_TSC_SET_IODEF_OUTPPLOW(htsc);
}
else
{
__HAL_TSC_SET_IODEF_INFLOAT(htsc);
}
/* Process unlocked */
__HAL_UNLOCK(htsc);
/* Return the group acquisition counter */
return HAL_OK;
}
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group4 State functions
* @brief State functions
*
@verbatim
===============================================================================
##### State functions #####
===============================================================================
[..]
This subsection provides functions allowing to
(+) Get TSC state.
(+) Poll for acquisition completed.
(+) Handles TSC interrupt request.
@endverbatim
* @{
*/
/**
* @brief Return the TSC state
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL state
*/
HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
if (htsc->State == HAL_TSC_STATE_BUSY)
{
/* Check end of acquisition flag */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET)
{
/* Check max count error flag */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET)
{
/* Change TSC state */
htsc->State = HAL_TSC_STATE_ERROR;
}
else
{
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
}
}
}
/* Return TSC state */
return htsc->State;
}
/**
* @brief Start acquisition and wait until completion
* @note There is no need of a timeout parameter as the max count error is already
* managed by the TSC peripheral.
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval HAL state
*/
HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Process locked */
__HAL_LOCK(htsc);
/* Check end of acquisition */
while (HAL_TSC_GetState(htsc) == HAL_TSC_STATE_BUSY)
{
/* The timeout (max count error) is managed by the TSC peripheral itself. */
}
/* Process unlocked */
__HAL_UNLOCK(htsc);
return HAL_OK;
}
/**
* @brief Handles TSC interrupt request
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc)
{
/* Check the parameters */
assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance));
/* Check if the end of acquisition occured */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET)
{
/* Clear EOA flag */
__HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_EOA);
}
/* Check if max count error occured */
if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET)
{
/* Clear MCE flag */
__HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_MCE);
/* Change TSC state */
htsc->State = HAL_TSC_STATE_ERROR;
/* Conversion completed callback */
HAL_TSC_ErrorCallback(htsc);
}
else
{
/* Change TSC state */
htsc->State = HAL_TSC_STATE_READY;
/* Conversion completed callback */
HAL_TSC_ConvCpltCallback(htsc);
}
}
/**
* @}
*/
/** @defgroup TSC_Exported_Functions_Group5 Callback functions
* @brief Callback functions
* @{
*/
/**
* @brief Acquisition completed callback in non blocking mode
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_ConvCpltCallback could be implemented in the user file.
*/
}
/**
* @brief Error callback in non blocking mode
* @param htsc: pointer to a TSC_HandleTypeDef structure that contains
* the configuration information for the specified TSC.
* @retval None
*/
__weak void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(htsc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_TSC_ErrorCallback could be implemented in the user file.
*/
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup TSC_Private_Functions TSC Private Functions
* @{
*/
/**
* @brief Utility function used to set the acquired groups mask
* @param iomask: Channels IOs mask
* @retval Acquired groups mask
*/
static uint32_t TSC_extract_groups(uint32_t iomask)
{
uint32_t groups = 0U;
uint32_t idx;
for (idx = 0U; idx < TSC_NB_OF_GROUPS; idx++)
{
if ((iomask & (0x0FU << (idx * 4U))) != RESET)
{
groups |= (1U << idx);
}
}
return groups;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(STM32F051x8) || defined(STM32F071xB) || defined(STM32F091xC) || */
/* defined(STM32F042x6) || defined(STM32F072xB) || */
/* defined(STM32F048xx) || defined(STM32F058xx) || defined(STM32F078xx) || defined(STM32F098xx) */
#endif /* HAL_TSC_MODULE_ENABLED */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
darklost/DexHunter | dalvik/vm/arch/generic/Call.cpp | 37 | 3909 | /*
* Copyright (C) 2008 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.
*/
/*
* This uses the FFI (Foreign Function Interface) library to abstract away
* the system-dependent stuff. The FFI code is slower than a custom
* assembly version, but has the distinct advantage of having been
* written already for several platforms.
*/
#include "Dalvik.h"
#include "ffi.h"
/*
* Convert a signature type character to an FFI type.
*/
static ffi_type* getFfiType(char sigType)
{
switch (sigType) {
case 'V': return &ffi_type_void;
case 'Z': return &ffi_type_uint8;
case 'B': return &ffi_type_sint8;
case 'C': return &ffi_type_uint16;
case 'S': return &ffi_type_sint16;
case 'I': return &ffi_type_sint32;
case 'F': return &ffi_type_float;
case 'J': return &ffi_type_sint64;
case 'D': return &ffi_type_double;
case '[':
case 'L': return &ffi_type_pointer;
default:
ALOGE("bad ffitype 0x%02x", sigType);
dvmAbort();
return NULL;
}
}
/* We will call this generic function if there are no hints */
#ifdef __mips__
#define dvmPlatformInvoke dvmPlatformInvokeFFI
extern "C" void dvmPlatformInvoke(void* pEnv, ClassObject* clazz, int argInfo,
int argc, const u4* argv, const char* signature, void* func, JValue* pResult);
#endif
/*
* Call "func" with the specified arguments.
*
* The second argument to JNI native functions is either the object (the
* "this" pointer) or, for static functions, a pointer to the class object.
* The Dalvik instructions will push "this" into argv[0], but it's up to
* us to insert the class object.
*
* Because there is no such thing in as a null "this" pointer, we use
* the non-NULL state of "clazz" to determine whether or not it's static.
*
* For maximum efficiency we should compute the CIF once and save it with
* the method. However, this requires storing the data with every native
* method. Since the goal is to have custom assembly versions of this
* on the platforms where performance matters, I'm recomputing the CIF on
* every call.
*/
void dvmPlatformInvoke(void* pEnv, ClassObject* clazz, int argInfo, int argc,
const u4* argv, const char* shorty, void* func, JValue* pReturn)
{
const int kMaxArgs = argc+2; /* +1 for env, maybe +1 for clazz */
ffi_cif cif;
ffi_type* types[kMaxArgs];
void* values[kMaxArgs];
ffi_type* retType;
char sigByte;
int srcArg, dstArg;
types[0] = &ffi_type_pointer;
values[0] = &pEnv;
types[1] = &ffi_type_pointer;
if (clazz != NULL) {
values[1] = &clazz;
srcArg = 0;
} else {
values[1] = (void*) argv++;
srcArg = 1;
}
dstArg = 2;
/*
* Scan the types out of the short signature. Use them to fill out the
* "types" array. Store the start address of the argument in "values".
*/
retType = getFfiType(*shorty);
while ((sigByte = *++shorty) != '\0') {
types[dstArg] = getFfiType(sigByte);
values[dstArg++] = (void*) argv++;
if (sigByte == 'D' || sigByte == 'J')
argv++;
}
/*
* Prep the CIF (Call InterFace object).
*/
if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, dstArg, retType, types) != FFI_OK) {
ALOGE("ffi_prep_cif failed");
dvmAbort();
}
ffi_call(&cif, FFI_FN(func), pReturn, values);
}
| apache-2.0 |
hjmjohnson/ITK | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/arpack/dsaupd.c | 39 | 36573 | /* arpack/dsaupd.f -- translated by f2c (version 20090411).
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
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"
/* Common Block Declarations */
/*Extern struct { */
/* integer logfil, ndigit, mgetv0, msaupd, msaup2, msaitr, mseigt, msapps, */
/* msgets, mseupd, mnaupd, mnaup2, mnaitr, mneigh, mnapps, mngets, */
/* mneupd, mcaupd, mcaup2, mcaitr, mceigh, mcapps, mcgets, mceupd; */
/*} debug_; */
/*#define debug_1 debug_ */
/*Extern struct { */
/* integer nopx, nbx, nrorth, nitref, nrstrt; */
/* real tsaupd, tsaup2, tsaitr, tseigt, tsgets, tsapps, tsconv, tnaupd, */
/* tnaup2, tnaitr, tneigh, tngets, tnapps, tnconv, tcaupd, tcaup2, */
/* tcaitr, tceigh, tcgets, tcapps, tcconv, tmvopx, tmvbx, tgetv0, */
/* titref, trvec; */
/*} timing_; */
/*#define timing_1 timing_ */
/* ----------------------------------------------------------------------- */
/* \BeginDoc */
/* \Name: dsaupd */
/* \Description: */
/* Reverse communication interface for the Implicitly Restarted Arnoldi */
/* Iteration. For symmetric problems this reduces to a variant of the Lanczos */
/* method. This method has been designed to compute approximations to a */
/* few eigenpairs of a linear operator OP that is real and symmetric */
/* with respect to a real positive semi-definite symmetric matrix B, */
/* i.e. */
/* B*OP = (OP')*B. */
/* Another way to express this condition is */
/* < x,OPy > = < OPx,y > where < z,w > = z'Bw . */
/* In the standard eigenproblem B is the identity matrix. */
/* ( A' denotes transpose of A) */
/* The computed approximate eigenvalues are called Ritz values and */
/* the corresponding approximate eigenvectors are called Ritz vectors. */
/* dsaupd is usually called iteratively to solve one of the */
/* following problems: */
/* Mode 1: A*x = lambda*x, A symmetric */
/* ===> OP = A and B = I. */
/* Mode 2: A*x = lambda*M*x, A symmetric, M symmetric positive definite */
/* ===> OP = inv[M]*A and B = M. */
/* ===> (If M can be factored see remark 3 below) */
/* Mode 3: K*x = lambda*M*x, K symmetric, M symmetric positive semi-definite */
/* ===> OP = (inv[K - sigma*M])*M and B = M. */
/* ===> Shift-and-Invert mode */
/* Mode 4: K*x = lambda*KG*x, K symmetric positive semi-definite, */
/* KG symmetric indefinite */
/* ===> OP = (inv[K - sigma*KG])*K and B = K. */
/* ===> Buckling mode */
/* Mode 5: A*x = lambda*M*x, A symmetric, M symmetric positive semi-definite */
/* ===> OP = inv[A - sigma*M]*[A + sigma*M] and B = M. */
/* ===> Cayley transformed mode */
/* NOTE: The action of w <- inv[A - sigma*M]*v or w <- inv[M]*v */
/* should be accomplished either by a direct method */
/* using a sparse matrix factorization and solving */
/* [A - sigma*M]*w = v or M*w = v, */
/* or through an iterative method for solving these */
/* systems. If an iterative method is used, the */
/* convergence test must be more stringent than */
/* the accuracy requirements for the eigenvalue */
/* approximations. */
/* \Usage: */
/* call dsaupd */
/* ( IDO, BMAT, N, WHICH, NEV, TOL, RESID, NCV, V, LDV, IPARAM, */
/* IPNTR, WORKD, WORKL, LWORKL, INFO ) */
/* \Arguments */
/* IDO Integer. (INPUT/OUTPUT) */
/* Reverse communication flag. IDO must be zero on the first */
/* call to dsaupd. IDO will be set internally to */
/* indicate the type of operation to be performed. Control is */
/* then given back to the calling routine which has the */
/* responsibility to carry out the requested operation and call */
/* dsaupd with the result. The operand is given in */
/* WORKD(IPNTR(1)), the result must be put in WORKD(IPNTR(2)). */
/* (If Mode = 2 see remark 5 below) */
/* ------------------------------------------------------------- */
/* IDO = 0: first call to the reverse communication interface */
/* IDO = -1: compute Y = OP * X where */
/* IPNTR(1) is the pointer into WORKD for X, */
/* IPNTR(2) is the pointer into WORKD for Y. */
/* This is for the initialization phase to force the */
/* starting vector into the range of OP. */
/* IDO = 1: compute Y = OP * X where */
/* IPNTR(1) is the pointer into WORKD for X, */
/* IPNTR(2) is the pointer into WORKD for Y. */
/* In mode 3,4 and 5, the vector B * X is already */
/* available in WORKD(ipntr(3)). It does not */
/* need to be recomputed in forming OP * X. */
/* IDO = 2: compute Y = B * X where */
/* IPNTR(1) is the pointer into WORKD for X, */
/* IPNTR(2) is the pointer into WORKD for Y. */
/* IDO = 3: compute the IPARAM(8) shifts where */
/* IPNTR(11) is the pointer into WORKL for */
/* placing the shifts. See remark 6 below. */
/* IDO = 99: done */
/* ------------------------------------------------------------- */
/* BMAT Character*1. (INPUT) */
/* BMAT specifies the type of the matrix B that defines the */
/* semi-inner product for the operator OP. */
/* B = 'I' -> standard eigenvalue problem A*x = lambda*x */
/* B = 'G' -> generalized eigenvalue problem A*x = lambda*B*x */
/* N Integer. (INPUT) */
/* Dimension of the eigenproblem. */
/* WHICH Character*2. (INPUT) */
/* Specify which of the Ritz values of OP to compute. */
/* 'LA' - compute the NEV largest (algebraic) eigenvalues. */
/* 'SA' - compute the NEV smallest (algebraic) eigenvalues. */
/* 'LM' - compute the NEV largest (in magnitude) eigenvalues. */
/* 'SM' - compute the NEV smallest (in magnitude) eigenvalues. */
/* 'BE' - compute NEV eigenvalues, half from each end of the */
/* spectrum. When NEV is odd, compute one more from the */
/* high end than from the low end. */
/* (see remark 1 below) */
/* NEV Integer. (INPUT) */
/* Number of eigenvalues of OP to be computed. 0 < NEV < N. */
/* TOL Double precision scalar. (INPUT) */
/* Stopping criterion: the relative accuracy of the Ritz value */
/* is considered acceptable if BOUNDS(I) .LE. TOL*ABS(RITZ(I)). */
/* If TOL .LE. 0. is passed a default is set: */
/* DEFAULT = DLAMCH('EPS') (machine precision as computed */
/* by the LAPACK auxiliary subroutine DLAMCH). */
/* RESID Double precision array of length N. (INPUT/OUTPUT) */
/* On INPUT: */
/* If INFO .EQ. 0, a random initial residual vector is used. */
/* If INFO .NE. 0, RESID contains the initial residual vector, */
/* possibly from a previous run. */
/* On OUTPUT: */
/* RESID contains the final residual vector. */
/* NCV Integer. (INPUT) */
/* Number of columns of the matrix V (less than or equal to N). */
/* This will indicate how many Lanczos vectors are generated */
/* at each iteration. After the startup phase in which NEV */
/* Lanczos vectors are generated, the algorithm generates */
/* NCV-NEV Lanczos vectors at each subsequent update iteration. */
/* Most of the cost in generating each Lanczos vector is in the */
/* matrix-vector product OP*x. (See remark 4 below). */
/* V Double precision N by NCV array. (OUTPUT) */
/* The NCV columns of V contain the Lanczos basis vectors. */
/* LDV Integer. (INPUT) */
/* Leading dimension of V exactly as declared in the calling */
/* program. */
/* IPARAM Integer array of length 11. (INPUT/OUTPUT) */
/* IPARAM(1) = ISHIFT: method for selecting the implicit shifts. */
/* The shifts selected at each iteration are used to restart */
/* the Arnoldi iteration in an implicit fashion. */
/* ------------------------------------------------------------- */
/* ISHIFT = 0: the shifts are provided by the user via */
/* reverse communication. The NCV eigenvalues of */
/* the current tridiagonal matrix T are returned in */
/* the part of WORKL array corresponding to RITZ. */
/* See remark 6 below. */
/* ISHIFT = 1: exact shifts with respect to the reduced */
/* tridiagonal matrix T. This is equivalent to */
/* restarting the iteration with a starting vector */
/* that is a linear combination of Ritz vectors */
/* associated with the "wanted" Ritz values. */
/* ------------------------------------------------------------- */
/* IPARAM(2) = LEVEC */
/* No longer referenced. See remark 2 below. */
/* IPARAM(3) = MXITER */
/* On INPUT: maximum number of Arnoldi update iterations allowed. */
/* On OUTPUT: actual number of Arnoldi update iterations taken. */
/* IPARAM(4) = NB: blocksize to be used in the recurrence. */
/* The code currently works only for NB = 1. */
/* IPARAM(5) = NCONV: number of "converged" Ritz values. */
/* This represents the number of Ritz values that satisfy */
/* the convergence criterion. */
/* IPARAM(6) = IUPD */
/* No longer referenced. Implicit restarting is ALWAYS used. */
/* IPARAM(7) = MODE */
/* On INPUT determines what type of eigenproblem is being solved. */
/* Must be 1,2,3,4,5; See under \Description of dsaupd for the */
/* five modes available. */
/* IPARAM(8) = NP */
/* When ido = 3 and the user provides shifts through reverse */
/* communication (IPARAM(1)=0), dsaupd returns NP, the number */
/* of shifts the user is to provide. 0 < NP <=NCV-NEV. See Remark */
/* 6 below. */
/* IPARAM(9) = NUMOP, IPARAM(10) = NUMOPB, IPARAM(11) = NUMREO, */
/* OUTPUT: NUMOP = total number of OP*x operations, */
/* NUMOPB = total number of B*x operations if BMAT='G', */
/* NUMREO = total number of steps of re-orthogonalization. */
/* IPNTR Integer array of length 11. (OUTPUT) */
/* Pointer to mark the starting locations in the WORKD and WORKL */
/* arrays for matrices/vectors used by the Lanczos iteration. */
/* ------------------------------------------------------------- */
/* IPNTR(1): pointer to the current operand vector X in WORKD. */
/* IPNTR(2): pointer to the current result vector Y in WORKD. */
/* IPNTR(3): pointer to the vector B * X in WORKD when used in */
/* the shift-and-invert mode. */
/* IPNTR(4): pointer to the next available location in WORKL */
/* that is untouched by the program. */
/* IPNTR(5): pointer to the NCV by 2 tridiagonal matrix T in WORKL. */
/* IPNTR(6): pointer to the NCV RITZ values array in WORKL. */
/* IPNTR(7): pointer to the Ritz estimates in array WORKL associated */
/* with the Ritz values located in RITZ in WORKL. */
/* IPNTR(11): pointer to the NP shifts in WORKL. See Remark 6 below. */
/* Note: IPNTR(8:10) is only referenced by dseupd. See Remark 2. */
/* IPNTR(8): pointer to the NCV RITZ values of the original system. */
/* IPNTR(9): pointer to the NCV corresponding error bounds. */
/* IPNTR(10): pointer to the NCV by NCV matrix of eigenvectors */
/* of the tridiagonal matrix T. Only referenced by */
/* dseupd if RVEC = .TRUE. See Remarks. */
/* ------------------------------------------------------------- */
/* WORKD Double precision work array of length 3*N. (REVERSE COMMUNICATION) */
/* Distributed array to be used in the basic Arnoldi iteration */
/* for reverse communication. The user should not use WORKD */
/* as temporary workspace during the iteration. Upon termination */
/* WORKD(1:N) contains B*RESID(1:N). If the Ritz vectors are desired */
/* subroutine dseupd uses this output. */
/* See Data Distribution Note below. */
/* WORKL Double precision work array of length LWORKL. (OUTPUT/WORKSPACE) */
/* Private (replicated) array on each PE or array allocated on */
/* the front end. See Data Distribution Note below. */
/* LWORKL Integer. (INPUT) */
/* LWORKL must be at least NCV**2 + 8*NCV . */
/* INFO Integer. (INPUT/OUTPUT) */
/* If INFO .EQ. 0, a randomly initial residual vector is used. */
/* If INFO .NE. 0, RESID contains the initial residual vector, */
/* possibly from a previous run. */
/* Error flag on output. */
/* = 0: Normal exit. */
/* = 1: Maximum number of iterations taken. */
/* All possible eigenvalues of OP has been found. IPARAM(5) */
/* returns the number of wanted converged Ritz values. */
/* = 2: No longer an informational error. Deprecated starting */
/* with release 2 of ARPACK. */
/* = 3: No shifts could be applied during a cycle of the */
/* Implicitly restarted Arnoldi iteration. One possibility */
/* is to increase the size of NCV relative to NEV. */
/* See remark 4 below. */
/* = -1: N must be positive. */
/* = -2: NEV must be positive. */
/* = -3: NCV must be greater than NEV and less than or equal to N. */
/* = -4: The maximum number of Arnoldi update iterations allowed */
/* must be greater than zero. */
/* = -5: WHICH must be one of 'LM', 'SM', 'LA', 'SA' or 'BE'. */
/* = -6: BMAT must be one of 'I' or 'G'. */
/* = -7: Length of private work array WORKL is not sufficient. */
/* = -8: Error return from trid. eigenvalue calculation; */
/* Informatinal error from LAPACK routine dsteqr. */
/* = -9: Starting vector is zero. */
/* = -10: IPARAM(7) must be 1,2,3,4,5. */
/* = -11: IPARAM(7) = 1 and BMAT = 'G' are incompatable. */
/* = -12: IPARAM(1) must be equal to 0 or 1. */
/* = -13: NEV and WHICH = 'BE' are incompatable. */
/* = -9999: Could not build an Arnoldi factorization. */
/* IPARAM(5) returns the size of the current Arnoldi */
/* factorization. The user is advised to check that */
/* enough workspace and array storage has been allocated. */
/* \Remarks */
/* 1. The converged Ritz values are always returned in ascending */
/* algebraic order. The computed Ritz values are approximate */
/* eigenvalues of OP. The selection of WHICH should be made */
/* with this in mind when Mode = 3,4,5. After convergence, */
/* approximate eigenvalues of the original problem may be obtained */
/* with the ARPACK subroutine dseupd. */
/* 2. If the Ritz vectors corresponding to the converged Ritz values */
/* are needed, the user must call dseupd immediately following completion */
/* of dsaupd. This is new starting with version 2.1 of ARPACK. */
/* 3. If M can be factored into a Cholesky factorization M = LL' */
/* then Mode = 2 should not be selected. Instead one should use */
/* Mode = 1 with OP = inv(L)*A*inv(L'). Appropriate triangular */
/* linear systems should be solved with L and L' rather */
/* than computing inverses. After convergence, an approximate */
/* eigenvector z of the original problem is recovered by solving */
/* L'z = x where x is a Ritz vector of OP. */
/* 4. At present there is no a-priori analysis to guide the selection */
/* of NCV relative to NEV. The only formal requirement is that NCV > NEV. */
/* However, it is recommended that NCV .ge. 2*NEV. If many problems of */
/* the same type are to be solved, one should experiment with increasing */
/* NCV while keeping NEV fixed for a given test problem. This will */
/* usually decrease the required number of OP*x operations but it */
/* also increases the work and storage required to maintain the orthogonal */
/* basis vectors. The optimal "cross-over" with respect to CPU time */
/* is problem dependent and must be determined empirically. */
/* 5. If IPARAM(7) = 2 then in the Reverse commuication interface the user */
/* must do the following. When IDO = 1, Y = OP * X is to be computed. */
/* When IPARAM(7) = 2 OP = inv(B)*A. After computing A*X the user */
/* must overwrite X with A*X. Y is then the solution to the linear set */
/* of equations B*Y = A*X. */
/* 6. When IPARAM(1) = 0, and IDO = 3, the user needs to provide the */
/* NP = IPARAM(8) shifts in locations: */
/* 1 WORKL(IPNTR(11)) */
/* 2 WORKL(IPNTR(11)+1) */
/* . */
/* . */
/* . */
/* NP WORKL(IPNTR(11)+NP-1). */
/* The eigenvalues of the current tridiagonal matrix are located in */
/* WORKL(IPNTR(6)) through WORKL(IPNTR(6)+NCV-1). They are in the */
/* order defined by WHICH. The associated Ritz estimates are located in */
/* WORKL(IPNTR(8)), WORKL(IPNTR(8)+1), ... , WORKL(IPNTR(8)+NCV-1). */
/* ----------------------------------------------------------------------- */
/* \Data Distribution Note: */
/* Fortran-D syntax: */
/* ================ */
/* REAL RESID(N), V(LDV,NCV), WORKD(3*N), WORKL(LWORKL) */
/* DECOMPOSE D1(N), D2(N,NCV) */
/* ALIGN RESID(I) with D1(I) */
/* ALIGN V(I,J) with D2(I,J) */
/* ALIGN WORKD(I) with D1(I) range (1:N) */
/* ALIGN WORKD(I) with D1(I-N) range (N+1:2*N) */
/* ALIGN WORKD(I) with D1(I-2*N) range (2*N+1:3*N) */
/* DISTRIBUTE D1(BLOCK), D2(BLOCK,:) */
/* REPLICATED WORKL(LWORKL) */
/* Cray MPP syntax: */
/* =============== */
/* REAL RESID(N), V(LDV,NCV), WORKD(N,3), WORKL(LWORKL) */
/* SHARED RESID(BLOCK), V(BLOCK,:), WORKD(BLOCK,:) */
/* REPLICATED WORKL(LWORKL) */
/* \BeginLib */
/* \References: */
/* 1. D.C. Sorensen, "Implicit Application of Polynomial Filters in */
/* a k-Step Arnoldi Method", SIAM J. Matr. Anal. Apps., 13 (1992), */
/* pp 357-385. */
/* 2. R.B. Lehoucq, "Analysis and Implementation of an Implicitly */
/* Restarted Arnoldi Iteration", Rice University Technical Report */
/* TR95-13, Department of Computational and Applied Mathematics. */
/* 3. B.N. Parlett, "The Symmetric Eigenvalue Problem". Prentice-Hall, */
/* 1980. */
/* 4. B.N. Parlett, B. Nour-Omid, "Towards a Black Box Lanczos Program", */
/* Computer Physics Communications, 53 (1989), pp 169-179. */
/* 5. B. Nour-Omid, B.N. Parlett, T. Ericson, P.S. Jensen, "How to */
/* Implement the Spectral Transformation", Math. Comp., 48 (1987), */
/* pp 663-673. */
/* 6. R.G. Grimes, J.G. Lewis and H.D. Simon, "A Shifted Block Lanczos */
/* Algorithm for Solving Sparse Symmetric Generalized Eigenproblems", */
/* SIAM J. Matr. Anal. Apps., January (1993). */
/* 7. L. Reichel, W.B. Gragg, "Algorithm 686: FORTRAN Subroutines */
/* for Updating the QR decomposition", ACM TOMS, December 1990, */
/* Volume 16 Number 4, pp 369-377. */
/* 8. R.B. Lehoucq, D.C. Sorensen, "Implementation of Some Spectral */
/* Transformations in a k-Step Arnoldi Method". In Preparation. */
/* \Routines called: */
/* dsaup2 ARPACK routine that implements the Implicitly Restarted */
/* Arnoldi Iteration. */
/* dstats ARPACK routine that initialize timing and other statistics */
/* variables. */
/* second ARPACK utility routine for timing. */
/* dlamch LAPACK routine that determines machine constants. */
/* \Authors */
/* Danny Sorensen Phuong Vu */
/* Richard Lehoucq CRPC / Rice University */
/* Dept. of Computational & Houston, Texas */
/* Applied Mathematics */
/* Rice University */
/* Houston, Texas */
/* \Revision history: */
/* 12/15/93: Version ' 2.4' */
/* \SCCS Information: @(#) */
/* FILE: saupd.F SID: 2.7 DATE OF SID: 8/27/96 RELEASE: 2 */
/* \Remarks */
/* 1. None */
/* \EndLib */
/* ----------------------------------------------------------------------- */
/*< >*/
/* Subroutine */ int dsaupd_(integer *ido, char *bmat, integer *n, char *
which, integer *nev, doublereal *tol, doublereal *resid, integer *ncv,
doublereal *v, integer *ldv, integer *iparam, integer *ipntr,
doublereal *workd, doublereal *workl, integer *lworkl, integer *info,
ftnlen bmat_len, ftnlen which_len)
{
/* System generated locals */
integer v_dim1, v_offset, i__1, i__2;
/* Builtin functions */
integer s_cmp(char *, char *, ftnlen, ftnlen);
/* Local variables */
integer j;
/* static real t0, t1; */
static integer nb, ih, iq, np, iw, ldh, ldq, nev0, mode, ierr, iupd, next,
ritz;
extern /* Subroutine */ int dsaup2_(integer *, char *, integer *, char *,
integer *, integer *, doublereal *, doublereal *, integer *,
integer *, integer *, integer *, doublereal *, integer *,
doublereal *, integer *, doublereal *, doublereal *, doublereal *,
integer *, doublereal *, integer *, doublereal *, integer *,
ftnlen, ftnlen);
extern doublereal dlamch_(char *, ftnlen);
extern /* Subroutine */ int second_(real *);
static integer bounds, ishift, /* msglvl, */ mxiter;
extern /* Subroutine */ int dstats_();
/* %----------------------------------------------------% */
/* | Include files for debugging and timing information | */
/* %----------------------------------------------------% */
/*< include 'debug.h' >*/
/*< include 'stat.h' >*/
/* \SCCS Information: @(#) */
/* FILE: debug.h SID: 2.3 DATE OF SID: 11/16/95 RELEASE: 2 */
/* %---------------------------------% */
/* | See debug.doc for documentation | */
/* %---------------------------------% */
/*< >*/
/*< character bmat*1, which*2 >*/
/* %------------------% */
/* | Scalar Arguments | */
/* %------------------% */
/* %--------------------------------% */
/* | See stat.doc for documentation | */
/* %--------------------------------% */
/* \SCCS Information: @(#) */
/* FILE: stat.h SID: 2.2 DATE OF SID: 11/16/95 RELEASE: 2 */
/*< save t0, t1, t2, t3, t4, t5 >*/
/*< integer nopx, nbx, nrorth, nitref, nrstrt >*/
/*< >*/
/*< >*/
/*< integer ido, info, ldv, lworkl, n, ncv, nev >*/
/*< >*/
/* %-----------------% */
/* | Array Arguments | */
/* %-----------------% */
/*< integer iparam(11), ipntr(11) >*/
/*< >*/
/* %------------% */
/* | Parameters | */
/* %------------% */
/*< >*/
/*< parameter (one = 1.0D+0, zero = 0.0D+0) >*/
/* %---------------% */
/* | Local Scalars | */
/* %---------------% */
/*< >*/
/*< >*/
/* %----------------------% */
/* | External Subroutines | */
/* %----------------------% */
/*< external dsaup2, second, dstats >*/
/* %--------------------% */
/* | External Functions | */
/* %--------------------% */
/*< >*/
/*< external dlamch >*/
/* %-----------------------% */
/* | Executable Statements | */
/* %-----------------------% */
/*< if (ido .eq. 0) then >*/
/* Parameter adjustments */
--workd;
--resid;
v_dim1 = *ldv;
v_offset = 1 + v_dim1;
v -= v_offset;
--iparam;
--ipntr;
--workl;
/* Function Body */
if (*ido == 0) {
/* %-------------------------------% */
/* | Initialize timing statistics | */
/* | & message level for debugging | */
/* %-------------------------------% */
/*< call dstats >*/
/* dstats_(); */
/*< call second (t0) >*/
/* second_(&t0); */
/*< msglvl = msaupd >*/
/* msglvl = debug_1.msaupd; */
/*< ierr = 0 >*/
ierr = 0;
/*< ishift = iparam(1) >*/
ishift = iparam[1];
/*< mxiter = iparam(3) >*/
mxiter = iparam[3];
/*< nb = iparam(4) >*/
nb = iparam[4];
/* %--------------------------------------------% */
/* | Revision 2 performs only implicit restart. | */
/* %--------------------------------------------% */
/*< iupd = 1 >*/
iupd = 1;
/*< mode = iparam(7) >*/
mode = iparam[7];
/* %----------------% */
/* | Error checking | */
/* %----------------% */
/*< if (n .le. 0) then >*/
if (*n <= 0) {
/*< ierr = -1 >*/
ierr = -1;
/*< else if (nev .le. 0) then >*/
} else if (*nev <= 0) {
/*< ierr = -2 >*/
ierr = -2;
/*< else if (ncv .le. nev .or. ncv .gt. n) then >*/
} else if (*ncv <= *nev || *ncv > *n) {
/*< ierr = -3 >*/
ierr = -3;
/*< end if >*/
}
/* %----------------------------------------------% */
/* | NP is the number of additional steps to | */
/* | extend the length NEV Lanczos factorization. | */
/* %----------------------------------------------% */
/*< np = ncv - nev >*/
np = *ncv - *nev;
/*< if (mxiter .le. 0) ierr = -4 >*/
if (mxiter <= 0) {
ierr = -4;
}
/*< >*/
if (s_cmp(which, "LM", (ftnlen)2, (ftnlen)2) != 0 && s_cmp(which,
"SM", (ftnlen)2, (ftnlen)2) != 0 && s_cmp(which, "LA", (
ftnlen)2, (ftnlen)2) != 0 && s_cmp(which, "SA", (ftnlen)2, (
ftnlen)2) != 0 && s_cmp(which, "BE", (ftnlen)2, (ftnlen)2) !=
0) {
ierr = -5;
}
/*< if (bmat .ne. 'I' .and. bmat .ne. 'G') ierr = -6 >*/
if (*(unsigned char *)bmat != 'I' && *(unsigned char *)bmat != 'G') {
ierr = -6;
}
/*< if (lworkl .lt. ncv**2 + 8*ncv) ierr = -7 >*/
/* Computing 2nd power */
i__1 = *ncv;
if (*lworkl < i__1 * i__1 + (*ncv << 3)) {
ierr = -7;
}
/*< if (mode .lt. 1 .or. mode .gt. 5) then >*/
if (mode < 1 || mode > 5) {
/*< ierr = -10 >*/
ierr = -10;
/*< else if (mode .eq. 1 .and. bmat .eq. 'G') then >*/
} else if (mode == 1 && *(unsigned char *)bmat == 'G') {
/*< ierr = -11 >*/
ierr = -11;
/*< else if (ishift .lt. 0 .or. ishift .gt. 1) then >*/
} else if (ishift < 0 || ishift > 1) {
/*< ierr = -12 >*/
ierr = -12;
/*< else if (nev .eq. 1 .and. which .eq. 'BE') then >*/
} else if (*nev == 1 && s_cmp(which, "BE", (ftnlen)2, (ftnlen)2) == 0)
{
/*< ierr = -13 >*/
ierr = -13;
/*< end if >*/
}
/* %------------% */
/* | Error Exit | */
/* %------------% */
/*< if (ierr .ne. 0) then >*/
if (ierr != 0) {
/*< info = ierr >*/
*info = ierr;
/*< ido = 99 >*/
*ido = 99;
/*< go to 9000 >*/
goto L9000;
/*< end if >*/
}
/* %------------------------% */
/* | Set default parameters | */
/* %------------------------% */
/*< if (nb .le. 0) nb = 1 >*/
if (nb <= 0) {
nb = 1;
}
/*< if (tol .le. zero) tol = dlamch('EpsMach') >*/
if (*tol <= 0.) {
*tol = dlamch_("EpsMach", (ftnlen)7);
}
/* %----------------------------------------------% */
/* | NP is the number of additional steps to | */
/* | extend the length NEV Lanczos factorization. | */
/* | NEV0 is the local variable designating the | */
/* | size of the invariant subspace desired. | */
/* %----------------------------------------------% */
/*< np = ncv - nev >*/
np = *ncv - *nev;
/*< nev0 = nev >*/
nev0 = *nev;
/* %-----------------------------% */
/* | Zero out internal workspace | */
/* %-----------------------------% */
/*< do 10 j = 1, ncv**2 + 8*ncv >*/
/* Computing 2nd power */
i__2 = *ncv;
i__1 = i__2 * i__2 + (*ncv << 3);
for (j = 1; j <= i__1; ++j) {
/*< workl(j) = zero >*/
workl[j] = 0.;
/*< 10 continue >*/
/* L10: */
}
/* %-------------------------------------------------------% */
/* | Pointer into WORKL for address of H, RITZ, BOUNDS, Q | */
/* | etc... and the remaining workspace. | */
/* | Also update pointer to be used on output. | */
/* | Memory is laid out as follows: | */
/* | workl(1:2*ncv) := generated tridiagonal matrix | */
/* | workl(2*ncv+1:2*ncv+ncv) := ritz values | */
/* | workl(3*ncv+1:3*ncv+ncv) := computed error bounds | */
/* | workl(4*ncv+1:4*ncv+ncv*ncv) := rotation matrix Q | */
/* | workl(4*ncv+ncv*ncv+1:7*ncv+ncv*ncv) := workspace | */
/* %-------------------------------------------------------% */
/*< ldh = ncv >*/
ldh = *ncv;
/*< ldq = ncv >*/
ldq = *ncv;
/*< ih = 1 >*/
ih = 1;
/*< ritz = ih + 2*ldh >*/
ritz = ih + (ldh << 1);
/*< bounds = ritz + ncv >*/
bounds = ritz + *ncv;
/*< iq = bounds + ncv >*/
iq = bounds + *ncv;
/*< iw = iq + ncv**2 >*/
/* Computing 2nd power */
i__1 = *ncv;
iw = iq + i__1 * i__1;
/*< next = iw + 3*ncv >*/
next = iw + *ncv * 3;
/*< ipntr(4) = next >*/
ipntr[4] = next;
/*< ipntr(5) = ih >*/
ipntr[5] = ih;
/*< ipntr(6) = ritz >*/
ipntr[6] = ritz;
/*< ipntr(7) = bounds >*/
ipntr[7] = bounds;
/*< ipntr(11) = iw >*/
ipntr[11] = iw;
/*< end if >*/
}
/* %-------------------------------------------------------% */
/* | Carry out the Implicitly restarted Lanczos Iteration. | */
/* %-------------------------------------------------------% */
/*< >*/
dsaup2_(ido, bmat, n, which, &nev0, &np, tol, &resid[1], &mode, &iupd, &
ishift, &mxiter, &v[v_offset], ldv, &workl[ih], &ldh, &workl[ritz]
, &workl[bounds], &workl[iq], &ldq, &workl[iw], &ipntr[1], &workd[
1], info, (ftnlen)1, (ftnlen)2);
/* %--------------------------------------------------% */
/* | ido .ne. 99 implies use of reverse communication | */
/* | to compute operations involving OP or shifts. | */
/* %--------------------------------------------------% */
/*< if (ido .eq. 3) iparam(8) = np >*/
if (*ido == 3) {
iparam[8] = np;
}
/*< if (ido .ne. 99) go to 9000 >*/
if (*ido != 99) {
goto L9000;
}
/*< iparam(3) = mxiter >*/
iparam[3] = mxiter;
/*< iparam(5) = np >*/
iparam[5] = np;
/*< iparam(9) = nopx >*/
/* iparam[9] = timing_1.nopx; */
/*< iparam(10) = nbx >*/
/* iparam[10] = timing_1.nbx; */
/*< iparam(11) = nrorth >*/
/* iparam[11] = timing_1.nrorth; */
/* %------------------------------------% */
/* | Exit if there was an informational | */
/* | error within dsaup2. | */
/* %------------------------------------% */
/*< if (info .lt. 0) go to 9000 >*/
if (*info < 0) {
goto L9000;
}
/*< if (info .eq. 2) info = 3 >*/
if (*info == 2) {
*info = 3;
}
/* if (msglvl .gt. 0) then */
/* call ivout (logfil, 1, mxiter, ndigit, */
/* & '_saupd: number of update iterations taken') */
/* call ivout (logfil, 1, np, ndigit, */
/* & '_saupd: number of "converged" Ritz values') */
/* call dvout (logfil, np, workl(Ritz), ndigit, */
/* & '_saupd: final Ritz values') */
/* call dvout (logfil, np, workl(Bounds), ndigit, */
/* & '_saupd: corresponding error bounds') */
/* end if */
/*< call second (t1) >*/
/* second_(&t1); */
/*< tsaupd = t1 - t0 >*/
/* timing_1.tsaupd = t1 - t0; */
/* if (msglvl .gt. 0) then */
/* %--------------------------------------------------------% */
/* | Version Number & Version Date are defined in version.h | */
/* %--------------------------------------------------------% */
/* write (6,1000) */
/* write (6,1100) mxiter, nopx, nbx, nrorth, nitref, nrstrt, */
/* & tmvopx, tmvbx, tsaupd, tsaup2, tsaitr, titref, */
/* & tgetv0, tseigt, tsgets, tsapps, tsconv */
/* 1000 format (//, */
/* & 5x, '==========================================',/ */
/* & 5x, '= Symmetric implicit Arnoldi update code =',/ */
/* & 5x, '= Version Number:', ' 2.4', 19x, ' =',/ */
/* & 5x, '= Version Date: ', ' 07/31/96', 14x, ' =',/ */
/* & 5x, '==========================================',/ */
/* & 5x, '= Summary of timing statistics =',/ */
/* & 5x, '==========================================',//) */
/* 1100 format ( */
/* & 5x, 'Total number update iterations = ', i5,/ */
/* & 5x, 'Total number of OP*x operations = ', i5,/ */
/* & 5x, 'Total number of B*x operations = ', i5,/ */
/* & 5x, 'Total number of reorthogonalization steps = ', i5,/ */
/* & 5x, 'Total number of iterative refinement steps = ', i5,/ */
/* & 5x, 'Total number of restart steps = ', i5,/ */
/* & 5x, 'Total time in user OP*x operation = ', f12.6,/ */
/* & 5x, 'Total time in user B*x operation = ', f12.6,/ */
/* & 5x, 'Total time in Arnoldi update routine = ', f12.6,/ */
/* & 5x, 'Total time in saup2 routine = ', f12.6,/ */
/* & 5x, 'Total time in basic Arnoldi iteration loop = ', f12.6,/ */
/* & 5x, 'Total time in reorthogonalization phase = ', f12.6,/ */
/* & 5x, 'Total time in (re)start vector generation = ', f12.6,/ */
/* & 5x, 'Total time in trid eigenvalue subproblem = ', f12.6,/ */
/* & 5x, 'Total time in getting the shifts = ', f12.6,/ */
/* & 5x, 'Total time in applying the shifts = ', f12.6,/ */
/* & 5x, 'Total time in convergence testing = ', f12.6) */
/* end if */
/*< 9000 continue >*/
L9000:
/*< return >*/
return 0;
/* %---------------% */
/* | End of dsaupd | */
/* %---------------% */
/*< end >*/
} /* dsaupd_ */
#ifdef __cplusplus
}
#endif
| apache-2.0 |
AnttiLukats/orp | third-party/qemu-orp/hw/usb/bus.c | 40 | 19391 | #include "hw/hw.h"
#include "hw/usb.h"
#include "hw/qdev.h"
#include "sysemu/sysemu.h"
#include "monitor/monitor.h"
#include "trace.h"
static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent);
static char *usb_get_dev_path(DeviceState *dev);
static char *usb_get_fw_dev_path(DeviceState *qdev);
static void usb_qdev_unrealize(DeviceState *qdev, Error **errp);
static Property usb_props[] = {
DEFINE_PROP_STRING("port", USBDevice, port_path),
DEFINE_PROP_STRING("serial", USBDevice, serial),
DEFINE_PROP_BIT("full-path", USBDevice, flags,
USB_DEV_FLAG_FULL_PATH, true),
DEFINE_PROP_BIT("msos-desc", USBDevice, flags,
USB_DEV_FLAG_MSOS_DESC_ENABLE, true),
DEFINE_PROP_END_OF_LIST()
};
static void usb_bus_class_init(ObjectClass *klass, void *data)
{
BusClass *k = BUS_CLASS(klass);
HotplugHandlerClass *hc = HOTPLUG_HANDLER_CLASS(klass);
k->print_dev = usb_bus_dev_print;
k->get_dev_path = usb_get_dev_path;
k->get_fw_dev_path = usb_get_fw_dev_path;
hc->unplug = qdev_simple_device_unplug_cb;
}
static const TypeInfo usb_bus_info = {
.name = TYPE_USB_BUS,
.parent = TYPE_BUS,
.instance_size = sizeof(USBBus),
.class_init = usb_bus_class_init,
.interfaces = (InterfaceInfo[]) {
{ TYPE_HOTPLUG_HANDLER },
{ }
}
};
static int next_usb_bus = 0;
static QTAILQ_HEAD(, USBBus) busses = QTAILQ_HEAD_INITIALIZER(busses);
static int usb_device_post_load(void *opaque, int version_id)
{
USBDevice *dev = opaque;
if (dev->state == USB_STATE_NOTATTACHED) {
dev->attached = 0;
} else {
dev->attached = 1;
}
if (dev->setup_index < 0 ||
dev->setup_len < 0 ||
dev->setup_index > dev->setup_len ||
dev->setup_len > sizeof(dev->data_buf)) {
return -EINVAL;
}
return 0;
}
const VMStateDescription vmstate_usb_device = {
.name = "USBDevice",
.version_id = 1,
.minimum_version_id = 1,
.post_load = usb_device_post_load,
.fields = (VMStateField[]) {
VMSTATE_UINT8(addr, USBDevice),
VMSTATE_INT32(state, USBDevice),
VMSTATE_INT32(remote_wakeup, USBDevice),
VMSTATE_INT32(setup_state, USBDevice),
VMSTATE_INT32(setup_len, USBDevice),
VMSTATE_INT32(setup_index, USBDevice),
VMSTATE_UINT8_ARRAY(setup_buf, USBDevice, 8),
VMSTATE_END_OF_LIST(),
}
};
void usb_bus_new(USBBus *bus, size_t bus_size,
USBBusOps *ops, DeviceState *host)
{
qbus_create_inplace(bus, bus_size, TYPE_USB_BUS, host, NULL);
qbus_set_bus_hotplug_handler(BUS(bus), &error_abort);
bus->ops = ops;
bus->busnr = next_usb_bus++;
QTAILQ_INIT(&bus->free);
QTAILQ_INIT(&bus->used);
QTAILQ_INSERT_TAIL(&busses, bus, next);
}
void usb_bus_release(USBBus *bus)
{
assert(next_usb_bus > 0);
QTAILQ_REMOVE(&busses, bus, next);
}
USBBus *usb_bus_find(int busnr)
{
USBBus *bus;
if (-1 == busnr)
return QTAILQ_FIRST(&busses);
QTAILQ_FOREACH(bus, &busses, next) {
if (bus->busnr == busnr)
return bus;
}
return NULL;
}
static void usb_device_realize(USBDevice *dev, Error **errp)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->realize) {
klass->realize(dev, errp);
}
}
USBDevice *usb_device_find_device(USBDevice *dev, uint8_t addr)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->find_device) {
return klass->find_device(dev, addr);
}
return NULL;
}
static void usb_device_handle_destroy(USBDevice *dev)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->handle_destroy) {
klass->handle_destroy(dev);
}
}
void usb_device_cancel_packet(USBDevice *dev, USBPacket *p)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->cancel_packet) {
klass->cancel_packet(dev, p);
}
}
void usb_device_handle_attach(USBDevice *dev)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->handle_attach) {
klass->handle_attach(dev);
}
}
void usb_device_handle_reset(USBDevice *dev)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->handle_reset) {
klass->handle_reset(dev);
}
}
void usb_device_handle_control(USBDevice *dev, USBPacket *p, int request,
int value, int index, int length, uint8_t *data)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->handle_control) {
klass->handle_control(dev, p, request, value, index, length, data);
}
}
void usb_device_handle_data(USBDevice *dev, USBPacket *p)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->handle_data) {
klass->handle_data(dev, p);
}
}
const char *usb_device_get_product_desc(USBDevice *dev)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
return klass->product_desc;
}
const USBDesc *usb_device_get_usb_desc(USBDevice *dev)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (dev->usb_desc) {
return dev->usb_desc;
}
return klass->usb_desc;
}
void usb_device_set_interface(USBDevice *dev, int interface,
int alt_old, int alt_new)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->set_interface) {
klass->set_interface(dev, interface, alt_old, alt_new);
}
}
void usb_device_flush_ep_queue(USBDevice *dev, USBEndpoint *ep)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->flush_ep_queue) {
klass->flush_ep_queue(dev, ep);
}
}
void usb_device_ep_stopped(USBDevice *dev, USBEndpoint *ep)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->ep_stopped) {
klass->ep_stopped(dev, ep);
}
}
int usb_device_alloc_streams(USBDevice *dev, USBEndpoint **eps, int nr_eps,
int streams)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->alloc_streams) {
return klass->alloc_streams(dev, eps, nr_eps, streams);
}
return 0;
}
void usb_device_free_streams(USBDevice *dev, USBEndpoint **eps, int nr_eps)
{
USBDeviceClass *klass = USB_DEVICE_GET_CLASS(dev);
if (klass->free_streams) {
klass->free_streams(dev, eps, nr_eps);
}
}
static void usb_qdev_realize(DeviceState *qdev, Error **errp)
{
USBDevice *dev = USB_DEVICE(qdev);
Error *local_err = NULL;
pstrcpy(dev->product_desc, sizeof(dev->product_desc),
usb_device_get_product_desc(dev));
dev->auto_attach = 1;
QLIST_INIT(&dev->strings);
usb_ep_init(dev);
usb_claim_port(dev, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
usb_device_realize(dev, &local_err);
if (local_err) {
usb_release_port(dev);
error_propagate(errp, local_err);
return;
}
if (dev->auto_attach) {
usb_device_attach(dev, &local_err);
if (local_err) {
usb_qdev_unrealize(qdev, NULL);
error_propagate(errp, local_err);
return;
}
}
}
static void usb_qdev_unrealize(DeviceState *qdev, Error **errp)
{
USBDevice *dev = USB_DEVICE(qdev);
if (dev->attached) {
usb_device_detach(dev);
}
usb_device_handle_destroy(dev);
if (dev->port) {
usb_release_port(dev);
}
}
typedef struct LegacyUSBFactory
{
const char *name;
const char *usbdevice_name;
USBDevice *(*usbdevice_init)(USBBus *bus, const char *params);
} LegacyUSBFactory;
static GSList *legacy_usb_factory;
void usb_legacy_register(const char *typename, const char *usbdevice_name,
USBDevice *(*usbdevice_init)(USBBus *bus,
const char *params))
{
if (usbdevice_name) {
LegacyUSBFactory *f = g_malloc0(sizeof(*f));
f->name = typename;
f->usbdevice_name = usbdevice_name;
f->usbdevice_init = usbdevice_init;
legacy_usb_factory = g_slist_append(legacy_usb_factory, f);
}
}
USBDevice *usb_create(USBBus *bus, const char *name)
{
DeviceState *dev;
dev = qdev_create(&bus->qbus, name);
return USB_DEVICE(dev);
}
USBDevice *usb_create_simple(USBBus *bus, const char *name)
{
USBDevice *dev = usb_create(bus, name);
int rc;
if (!dev) {
error_report("Failed to create USB device '%s'", name);
return NULL;
}
rc = qdev_init(&dev->qdev);
if (rc < 0) {
error_report("Failed to initialize USB device '%s'", name);
return NULL;
}
return dev;
}
static void usb_fill_port(USBPort *port, void *opaque, int index,
USBPortOps *ops, int speedmask)
{
port->opaque = opaque;
port->index = index;
port->ops = ops;
port->speedmask = speedmask;
usb_port_location(port, NULL, index + 1);
}
void usb_register_port(USBBus *bus, USBPort *port, void *opaque, int index,
USBPortOps *ops, int speedmask)
{
usb_fill_port(port, opaque, index, ops, speedmask);
QTAILQ_INSERT_TAIL(&bus->free, port, next);
bus->nfree++;
}
int usb_register_companion(const char *masterbus, USBPort *ports[],
uint32_t portcount, uint32_t firstport,
void *opaque, USBPortOps *ops, int speedmask)
{
USBBus *bus;
int i;
QTAILQ_FOREACH(bus, &busses, next) {
if (strcmp(bus->qbus.name, masterbus) == 0) {
break;
}
}
if (!bus || !bus->ops->register_companion) {
qerror_report(QERR_INVALID_PARAMETER_VALUE, "masterbus",
"an USB masterbus");
if (bus) {
error_printf_unless_qmp(
"USB bus '%s' does not allow companion controllers\n",
masterbus);
}
return -1;
}
for (i = 0; i < portcount; i++) {
usb_fill_port(ports[i], opaque, i, ops, speedmask);
}
return bus->ops->register_companion(bus, ports, portcount, firstport);
}
void usb_port_location(USBPort *downstream, USBPort *upstream, int portnr)
{
if (upstream) {
snprintf(downstream->path, sizeof(downstream->path), "%s.%d",
upstream->path, portnr);
downstream->hubcount = upstream->hubcount + 1;
} else {
snprintf(downstream->path, sizeof(downstream->path), "%d", portnr);
downstream->hubcount = 0;
}
}
void usb_unregister_port(USBBus *bus, USBPort *port)
{
if (port->dev) {
object_unparent(OBJECT(port->dev));
}
QTAILQ_REMOVE(&bus->free, port, next);
bus->nfree--;
}
void usb_claim_port(USBDevice *dev, Error **errp)
{
USBBus *bus = usb_bus_from_device(dev);
USBPort *port;
assert(dev->port == NULL);
if (dev->port_path) {
QTAILQ_FOREACH(port, &bus->free, next) {
if (strcmp(port->path, dev->port_path) == 0) {
break;
}
}
if (port == NULL) {
error_setg(errp, "Error: usb port %s (bus %s) not found (in use?)",
dev->port_path, bus->qbus.name);
return;
}
} else {
if (bus->nfree == 1 && strcmp(object_get_typename(OBJECT(dev)), "usb-hub") != 0) {
/* Create a new hub and chain it on */
usb_create_simple(bus, "usb-hub");
}
if (bus->nfree == 0) {
error_setg(errp, "Error: tried to attach usb device %s to a bus "
"with no free ports", dev->product_desc);
return;
}
port = QTAILQ_FIRST(&bus->free);
}
trace_usb_port_claim(bus->busnr, port->path);
QTAILQ_REMOVE(&bus->free, port, next);
bus->nfree--;
dev->port = port;
port->dev = dev;
QTAILQ_INSERT_TAIL(&bus->used, port, next);
bus->nused++;
}
void usb_release_port(USBDevice *dev)
{
USBBus *bus = usb_bus_from_device(dev);
USBPort *port = dev->port;
assert(port != NULL);
trace_usb_port_release(bus->busnr, port->path);
QTAILQ_REMOVE(&bus->used, port, next);
bus->nused--;
dev->port = NULL;
port->dev = NULL;
QTAILQ_INSERT_TAIL(&bus->free, port, next);
bus->nfree++;
}
static void usb_mask_to_str(char *dest, size_t size,
unsigned int speedmask)
{
static const struct {
unsigned int mask;
const char *name;
} speeds[] = {
{ .mask = USB_SPEED_MASK_FULL, .name = "full" },
{ .mask = USB_SPEED_MASK_HIGH, .name = "high" },
{ .mask = USB_SPEED_MASK_SUPER, .name = "super" },
};
int i, pos = 0;
for (i = 0; i < ARRAY_SIZE(speeds); i++) {
if (speeds[i].mask & speedmask) {
pos += snprintf(dest + pos, size - pos, "%s%s",
pos ? "+" : "",
speeds[i].name);
}
}
}
void usb_check_attach(USBDevice *dev, Error **errp)
{
USBBus *bus = usb_bus_from_device(dev);
USBPort *port = dev->port;
char devspeed[32], portspeed[32];
assert(port != NULL);
assert(!dev->attached);
usb_mask_to_str(devspeed, sizeof(devspeed), dev->speedmask);
usb_mask_to_str(portspeed, sizeof(portspeed), port->speedmask);
trace_usb_port_attach(bus->busnr, port->path,
devspeed, portspeed);
if (!(port->speedmask & dev->speedmask)) {
error_setg(errp, "Warning: speed mismatch trying to attach"
" usb device \"%s\" (%s speed)"
" to bus \"%s\", port \"%s\" (%s speed)",
dev->product_desc, devspeed,
bus->qbus.name, port->path, portspeed);
return;
}
}
void usb_device_attach(USBDevice *dev, Error **errp)
{
USBPort *port = dev->port;
Error *local_err = NULL;
usb_check_attach(dev, &local_err);
if (local_err) {
error_propagate(errp, local_err);
return;
}
dev->attached++;
usb_attach(port);
}
int usb_device_detach(USBDevice *dev)
{
USBBus *bus = usb_bus_from_device(dev);
USBPort *port = dev->port;
assert(port != NULL);
assert(dev->attached);
trace_usb_port_detach(bus->busnr, port->path);
usb_detach(port);
dev->attached--;
return 0;
}
int usb_device_delete_addr(int busnr, int addr)
{
USBBus *bus;
USBPort *port;
USBDevice *dev;
bus = usb_bus_find(busnr);
if (!bus)
return -1;
QTAILQ_FOREACH(port, &bus->used, next) {
if (port->dev->addr == addr)
break;
}
if (!port)
return -1;
dev = port->dev;
object_unparent(OBJECT(dev));
return 0;
}
static const char *usb_speed(unsigned int speed)
{
static const char *txt[] = {
[ USB_SPEED_LOW ] = "1.5",
[ USB_SPEED_FULL ] = "12",
[ USB_SPEED_HIGH ] = "480",
[ USB_SPEED_SUPER ] = "5000",
};
if (speed >= ARRAY_SIZE(txt))
return "?";
return txt[speed];
}
static void usb_bus_dev_print(Monitor *mon, DeviceState *qdev, int indent)
{
USBDevice *dev = USB_DEVICE(qdev);
USBBus *bus = usb_bus_from_device(dev);
monitor_printf(mon, "%*saddr %d.%d, port %s, speed %s, name %s%s\n",
indent, "", bus->busnr, dev->addr,
dev->port ? dev->port->path : "-",
usb_speed(dev->speed), dev->product_desc,
dev->attached ? ", attached" : "");
}
static char *usb_get_dev_path(DeviceState *qdev)
{
USBDevice *dev = USB_DEVICE(qdev);
DeviceState *hcd = qdev->parent_bus->parent;
char *id = NULL;
if (dev->flags & (1 << USB_DEV_FLAG_FULL_PATH)) {
id = qdev_get_dev_path(hcd);
}
if (id) {
char *ret = g_strdup_printf("%s/%s", id, dev->port->path);
g_free(id);
return ret;
} else {
return g_strdup(dev->port->path);
}
}
static char *usb_get_fw_dev_path(DeviceState *qdev)
{
USBDevice *dev = USB_DEVICE(qdev);
char *fw_path, *in;
ssize_t pos = 0, fw_len;
long nr;
fw_len = 32 + strlen(dev->port->path) * 6;
fw_path = g_malloc(fw_len);
in = dev->port->path;
while (fw_len - pos > 0) {
nr = strtol(in, &in, 10);
if (in[0] == '.') {
/* some hub between root port and device */
pos += snprintf(fw_path + pos, fw_len - pos, "hub@%lx/", nr);
in++;
} else {
/* the device itself */
pos += snprintf(fw_path + pos, fw_len - pos, "%s@%lx",
qdev_fw_name(qdev), nr);
break;
}
}
return fw_path;
}
void usb_info(Monitor *mon, const QDict *qdict)
{
USBBus *bus;
USBDevice *dev;
USBPort *port;
if (QTAILQ_EMPTY(&busses)) {
monitor_printf(mon, "USB support not enabled\n");
return;
}
QTAILQ_FOREACH(bus, &busses, next) {
QTAILQ_FOREACH(port, &bus->used, next) {
dev = port->dev;
if (!dev)
continue;
monitor_printf(mon, " Device %d.%d, Port %s, Speed %s Mb/s, Product %s\n",
bus->busnr, dev->addr, port->path, usb_speed(dev->speed),
dev->product_desc);
}
}
}
/* handle legacy -usbdevice cmd line option */
USBDevice *usbdevice_create(const char *cmdline)
{
USBBus *bus = usb_bus_find(-1 /* any */);
LegacyUSBFactory *f = NULL;
GSList *i;
char driver[32];
const char *params;
int len;
params = strchr(cmdline,':');
if (params) {
params++;
len = params - cmdline;
if (len > sizeof(driver))
len = sizeof(driver);
pstrcpy(driver, len, cmdline);
} else {
params = "";
pstrcpy(driver, sizeof(driver), cmdline);
}
for (i = legacy_usb_factory; i; i = i->next) {
f = i->data;
if (strcmp(f->usbdevice_name, driver) == 0) {
break;
}
}
if (i == NULL) {
#if 0
/* no error because some drivers are not converted (yet) */
error_report("usbdevice %s not found", driver);
#endif
return NULL;
}
if (!bus) {
error_report("Error: no usb bus to attach usbdevice %s, "
"please try -machine usb=on and check that "
"the machine model supports USB", driver);
return NULL;
}
if (!f->usbdevice_init) {
if (*params) {
error_report("usbdevice %s accepts no params", driver);
return NULL;
}
return usb_create_simple(bus, f->name);
}
return f->usbdevice_init(bus, params);
}
static void usb_device_class_init(ObjectClass *klass, void *data)
{
DeviceClass *k = DEVICE_CLASS(klass);
k->bus_type = TYPE_USB_BUS;
k->realize = usb_qdev_realize;
k->unrealize = usb_qdev_unrealize;
k->props = usb_props;
}
static const TypeInfo usb_device_type_info = {
.name = TYPE_USB_DEVICE,
.parent = TYPE_DEVICE,
.instance_size = sizeof(USBDevice),
.abstract = true,
.class_size = sizeof(USBDeviceClass),
.class_init = usb_device_class_init,
};
static void usb_register_types(void)
{
type_register_static(&usb_bus_info);
type_register_static(&usb_device_type_info);
}
type_init(usb_register_types)
| apache-2.0 |
c1728p9/mbed-os | targets/TARGET_STM/TARGET_STM32F4/device/stm32f4xx_hal_fmpi2c.c | 43 | 169754 | /**
******************************************************************************
* @file stm32f4xx_hal_fmpi2c.c
* @author MCD Application Team
* @brief FMPI2C HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Inter Integrated Circuit (FMPI2C) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral State and Errors functions
*
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The FMPI2C HAL driver can be used as follows:
(#) Declare a FMPI2C_HandleTypeDef handle structure, for example:
FMPI2C_HandleTypeDef hfmpi2c;
(#)Initialize the FMPI2C low level resources by implementing the HAL_FMPI2C_MspInit() API:
(##) Enable the FMPI2Cx interface clock
(##) FMPI2C pins configuration
(+++) Enable the clock for the FMPI2C GPIOs
(+++) Configure FMPI2C pins as alternate function open-drain
(##) NVIC configuration if you need to use interrupt process
(+++) Configure the FMPI2Cx interrupt priority
(+++) Enable the NVIC FMPI2C IRQ Channel
(##) DMA Configuration if you need to use DMA process
(+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream
(+++) Enable the DMAx interface clock using
(+++) Configure the DMA handle parameters
(+++) Configure the DMA Tx or Rx stream
(+++) Associate the initialized DMA handle to the hfmpi2c DMA Tx or Rx handle
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on
the DMA Tx or Rx stream
(#) Configure the Communication Clock Timing, Own Address1, Master Addressing mode, Dual Addressing mode,
Own Address2, Own Address2 Mask, General call and Nostretch mode in the hfmpi2c Init structure.
(#) Initialize the FMPI2C registers by calling the HAL_FMPI2C_Init(), configures also the low level Hardware
(GPIO, CLOCK, NVIC...etc) by calling the customized HAL_FMPI2C_MspInit(&hfmpi2c) API.
(#) To check if target device is ready for communication, use the function HAL_FMPI2C_IsDeviceReady()
(#) For FMPI2C IO and IO MEM operations, three operation modes are available within this driver :
*** Polling mode IO operation ***
=================================
[..]
(+) Transmit in master mode an amount of data in blocking mode using HAL_FMPI2C_Master_Transmit()
(+) Receive in master mode an amount of data in blocking mode using HAL_FMPI2C_Master_Receive()
(+) Transmit in slave mode an amount of data in blocking mode using HAL_FMPI2C_Slave_Transmit()
(+) Receive in slave mode an amount of data in blocking mode using HAL_FMPI2C_Slave_Receive()
*** Polling mode IO MEM operation ***
=====================================
[..]
(+) Write an amount of data in blocking mode to a specific memory address using HAL_FMPI2C_Mem_Write()
(+) Read an amount of data in blocking mode from a specific memory address using HAL_FMPI2C_Mem_Read()
*** Interrupt mode IO operation ***
===================================
[..]
(+) Transmit in master mode an amount of data in non-blocking mode using HAL_FMPI2C_Master_Transmit_IT()
(+) At transmission end of transfer, HAL_FMPI2C_MasterTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MasterTxCpltCallback()
(+) Receive in master mode an amount of data in non-blocking mode using HAL_FMPI2C_Master_Receive_IT()
(+) At reception end of transfer, HAL_FMPI2C_MasterRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MasterRxCpltCallback()
(+) Transmit in slave mode an amount of data in non-blocking mode using HAL_FMPI2C_Slave_Transmit_IT()
(+) At transmission end of transfer, HAL_FMPI2C_SlaveTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_SlaveTxCpltCallback()
(+) Receive in slave mode an amount of data in non-blocking mode using HAL_FMPI2C_Slave_Receive_IT()
(+) At reception end of transfer, HAL_FMPI2C_SlaveRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_SlaveRxCpltCallback()
(+) In case of transfer Error, HAL_FMPI2C_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_ErrorCallback()
(+) Abort a master FMPI2C process communication with Interrupt using HAL_FMPI2C_Master_Abort_IT()
(+) End of abort process, HAL_FMPI2C_AbortCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_AbortCpltCallback()
(+) Discard a slave FMPI2C process communication using __HAL_FMPI2C_GENERATE_NACK() macro.
This action will inform Master to generate a Stop condition to discard the communication.
*** Interrupt mode IO sequential operation ***
==============================================
[..]
(@) These interfaces allow to manage a sequential transfer with a repeated start condition
when a direction change during transfer
[..]
(+) A specific option field manage the different steps of a sequential transfer
(+) Option field values are defined through @ref FMPI2C_XFEROPTIONS and are listed below:
(++) FMPI2C_FIRST_AND_LAST_FRAME: No sequential usage, functionnal is same as associated interfaces in no sequential mode
(++) FMPI2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address
and data to transfer without a final stop condition
(++) FMPI2C_FIRST_AND_NEXT_FRAME: Sequential usage (Master only), this option allow to manage a sequence with start condition, address
and data to transfer without a final stop condition, an then permit a call the same master sequential interface
several times (like HAL_FMPI2C_Master_Sequential_Transmit_IT() then HAL_FMPI2C_Master_Sequential_Transmit_IT())
(++) FMPI2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address
and with new data to transfer if the direction change or manage only the new data to transfer
if no direction change and without a final stop condition in both cases
(++) FMPI2C_LAST_FRAME: Sequential usage, this option allow to manage a sequance with a restart condition, address
and with new data to transfer if the direction change or manage only the new data to transfer
if no direction change and with a final stop condition in both cases
(++) FMPI2C_LAST_FRAME_NO_STOP: Sequential usage (Master only), this option allow to manage a restart condition after several call of the same master sequential
interface several times (link with option FMPI2C_FIRST_AND_NEXT_FRAME).
Usage can, transfer several bytes one by one using HAL_FMPI2C_Master_Sequential_Transmit_IT(option FMPI2C_FIRST_AND_NEXT_FRAME then FMPI2C_NEXT_FRAME)
or HAL_FMPI2C_Master_Sequential_Receive_IT(option FMPI2C_FIRST_AND_NEXT_FRAME then FMPI2C_NEXT_FRAME).
Then usage of this option FMPI2C_LAST_FRAME_NO_STOP at the last Transmit or Receive sequence permit to call the oposite interface Receive or Transmit
without stopping the communication and so generate a restart condition.
(+) Differents sequential FMPI2C interfaces are listed below:
(++) Sequential transmit in master FMPI2C mode an amount of data in non-blocking mode using HAL_FMPI2C_Master_Sequential_Transmit_IT()
(+++) At transmission end of current frame transfer, HAL_FMPI2C_MasterTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MasterTxCpltCallback()
(++) Sequential receive in master FMPI2C mode an amount of data in non-blocking mode using HAL_FMPI2C_Master_Sequential_Receive_IT()
(+++) At reception end of current frame transfer, HAL_FMPI2C_MasterRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MasterRxCpltCallback()
(++) Abort a master FMPI2C process communication with Interrupt using HAL_FMPI2C_Master_Abort_IT()
(+++) End of abort process, HAL_FMPI2C_AbortCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_AbortCpltCallback()
(++) Enable/disable the Address listen mode in slave FMPI2C mode using HAL_FMPI2C_EnableListen_IT() HAL_FMPI2C_DisableListen_IT()
(+++) When address slave FMPI2C match, HAL_FMPI2C_AddrCallback() is executed and user can
add his own code to check the Address Match Code and the transmission direction request by master (Write/Read).
(+++) At Listen mode end HAL_FMPI2C_ListenCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_ListenCpltCallback()
(++) Sequential transmit in slave FMPI2C mode an amount of data in non-blocking mode using HAL_FMPI2C_Slave_Sequential_Transmit_IT()
(+++) At transmission end of current frame transfer, HAL_FMPI2C_SlaveTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_SlaveTxCpltCallback()
(++) Sequential receive in slave FMPI2C mode an amount of data in non-blocking mode using HAL_FMPI2C_Slave_Sequential_Receive_IT()
(+++) At reception end of current frame transfer, HAL_FMPI2C_SlaveRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_SlaveRxCpltCallback()
(++) In case of transfer Error, HAL_FMPI2C_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_ErrorCallback()
(++) Abort a master FMPI2C process communication with Interrupt using HAL_FMPI2C_Master_Abort_IT()
(++) End of abort process, HAL_FMPI2C_AbortCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_AbortCpltCallback()
(++) Discard a slave FMPI2C process communication using __HAL_FMPI2C_GENERATE_NACK() macro.
This action will inform Master to generate a Stop condition to discard the communication.
*** Interrupt mode IO MEM operation ***
=======================================
[..]
(+) Write an amount of data in non-blocking mode with Interrupt to a specific memory address using
HAL_FMPI2C_Mem_Write_IT()
(+) At Memory end of write transfer, HAL_FMPI2C_MemTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MemTxCpltCallback()
(+) Read an amount of data in non-blocking mode with Interrupt from a specific memory address using
HAL_FMPI2C_Mem_Read_IT()
(+) At Memory end of read transfer, HAL_FMPI2C_MemRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MemRxCpltCallback()
(+) In case of transfer Error, HAL_FMPI2C_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_ErrorCallback()
*** DMA mode IO operation ***
==============================
[..]
(+) Transmit in master mode an amount of data in non-blocking mode (DMA) using
HAL_FMPI2C_Master_Transmit_DMA()
(+) At transmission end of transfer, HAL_FMPI2C_MasterTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MasterTxCpltCallback()
(+) Receive in master mode an amount of data in non-blocking mode (DMA) using
HAL_FMPI2C_Master_Receive_DMA()
(+) At reception end of transfer, HAL_FMPI2C_MasterRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MasterRxCpltCallback()
(+) Transmit in slave mode an amount of data in non-blocking mode (DMA) using
HAL_FMPI2C_Slave_Transmit_DMA()
(+) At transmission end of transfer, HAL_FMPI2C_SlaveTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_SlaveTxCpltCallback()
(+) Receive in slave mode an amount of data in non-blocking mode (DMA) using
HAL_FMPI2C_Slave_Receive_DMA()
(+) At reception end of transfer, HAL_FMPI2C_SlaveRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_SlaveRxCpltCallback()
(+) In case of transfer Error, HAL_FMPI2C_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_ErrorCallback()
(+) Abort a master FMPI2C process communication with Interrupt using HAL_FMPI2C_Master_Abort_IT()
(+) End of abort process, HAL_FMPI2C_AbortCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_AbortCpltCallback()
(+) Discard a slave FMPI2C process communication using __HAL_FMPI2C_GENERATE_NACK() macro.
This action will inform Master to generate a Stop condition to discard the communication.
*** DMA mode IO MEM operation ***
=================================
[..]
(+) Write an amount of data in non-blocking mode with DMA to a specific memory address using
HAL_FMPI2C_Mem_Write_DMA()
(+) At Memory end of write transfer, HAL_FMPI2C_MemTxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MemTxCpltCallback()
(+) Read an amount of data in non-blocking mode with DMA from a specific memory address using
HAL_FMPI2C_Mem_Read_DMA()
(+) At Memory end of read transfer, HAL_FMPI2C_MemRxCpltCallback() is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_MemRxCpltCallback()
(+) In case of transfer Error, HAL_FMPI2C_ErrorCallback() function is executed and user can
add his own code by customization of function pointer HAL_FMPI2C_ErrorCallback()
*** FMPI2C HAL driver macros list ***
==================================
[..]
Below the list of most used macros in FMPI2C HAL driver.
(+) __HAL_FMPI2C_ENABLE: Enable the FMPI2C peripheral
(+) __HAL_FMPI2C_DISABLE: Disable the FMPI2C peripheral
(+) __HAL_FMPI2C_GENERATE_NACK: Generate a Non-Acknowledge FMPI2C peripheral in Slave mode
(+) __HAL_FMPI2C_GET_FLAG: Check whether the specified FMPI2C flag is set or not
(+) __HAL_FMPI2C_CLEAR_FLAG: Clear the specified FMPI2C pending flag
(+) __HAL_FMPI2C_ENABLE_IT: Enable the specified FMPI2C interrupt
(+) __HAL_FMPI2C_DISABLE_IT: Disable the specified FMPI2C interrupt
[..]
(@) You can refer to the FMPI2C HAL driver header file for more useful macros
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup FMPI2C FMPI2C
* @brief FMPI2C HAL module driver
* @{
*/
#ifdef HAL_FMPI2C_MODULE_ENABLED
#if defined(STM32F410Tx) || defined(STM32F410Cx) || defined(STM32F410Rx) || defined(STM32F446xx) || defined(STM32F412Zx) ||\
defined(STM32F412Vx) || defined(STM32F412Rx) || defined(STM32F412Cx) || defined(STM32F413xx) || defined(STM32F423xx)
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup FMPI2C_Private_Define FMPI2C Private Define
* @{
*/
#define TIMING_CLEAR_MASK (0xF0FFFFFFU) /*!< FMPI2C TIMING clear register Mask */
#define FMPI2C_TIMEOUT_ADDR (10000U) /*!< 10 s */
#define FMPI2C_TIMEOUT_BUSY (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_DIR (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_RXNE (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_STOPF (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_TC (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_TCR (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_TXIS (25U) /*!< 25 ms */
#define FMPI2C_TIMEOUT_FLAG (25U) /*!< 25 ms */
#define MAX_NBYTE_SIZE 255U
#define SlaveAddr_SHIFT 7U
#define SlaveAddr_MSK 0x06U
/* Private define for @ref PreviousState usage */
#define FMPI2C_STATE_MSK ((uint32_t)((HAL_FMPI2C_STATE_BUSY_TX | HAL_FMPI2C_STATE_BUSY_RX) & (~((uint32_t)HAL_FMPI2C_STATE_READY)))) /*!< Mask State define, keep only RX and TX bits */
#define FMPI2C_STATE_NONE ((uint32_t)(HAL_FMPI2C_MODE_NONE)) /*!< Default Value */
#define FMPI2C_STATE_MASTER_BUSY_TX ((uint32_t)((HAL_FMPI2C_STATE_BUSY_TX & FMPI2C_STATE_MSK) | HAL_FMPI2C_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */
#define FMPI2C_STATE_MASTER_BUSY_RX ((uint32_t)((HAL_FMPI2C_STATE_BUSY_RX & FMPI2C_STATE_MSK) | HAL_FMPI2C_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */
#define FMPI2C_STATE_SLAVE_BUSY_TX ((uint32_t)((HAL_FMPI2C_STATE_BUSY_TX & FMPI2C_STATE_MSK) | HAL_FMPI2C_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */
#define FMPI2C_STATE_SLAVE_BUSY_RX ((uint32_t)((HAL_FMPI2C_STATE_BUSY_RX & FMPI2C_STATE_MSK) | HAL_FMPI2C_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */
#define FMPI2C_STATE_MEM_BUSY_TX ((uint32_t)((HAL_FMPI2C_STATE_BUSY_TX & FMPI2C_STATE_MSK) | HAL_FMPI2C_MODE_MEM)) /*!< Memory Busy TX, combinaison of State LSB and Mode enum */
#define FMPI2C_STATE_MEM_BUSY_RX ((uint32_t)((HAL_FMPI2C_STATE_BUSY_RX & FMPI2C_STATE_MSK) | HAL_FMPI2C_MODE_MEM)) /*!< Memory Busy RX, combinaison of State LSB and Mode enum */
/* Private define to centralize the enable/disable of Interrupts */
#define FMPI2C_XFER_TX_IT (0x00000001U)
#define FMPI2C_XFER_RX_IT (0x00000002U)
#define FMPI2C_XFER_LISTEN_IT (0x00000004U)
#define FMPI2C_XFER_ERROR_IT (0x00000011U)
#define FMPI2C_XFER_CPLT_IT (0x00000012U)
#define FMPI2C_XFER_RELOAD_IT (0x00000012U)
/* Private define Sequential Transfer Options default/reset value */
#define FMPI2C_NO_OPTION_FRAME (0xFFFF0000U)
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
#define FMPI2C_GET_DMA_REMAIN_DATA(__HANDLE__) ((((__HANDLE__)->State) == HAL_FMPI2C_STATE_BUSY_TX) ? \
((uint32_t)(((DMA_Stream_TypeDef *)(__HANDLE__)->hdmatx->Instance)->NDTR)) : \
((uint32_t)(((DMA_Stream_TypeDef *)(__HANDLE__)->hdmarx->Instance)->NDTR)))
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup FMPI2C_Private_Functions FMPI2C Private Functions
* @{
*/
/* Private functions to handle DMA transfer */
static void FMPI2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma);
static void FMPI2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma);
static void FMPI2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma);
static void FMPI2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma);
static void FMPI2C_DMAError(DMA_HandleTypeDef *hdma);
static void FMPI2C_DMAAbort(DMA_HandleTypeDef *hdma);
/* Private functions to handle IT transfer */
static void FMPI2C_ITAddrCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags);
static void FMPI2C_ITMasterSequentialCplt(FMPI2C_HandleTypeDef *hfmpi2c);
static void FMPI2C_ITSlaveSequentialCplt(FMPI2C_HandleTypeDef *hfmpi2c);
static void FMPI2C_ITMasterCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags);
static void FMPI2C_ITSlaveCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags);
static void FMPI2C_ITListenCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags);
static void FMPI2C_ITError(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ErrorCode);
/* Private functions to handle IT transfer */
static HAL_StatusTypeDef FMPI2C_RequestMemoryWrite(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef FMPI2C_RequestMemoryRead(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart);
/* Private functions for FMPI2C transfer IRQ handler */
static HAL_StatusTypeDef FMPI2C_Master_ISR_IT(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources);
static HAL_StatusTypeDef FMPI2C_Slave_ISR_IT(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources);
static HAL_StatusTypeDef FMPI2C_Master_ISR_DMA(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources);
static HAL_StatusTypeDef FMPI2C_Slave_ISR_DMA(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources);
/* Private functions to handle flags during polling transfer */
static HAL_StatusTypeDef FMPI2C_WaitOnFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef FMPI2C_WaitOnTXISFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef FMPI2C_WaitOnRXNEFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef FMPI2C_WaitOnSTOPFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart);
static HAL_StatusTypeDef FMPI2C_IsAcknowledgeFailed(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart);
/* Private functions to centralize the enable/disable of Interrupts */
static HAL_StatusTypeDef FMPI2C_Enable_IRQ(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t InterruptRequest);
static HAL_StatusTypeDef FMPI2C_Disable_IRQ(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t InterruptRequest);
/* Private functions to flush TXDR register */
static void FMPI2C_Flush_TXDR(FMPI2C_HandleTypeDef *hfmpi2c);
/* Private functions to handle start, restart or stop a transfer */
static void FMPI2C_TransferConfig(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup FMPI2C_Exported_Functions FMPI2C Exported Functions
* @{
*/
/** @defgroup FMPI2C_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to initialize and
deinitialize the FMPI2Cx peripheral:
(+) User must Implement HAL_FMPI2C_MspInit() function in which he configures
all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
(+) Call the function HAL_FMPI2C_Init() to configure the selected device with
the selected configuration:
(++) Clock Timing
(++) Own Address 1
(++) Addressing mode (Master, Slave)
(++) Dual Addressing mode
(++) Own Address 2
(++) Own Address 2 Mask
(++) General call mode
(++) Nostretch mode
(+) Call the function HAL_FMPI2C_DeInit() to restore the default configuration
of the selected FMPI2Cx peripheral.
@endverbatim
* @{
*/
/**
* @brief Initializes the FMPI2C according to the specified parameters
* in the FMPI2C_InitTypeDef and initialize the associated handle.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Init(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Check the FMPI2C handle allocation */
if (hfmpi2c == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_FMPI2C_ALL_INSTANCE(hfmpi2c->Instance));
assert_param(IS_FMPI2C_OWN_ADDRESS1(hfmpi2c->Init.OwnAddress1));
assert_param(IS_FMPI2C_ADDRESSING_MODE(hfmpi2c->Init.AddressingMode));
assert_param(IS_FMPI2C_DUAL_ADDRESS(hfmpi2c->Init.DualAddressMode));
assert_param(IS_FMPI2C_OWN_ADDRESS2(hfmpi2c->Init.OwnAddress2));
assert_param(IS_FMPI2C_OWN_ADDRESS2_MASK(hfmpi2c->Init.OwnAddress2Masks));
assert_param(IS_FMPI2C_GENERAL_CALL(hfmpi2c->Init.GeneralCallMode));
assert_param(IS_FMPI2C_NO_STRETCH(hfmpi2c->Init.NoStretchMode));
if (hfmpi2c->State == HAL_FMPI2C_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hfmpi2c->Lock = HAL_UNLOCKED;
/* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */
HAL_FMPI2C_MspInit(hfmpi2c);
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY;
/* Disable the selected FMPI2C peripheral */
__HAL_FMPI2C_DISABLE(hfmpi2c);
/*---------------------------- FMPI2Cx TIMINGR Configuration ------------------*/
/* Configure FMPI2Cx: Frequency range */
hfmpi2c->Instance->TIMINGR = hfmpi2c->Init.Timing & TIMING_CLEAR_MASK;
/*---------------------------- FMPI2Cx OAR1 Configuration ---------------------*/
/* Disable Own Address1 before set the Own Address1 configuration */
hfmpi2c->Instance->OAR1 &= ~FMPI2C_OAR1_OA1EN;
/* Configure FMPI2Cx: Own Address1 and ack own address1 mode */
if (hfmpi2c->Init.AddressingMode == FMPI2C_ADDRESSINGMODE_7BIT)
{
hfmpi2c->Instance->OAR1 = (FMPI2C_OAR1_OA1EN | hfmpi2c->Init.OwnAddress1);
}
else /* FMPI2C_ADDRESSINGMODE_10BIT */
{
hfmpi2c->Instance->OAR1 = (FMPI2C_OAR1_OA1EN | FMPI2C_OAR1_OA1MODE | hfmpi2c->Init.OwnAddress1);
}
/*---------------------------- FMPI2Cx CR2 Configuration ----------------------*/
/* Configure FMPI2Cx: Addressing Master mode */
if (hfmpi2c->Init.AddressingMode == FMPI2C_ADDRESSINGMODE_10BIT)
{
hfmpi2c->Instance->CR2 = (FMPI2C_CR2_ADD10);
}
/* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */
hfmpi2c->Instance->CR2 |= (FMPI2C_CR2_AUTOEND | FMPI2C_CR2_NACK);
/*---------------------------- FMPI2Cx OAR2 Configuration ---------------------*/
/* Disable Own Address2 before set the Own Address2 configuration */
hfmpi2c->Instance->OAR2 &= ~FMPI2C_DUALADDRESS_ENABLE;
/* Configure FMPI2Cx: Dual mode and Own Address2 */
hfmpi2c->Instance->OAR2 = (hfmpi2c->Init.DualAddressMode | hfmpi2c->Init.OwnAddress2 | (hfmpi2c->Init.OwnAddress2Masks << 8));
/*---------------------------- FMPI2Cx CR1 Configuration ----------------------*/
/* Configure FMPI2Cx: Generalcall and NoStretch mode */
hfmpi2c->Instance->CR1 = (hfmpi2c->Init.GeneralCallMode | hfmpi2c->Init.NoStretchMode);
/* Enable the selected FMPI2C peripheral */
__HAL_FMPI2C_ENABLE(hfmpi2c);
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
return HAL_OK;
}
/**
* @brief DeInitialize the FMPI2C peripheral.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_DeInit(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Check the FMPI2C handle allocation */
if (hfmpi2c == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_FMPI2C_ALL_INSTANCE(hfmpi2c->Instance));
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY;
/* Disable the FMPI2C Peripheral Clock */
__HAL_FMPI2C_DISABLE(hfmpi2c);
/* DeInit the low level hardware: GPIO, CLOCK, NVIC */
HAL_FMPI2C_MspDeInit(hfmpi2c);
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
hfmpi2c->State = HAL_FMPI2C_STATE_RESET;
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Release Lock */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
/**
* @brief Initialize the FMPI2C MSP.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_MspInit(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitialize the FMPI2C MSP.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_MspDeInit(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup FMPI2C_Exported_Functions_Group2 Input and Output operation functions
* @brief Data transfers functions
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to manage the FMPI2C data
transfers.
(#) There are two modes of transfer:
(++) Blocking mode : The communication is performed in the polling mode.
The status of all data processing is returned by the same function
after finishing transfer.
(++) No-Blocking mode : The communication is performed using Interrupts
or DMA. These functions return the status of the transfer startup.
The end of the data processing will be indicated through the
dedicated FMPI2C IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
(#) Blocking mode functions are :
(++) HAL_FMPI2C_Master_Transmit()
(++) HAL_FMPI2C_Master_Receive()
(++) HAL_FMPI2C_Slave_Transmit()
(++) HAL_FMPI2C_Slave_Receive()
(++) HAL_FMPI2C_Mem_Write()
(++) HAL_FMPI2C_Mem_Read()
(++) HAL_FMPI2C_IsDeviceReady()
(#) No-Blocking mode functions with Interrupt are :
(++) HAL_FMPI2C_Master_Transmit_IT()
(++) HAL_FMPI2C_Master_Receive_IT()
(++) HAL_FMPI2C_Slave_Transmit_IT()
(++) HAL_FMPI2C_Slave_Receive_IT()
(++) HAL_FMPI2C_Master_Sequential_Transmit_IT()
(++) HAL_FMPI2C_Master_Sequential_Receive_IT()
(++) HAL_FMPI2C_Slave_Sequential_Transmit_IT()
(++) HAL_FMPI2C_Slave_Sequential_Receive_IT()
(++) HAL_FMPI2C_Mem_Write_IT()
(++) HAL_FMPI2C_Mem_Read_IT()
(#) No-Blocking mode functions with DMA are :
(++) HAL_FMPI2C_Master_Transmit_DMA()
(++) HAL_FMPI2C_Master_Receive_DMA()
(++) HAL_FMPI2C_Slave_Transmit_DMA()
(++) HAL_FMPI2C_Slave_Receive_DMA()
(++) HAL_FMPI2C_Mem_Write_DMA()
(++) HAL_FMPI2C_Mem_Read_DMA()
(#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
(++) HAL_FMPI2C_MemTxCpltCallback()
(++) HAL_FMPI2C_MemRxCpltCallback()
(++) HAL_FMPI2C_MasterTxCpltCallback()
(++) HAL_FMPI2C_MasterRxCpltCallback()
(++) HAL_FMPI2C_SlaveTxCpltCallback()
(++) HAL_FMPI2C_SlaveRxCpltCallback()
(++) HAL_FMPI2C_ErrorCallback()
@endverbatim
* @{
*/
/**
* @brief Transmits in master mode an amount of data in blocking mode.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_BUSY, SET, FMPI2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferISR = NULL;
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_GENERATE_START_WRITE);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_GENERATE_START_WRITE);
}
while (hfmpi2c->XferCount > 0U)
{
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Write data to TXDR */
hfmpi2c->Instance->TXDR = (*hfmpi2c->pBuffPtr++);
hfmpi2c->XferCount--;
hfmpi2c->XferSize--;
if ((hfmpi2c->XferSize == 0U) && (hfmpi2c->XferCount != 0U))
{
/* Wait until TCR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_NO_STARTSTOP);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_NO_STARTSTOP);
}
}
}
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is set */
if (FMPI2C_WaitOnSTOPFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives in master mode an amount of data in blocking mode.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Receive(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_BUSY, SET, FMPI2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferISR = NULL;
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_GENERATE_START_READ);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_GENERATE_START_READ);
}
while (hfmpi2c->XferCount > 0U)
{
/* Wait until RXNE flag is set */
if (FMPI2C_WaitOnRXNEFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
if ((hfmpi2c->XferSize == 0U) && (hfmpi2c->XferCount != 0U))
{
/* Wait until TCR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_NO_STARTSTOP);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_NO_STARTSTOP);
}
}
}
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is set */
if (FMPI2C_WaitOnSTOPFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmits in slave mode an amount of data in blocking mode.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferISR = NULL;
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Wait until ADDR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
/* If 10bit addressing mode is selected */
if (hfmpi2c->Init.AddressingMode == FMPI2C_ADDRESSINGMODE_10BIT)
{
/* Wait until ADDR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
}
/* Wait until DIR flag is set Transmitter mode */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_DIR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
while (hfmpi2c->XferCount > 0U)
{
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Write data to TXDR */
hfmpi2c->Instance->TXDR = (*hfmpi2c->pBuffPtr++);
hfmpi2c->XferCount--;
}
/* Wait until STOP flag is set */
if (FMPI2C_WaitOnSTOPFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Normal use case for Transmitter mode */
/* A NACK is generated to confirm the end of transfer */
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
}
else
{
return HAL_TIMEOUT;
}
}
/* Clear STOP flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Wait until BUSY flag is reset */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in slave mode an amount of data in blocking mode
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferISR = NULL;
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Wait until ADDR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
/* Wait until DIR flag is reset Receiver mode */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_DIR, SET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
while (hfmpi2c->XferCount > 0U)
{
/* Wait until RXNE flag is set */
if (FMPI2C_WaitOnRXNEFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
/* Store Last receive data if any */
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_RXNE) == SET)
{
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
hfmpi2c->XferCount--;
}
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_TIMEOUT)
{
return HAL_TIMEOUT;
}
else
{
return HAL_ERROR;
}
}
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
hfmpi2c->XferCount--;
}
/* Wait until STOP flag is set */
if (FMPI2C_WaitOnSTOPFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Clear STOP flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Wait until BUSY flag is reset */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_BUSY, SET, Timeout, tickstart) != HAL_OK)
{
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
return HAL_TIMEOUT;
}
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
{
uint32_t xfermode = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_GENERATE_START_WRITE);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in master mode an amount of data in non-blocking mode with Interrupt
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Receive_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
{
uint32_t xfermode = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, RXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size)
{
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferSize = hfmpi2c->XferCount;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_IT;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT | FMPI2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size)
{
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferSize = hfmpi2c->XferCount;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_IT;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, RXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT | FMPI2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in master mode an amount of data in non-blocking mode with DMA
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Transmit_DMA(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
{
uint32_t xfermode = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_DMA;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
if (hfmpi2c->XferSize > 0U)
{
/* Set the FMPI2C DMA transfer complete callback */
hfmpi2c->hdmatx->XferCpltCallback = FMPI2C_DMAMasterTransmitCplt;
/* Set the DMA error callback */
hfmpi2c->hdmatx->XferErrorCallback = FMPI2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hfmpi2c->hdmatx->XferHalfCpltCallback = NULL;
hfmpi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmatx, (uint32_t)pData, (uint32_t)&hfmpi2c->Instance->TXDR, hfmpi2c->XferSize);
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_GENERATE_START_WRITE);
/* Update XferCount value */
hfmpi2c->XferCount -= hfmpi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_ERROR_IT);
/* Enable DMA Request */
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_TXDMAEN;
}
else
{
/* Update Transfer ISR function pointer */
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
/* Send Slave Address */
/* Set NBYTES to write and generate START condition */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_GENERATE_START_WRITE);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in master mode an amount of data in non-blocking mode with DMA
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Receive_DMA(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
{
uint32_t xfermode = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_DMA;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
if (hfmpi2c->XferSize > 0U)
{
/* Set the FMPI2C DMA transfer complete callback */
hfmpi2c->hdmarx->XferCpltCallback = FMPI2C_DMAMasterReceiveCplt;
/* Set the DMA error callback */
hfmpi2c->hdmarx->XferErrorCallback = FMPI2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hfmpi2c->hdmarx->XferHalfCpltCallback = NULL;
hfmpi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmarx, (uint32_t)&hfmpi2c->Instance->RXDR, (uint32_t)pData, hfmpi2c->XferSize);
/* Send Slave Address */
/* Set NBYTES to read and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_GENERATE_START_READ);
/* Update XferCount value */
hfmpi2c->XferCount -= hfmpi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_ERROR_IT);
/* Enable DMA Request */
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_RXDMAEN;
}
else
{
/* Update Transfer ISR function pointer */
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
/* Send Slave Address */
/* Set NBYTES to read and generate START condition */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit in slave mode an amount of data in non-blocking mode with DMA
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Transmit_DMA(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size)
{
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferSize = hfmpi2c->XferCount;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_DMA;
/* Set the FMPI2C DMA transfer complete callback */
hfmpi2c->hdmatx->XferCpltCallback = FMPI2C_DMASlaveTransmitCplt;
/* Set the DMA error callback */
hfmpi2c->hdmatx->XferErrorCallback = FMPI2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hfmpi2c->hdmatx->XferHalfCpltCallback = NULL;
hfmpi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmatx, (uint32_t)pData, (uint32_t)&hfmpi2c->Instance->TXDR, hfmpi2c->XferSize);
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, STOP, NACK, ADDR interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT);
/* Enable DMA Request */
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_TXDMAEN;
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive in slave mode an amount of data in non-blocking mode with DMA
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Receive_DMA(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size)
{
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferSize = hfmpi2c->XferCount;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_DMA;
/* Set the FMPI2C DMA transfer complete callback */
hfmpi2c->hdmarx->XferCpltCallback = FMPI2C_DMASlaveReceiveCplt;
/* Set the DMA error callback */
hfmpi2c->hdmarx->XferErrorCallback = FMPI2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hfmpi2c->hdmarx->XferHalfCpltCallback = NULL;
hfmpi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmarx, (uint32_t)&hfmpi2c->Instance->RXDR, (uint32_t)pData, hfmpi2c->XferSize);
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, STOP, NACK, ADDR interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT);
/* Enable DMA Request */
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_RXDMAEN;
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Write an amount of data in blocking mode to a specific memory address
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Mem_Write(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_FMPI2C_MEMADD_SIZE(MemAddSize));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_BUSY, SET, FMPI2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MEM;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferISR = NULL;
/* Send Slave Address and Memory Address */
if (FMPI2C_RequestMemoryWrite(hfmpi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_NO_STARTSTOP);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_NO_STARTSTOP);
}
do
{
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Write data to TXDR */
hfmpi2c->Instance->TXDR = (*hfmpi2c->pBuffPtr++);
hfmpi2c->XferCount--;
hfmpi2c->XferSize--;
if ((hfmpi2c->XferSize == 0U) && (hfmpi2c->XferCount != 0U))
{
/* Wait until TCR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_NO_STARTSTOP);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_NO_STARTSTOP);
}
}
}
while (hfmpi2c->XferCount > 0U);
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is reset */
if (FMPI2C_WaitOnSTOPFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Read an amount of data in blocking mode from a specific memory address
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Mem_Read(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_FMPI2C_MEMADD_SIZE(MemAddSize));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_BUSY, SET, FMPI2C_TIMEOUT_BUSY, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MEM;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferISR = NULL;
/* Send Slave Address and Memory Address */
if (FMPI2C_RequestMemoryRead(hfmpi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_GENERATE_START_READ);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_GENERATE_START_READ);
}
do
{
/* Wait until RXNE flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_RXNE, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
if ((hfmpi2c->XferSize == 0U) && (hfmpi2c->XferCount != 0U))
{
/* Wait until TCR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_TCR, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_NO_STARTSTOP);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_NO_STARTSTOP);
}
}
}
while (hfmpi2c->XferCount > 0U);
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is reset */
if (FMPI2C_WaitOnSTOPFlagUntilTimeout(hfmpi2c, Timeout, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Mem_Write_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
uint32_t xfermode = 0U;
/* Check the parameters */
assert_param(IS_FMPI2C_MEMADD_SIZE(MemAddSize));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MEM;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (FMPI2C_RequestMemoryWrite(hfmpi2c, DevAddress, MemAddress, MemAddSize, FMPI2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_NO_STARTSTOP);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, TXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Mem_Read_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
uint32_t xfermode = 0U;
/* Check the parameters */
assert_param(IS_FMPI2C_MEMADD_SIZE(MemAddSize));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MEM;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (FMPI2C_RequestMemoryRead(hfmpi2c, DevAddress, MemAddress, MemAddSize, FMPI2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_GENERATE_START_READ);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR, TC, STOP, NACK, RXI interrupt */
/* possible to enable all of these */
/* FMPI2C_IT_ERRI | FMPI2C_IT_TCI| FMPI2C_IT_STOPI| FMPI2C_IT_NACKI | FMPI2C_IT_ADDRI | FMPI2C_IT_RXI | FMPI2C_IT_TXI */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Write an amount of data in non-blocking mode with DMA to a specific memory address
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Mem_Write_DMA(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
uint32_t xfermode = 0U;
/* Check the parameters */
assert_param(IS_FMPI2C_MEMADD_SIZE(MemAddSize));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MEM;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_DMA;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (FMPI2C_RequestMemoryWrite(hfmpi2c, DevAddress, MemAddress, MemAddSize, FMPI2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
/* Set the FMPI2C DMA transfer complete callback */
hfmpi2c->hdmatx->XferCpltCallback = FMPI2C_DMAMasterTransmitCplt;
/* Set the DMA error callback */
hfmpi2c->hdmatx->XferErrorCallback = FMPI2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hfmpi2c->hdmatx->XferHalfCpltCallback = NULL;
hfmpi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmatx, (uint32_t)pData, (uint32_t)&hfmpi2c->Instance->TXDR, hfmpi2c->XferSize);
/* Send Slave Address */
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_NO_STARTSTOP);
/* Update XferCount value */
hfmpi2c->XferCount -= hfmpi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_ERROR_IT);
/* Enable DMA Request */
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_TXDMAEN;
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param pData Pointer to data buffer
* @param Size Amount of data to be read
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Mem_Read_DMA(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
{
uint32_t tickstart = 0U;
uint32_t xfermode = 0U;
/* Check the parameters */
assert_param(IS_FMPI2C_MEMADD_SIZE(MemAddSize));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MEM;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferISR = FMPI2C_Master_ISR_DMA;
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Send Slave Address and Memory Address */
if (FMPI2C_RequestMemoryRead(hfmpi2c, DevAddress, MemAddress, MemAddSize, FMPI2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
/* Set the FMPI2C DMA transfer complete callback */
hfmpi2c->hdmarx->XferCpltCallback = FMPI2C_DMAMasterReceiveCplt;
/* Set the DMA error callback */
hfmpi2c->hdmarx->XferErrorCallback = FMPI2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hfmpi2c->hdmarx->XferHalfCpltCallback = NULL;
hfmpi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmarx, (uint32_t)&hfmpi2c->Instance->RXDR, (uint32_t)pData, hfmpi2c->XferSize);
/* Set NBYTES to write and reload if hfmpi2c->XferCount > MAX_NBYTE_SIZE and generate RESTART */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, FMPI2C_GENERATE_START_READ);
/* Update XferCount value */
hfmpi2c->XferCount -= hfmpi2c->XferSize;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Enable DMA Request */
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_RXDMAEN;
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* Enable ERR and NACK interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_ERROR_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Checks if target device is ready for communication.
* @note This function is used with Memory devices
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param Trials Number of trials
* @param Timeout Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_IsDeviceReady(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout)
{
uint32_t tickstart = 0U;
__IO uint32_t FMPI2C_Trials = 0U;
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_BUSY) == SET)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
do
{
/* Generate Start */
hfmpi2c->Instance->CR2 = FMPI2C_GENERATE_START(hfmpi2c->Init.AddressingMode, DevAddress);
/* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */
/* Wait until STOPF flag is set or a NACK flag is set*/
tickstart = HAL_GetTick();
while ((__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF) == RESET) && (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_AF) == RESET) && (hfmpi2c->State != HAL_FMPI2C_STATE_TIMEOUT))
{
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
{
/* Device is ready */
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
}
/* Check if the NACKF flag has not been set */
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_AF) == RESET)
{
/* Wait until STOPF flag is reset */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Device is ready */
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
else
{
/* Wait until STOPF flag is reset */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Clear STOP Flag, auto generated with autoend*/
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
}
/* Check if the maximum allowed number of trials has been reached */
if (FMPI2C_Trials++ == Trials)
{
/* Generate Stop */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_STOP;
/* Wait until STOPF flag is reset */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_STOPF, RESET, Timeout, tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
}
}
while (FMPI2C_Trials < Trials);
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential transmit in master FMPI2C mode an amount of data in non-blocking mode with Interrupt.
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref FMPI2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Sequential_Transmit_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
{
uint32_t xfermode = 0U;
uint32_t xferrequest = FMPI2C_GENERATE_START_WRITE;
/* Check the parameters */
assert_param(IS_FMPI2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = XferOptions;
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
/* If size > MAX_NBYTE_SIZE, use reload mode */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = hfmpi2c->XferOptions;
}
/* If transfer direction not change, do not generate Restart Condition */
/* Mean Previous state is same as current state */
if (hfmpi2c->PreviousState == FMPI2C_STATE_MASTER_BUSY_TX)
{
xferrequest = FMPI2C_NO_STARTSTOP;
}
/* Send Slave Address and set NBYTES to write */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, xferrequest);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential receive in master FMPI2C mode an amount of data in non-blocking mode with Interrupt
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref FMPI2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Sequential_Receive_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
{
uint32_t xfermode = 0U;
uint32_t xferrequest = FMPI2C_GENERATE_START_READ;
/* Check the parameters */
assert_param(IS_FMPI2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX;
hfmpi2c->Mode = HAL_FMPI2C_MODE_MASTER;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferOptions = XferOptions;
hfmpi2c->XferISR = FMPI2C_Master_ISR_IT;
/* If hfmpi2c->XferCount > MAX_NBYTE_SIZE, use reload mode */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = hfmpi2c->XferOptions;
}
/* If transfer direction not change, do not generate Restart Condition */
/* Mean Previous state is same as current state */
if (hfmpi2c->PreviousState == FMPI2C_STATE_MASTER_BUSY_RX)
{
xferrequest = FMPI2C_NO_STARTSTOP;
}
/* Send Slave Address and set NBYTES to read */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, hfmpi2c->XferSize, xfermode, xferrequest);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sequential transmit in slave/device FMPI2C mode an amount of data in non-blocking mode with Interrupt
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref FMPI2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Sequential_Transmit_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
{
/* Check the parameters */
assert_param(IS_FMPI2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if ((hfmpi2c->State & HAL_FMPI2C_STATE_LISTEN) == HAL_FMPI2C_STATE_LISTEN)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Disable Interrupts, to prevent preemption during treatment in case of multicall */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT | FMPI2C_XFER_TX_IT);
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* FMPI2C cannot manage full duplex exchange so disable previous IT enabled if any */
/* and then toggle the HAL slave RX state to TX state */
if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX_LISTEN)
{
/* Disable associated Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_TX_LISTEN;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferSize = hfmpi2c->XferCount;
hfmpi2c->XferOptions = XferOptions;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_IT;
if (FMPI2C_GET_DIR(hfmpi2c) == FMPI2C_DIRECTION_RECEIVE)
{
/* Clear ADDR flag after prepare the transfer parameters */
/* This action will generate an acknowledge to the Master */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
}
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* REnable ADDR interrupt */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT | FMPI2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Sequential receive in slave/device FMPI2C mode an amount of data in non-blocking mode with Interrupt
* @note This interface allow to manage repeated start condition when a direction change during transfer
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param pData Pointer to data buffer
* @param Size Amount of data to be sent
* @param XferOptions Options of Transfer, value of @ref FMPI2C_XFEROPTIONS
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Slave_Sequential_Receive_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
{
/* Check the parameters */
assert_param(IS_FMPI2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
if ((hfmpi2c->State & HAL_FMPI2C_STATE_LISTEN) == HAL_FMPI2C_STATE_LISTEN)
{
if ((pData == NULL) || (Size == 0U))
{
return HAL_ERROR;
}
/* Disable Interrupts, to prevent preemption during treatment in case of multicall */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT | FMPI2C_XFER_RX_IT);
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* FMPI2C cannot manage full duplex exchange so disable previous IT enabled if any */
/* and then toggle the HAL slave TX state to RX state */
if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX_LISTEN)
{
/* Disable associated Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
}
hfmpi2c->State = HAL_FMPI2C_STATE_BUSY_RX_LISTEN;
hfmpi2c->Mode = HAL_FMPI2C_MODE_SLAVE;
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
/* Enable Address Acknowledge */
hfmpi2c->Instance->CR2 &= ~FMPI2C_CR2_NACK;
/* Prepare transfer parameters */
hfmpi2c->pBuffPtr = pData;
hfmpi2c->XferCount = Size;
hfmpi2c->XferSize = hfmpi2c->XferCount;
hfmpi2c->XferOptions = XferOptions;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_IT;
if (FMPI2C_GET_DIR(hfmpi2c) == FMPI2C_DIRECTION_TRANSMIT)
{
/* Clear ADDR flag after prepare the transfer parameters */
/* This action will generate an acknowledge to the Master */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
}
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
/* REnable ADDR interrupt */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT | FMPI2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief Enable the Address listen mode with Interrupt.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_EnableListen_IT(FMPI2C_HandleTypeDef *hfmpi2c)
{
if (hfmpi2c->State == HAL_FMPI2C_STATE_READY)
{
hfmpi2c->State = HAL_FMPI2C_STATE_LISTEN;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_IT;
/* Enable the Address Match interrupt */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Disable the Address listen mode with Interrupt.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_DisableListen_IT(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Declaration of tmp to prevent undefined behavior of volatile usage */
uint32_t tmp;
/* Disable Address listen mode only if a transfer is not ongoing */
if (hfmpi2c->State == HAL_FMPI2C_STATE_LISTEN)
{
tmp = (uint32_t)(hfmpi2c->State) & FMPI2C_STATE_MSK;
hfmpi2c->PreviousState = tmp | (uint32_t)(hfmpi2c->Mode);
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
hfmpi2c->XferISR = NULL;
/* Disable the Address Match interrupt */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Abort a master FMPI2C IT or DMA process communication with Interrupt.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @retval HAL status
*/
HAL_StatusTypeDef HAL_FMPI2C_Master_Abort_IT(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress)
{
if (hfmpi2c->Mode == HAL_FMPI2C_MODE_MASTER)
{
/* Process Locked */
__HAL_LOCK(hfmpi2c);
/* Disable Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
/* Set State at HAL_FMPI2C_STATE_ABORT */
hfmpi2c->State = HAL_FMPI2C_STATE_ABORT;
/* Set NBYTES to 1 to generate a dummy read on FMPI2C peripheral */
/* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */
FMPI2C_TransferConfig(hfmpi2c, DevAddress, 1, FMPI2C_AUTOEND_MODE, FMPI2C_GENERATE_STOP);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Note : The FMPI2C interrupts must be enabled after unlocking current process
to avoid the risk of FMPI2C interrupt handle execution before current
process unlock */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_CPLT_IT);
return HAL_OK;
}
else
{
/* Wrong usage of abort function */
/* This function should be used only in case of abort monitored by master device */
return HAL_ERROR;
}
}
/**
* @}
*/
/** @defgroup FMPI2C_IRQ_Handler_and_Callbacks IRQ Handler and Callbacks
* @{
*/
/**
* @brief This function handles FMPI2C event interrupt request.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
void HAL_FMPI2C_EV_IRQHandler(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Get current IT Flags and IT sources value */
uint32_t itflags = READ_REG(hfmpi2c->Instance->ISR);
uint32_t itsources = READ_REG(hfmpi2c->Instance->CR1);
/* FMPI2C events treatment -------------------------------------*/
if (hfmpi2c->XferISR != NULL)
{
hfmpi2c->XferISR(hfmpi2c, itflags, itsources);
}
}
/**
* @brief This function handles FMPI2C error interrupt request.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
void HAL_FMPI2C_ER_IRQHandler(FMPI2C_HandleTypeDef *hfmpi2c)
{
uint32_t itflags = READ_REG(hfmpi2c->Instance->ISR);
uint32_t itsources = READ_REG(hfmpi2c->Instance->CR1);
/* FMPI2C Bus error interrupt occurred ------------------------------------*/
if (((itflags & FMPI2C_FLAG_BERR) != RESET) && ((itsources & FMPI2C_IT_ERRI) != RESET))
{
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_BERR;
/* Clear BERR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_BERR);
}
/* FMPI2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/
if (((itflags & FMPI2C_FLAG_OVR) != RESET) && ((itsources & FMPI2C_IT_ERRI) != RESET))
{
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_OVR;
/* Clear OVR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_OVR);
}
/* FMPI2C Arbitration Loss error interrupt occurred -------------------------------------*/
if (((itflags & FMPI2C_FLAG_ARLO) != RESET) && ((itsources & FMPI2C_IT_ERRI) != RESET))
{
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_ARLO;
/* Clear ARLO flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ARLO);
}
/* Call the Error Callback in case of Error detected */
if ((hfmpi2c->ErrorCode & (HAL_FMPI2C_ERROR_BERR | HAL_FMPI2C_ERROR_OVR | HAL_FMPI2C_ERROR_ARLO)) != HAL_FMPI2C_ERROR_NONE)
{
FMPI2C_ITError(hfmpi2c, hfmpi2c->ErrorCode);
}
}
/**
* @brief Master Tx Transfer completed callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_MasterTxCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_MasterTxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Master Rx Transfer completed callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_MasterRxCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_MasterRxCpltCallback could be implemented in the user file
*/
}
/** @brief Slave Tx Transfer completed callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_SlaveTxCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_SlaveTxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Slave Rx Transfer completed callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_SlaveRxCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_SlaveRxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Slave Address Match callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref FMPI2C_XFERDIRECTION
* @param AddrMatchCode Address Match Code
* @retval None
*/
__weak void HAL_FMPI2C_AddrCallback(FMPI2C_HandleTypeDef *hfmpi2c, uint8_t TransferDirection, uint16_t AddrMatchCode)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
UNUSED(TransferDirection);
UNUSED(AddrMatchCode);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_AddrCallback() could be implemented in the user file
*/
}
/**
* @brief Listen Complete callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_ListenCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_ListenCpltCallback() could be implemented in the user file
*/
}
/**
* @brief Memory Tx Transfer completed callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_MemTxCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_MemTxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Memory Rx Transfer completed callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_MemRxCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_MemRxCpltCallback could be implemented in the user file
*/
}
/**
* @brief FMPI2C error callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_ErrorCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_ErrorCallback could be implemented in the user file
*/
}
/**
* @brief FMPI2C abort callback.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval None
*/
__weak void HAL_FMPI2C_AbortCpltCallback(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hfmpi2c);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_FMPI2C_AbortCpltCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup FMPI2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions
* @brief Peripheral State, Mode and Error functions
*
@verbatim
===============================================================================
##### Peripheral State, Mode and Error functions #####
===============================================================================
[..]
This subsection permit to get in run-time the status of the peripheral
and the data flow.
@endverbatim
* @{
*/
/**
* @brief Return the FMPI2C handle state.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval HAL state
*/
HAL_FMPI2C_StateTypeDef HAL_FMPI2C_GetState(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Return FMPI2C handle state */
return hfmpi2c->State;
}
/**
* @brief Returns the FMPI2C Master, Slave, Memory or no mode.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for FMPI2C module
* @retval HAL mode
*/
HAL_FMPI2C_ModeTypeDef HAL_FMPI2C_GetMode(FMPI2C_HandleTypeDef *hfmpi2c)
{
return hfmpi2c->Mode;
}
/**
* @brief Return the FMPI2C error code.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @retval FMPI2C Error Code
*/
uint32_t HAL_FMPI2C_GetError(FMPI2C_HandleTypeDef *hfmpi2c)
{
return hfmpi2c->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @addtogroup FMPI2C_Private_Functions
* @{
*/
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with Interrupt.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_Master_ISR_IT(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources)
{
uint16_t devaddress = 0U;
/* Process Locked */
__HAL_LOCK(hfmpi2c);
if (((ITFlags & FMPI2C_FLAG_AF) != RESET) && ((ITSources & FMPI2C_IT_NACKI) != RESET))
{
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Set corresponding Error Code */
/* No need to generate STOP, it is automatically done */
/* Error callback will be send during stop flag treatment */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
/* Flush TX register */
FMPI2C_Flush_TXDR(hfmpi2c);
}
else if (((ITFlags & FMPI2C_FLAG_RXNE) != RESET) && ((ITSources & FMPI2C_IT_RXI) != RESET))
{
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
}
else if (((ITFlags & FMPI2C_FLAG_TXIS) != RESET) && ((ITSources & FMPI2C_IT_TXI) != RESET))
{
/* Write data to TXDR */
hfmpi2c->Instance->TXDR = (*hfmpi2c->pBuffPtr++);
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
}
else if (((ITFlags & FMPI2C_FLAG_TCR) != RESET) && ((ITSources & FMPI2C_IT_TCI) != RESET))
{
if ((hfmpi2c->XferSize == 0U) && (hfmpi2c->XferCount != 0U))
{
devaddress = (hfmpi2c->Instance->CR2 & FMPI2C_CR2_SADD);
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
FMPI2C_TransferConfig(hfmpi2c, devaddress, hfmpi2c->XferSize, FMPI2C_RELOAD_MODE, FMPI2C_NO_STARTSTOP);
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
if (hfmpi2c->XferOptions != FMPI2C_NO_OPTION_FRAME)
{
FMPI2C_TransferConfig(hfmpi2c, devaddress, hfmpi2c->XferSize, hfmpi2c->XferOptions, FMPI2C_NO_STARTSTOP);
}
else
{
FMPI2C_TransferConfig(hfmpi2c, devaddress, hfmpi2c->XferSize, FMPI2C_AUTOEND_MODE, FMPI2C_NO_STARTSTOP);
}
}
}
else
{
/* Call TxCpltCallback() if no stop mode is set */
if (FMPI2C_GET_STOP_MODE(hfmpi2c) != FMPI2C_AUTOEND_MODE)
{
/* Call FMPI2C Master Sequential complete process */
FMPI2C_ITMasterSequentialCplt(hfmpi2c);
}
else
{
/* Wrong size Status regarding TCR flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
FMPI2C_ITError(hfmpi2c, HAL_FMPI2C_ERROR_SIZE);
}
}
}
else if (((ITFlags & FMPI2C_FLAG_TC) != RESET) && ((ITSources & FMPI2C_IT_TCI) != RESET))
{
if (hfmpi2c->XferCount == 0U)
{
if (FMPI2C_GET_STOP_MODE(hfmpi2c) != FMPI2C_AUTOEND_MODE)
{
/* Generate a stop condition in case of no transfer option */
if (hfmpi2c->XferOptions == FMPI2C_NO_OPTION_FRAME)
{
/* Generate Stop */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_STOP;
}
else
{
/* Call FMPI2C Master Sequential complete process */
FMPI2C_ITMasterSequentialCplt(hfmpi2c);
}
}
}
else
{
/* Wrong size Status regarding TC flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
FMPI2C_ITError(hfmpi2c, HAL_FMPI2C_ERROR_SIZE);
}
}
if (((ITFlags & FMPI2C_FLAG_STOPF) != RESET) && ((ITSources & FMPI2C_IT_STOPI) != RESET))
{
/* Call FMPI2C Master complete process */
FMPI2C_ITMasterCplt(hfmpi2c, ITFlags);
}
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with Interrupt.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_Slave_ISR_IT(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources)
{
/* Process locked */
__HAL_LOCK(hfmpi2c);
if (((ITFlags & FMPI2C_FLAG_AF) != RESET) && ((ITSources & FMPI2C_IT_NACKI) != RESET))
{
/* Check that FMPI2C transfer finished */
/* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
/* Mean XferCount == 0*/
/* So clear Flag NACKF only */
if (hfmpi2c->XferCount == 0U)
{
if (((hfmpi2c->XferOptions == FMPI2C_FIRST_AND_LAST_FRAME) || (hfmpi2c->XferOptions == FMPI2C_LAST_FRAME)) && \
(hfmpi2c->State == HAL_FMPI2C_STATE_LISTEN))
{
/* Call FMPI2C Listen complete process */
FMPI2C_ITListenCplt(hfmpi2c, ITFlags);
}
else if ((hfmpi2c->XferOptions != FMPI2C_NO_OPTION_FRAME) && (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX_LISTEN))
{
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Flush TX register */
FMPI2C_Flush_TXDR(hfmpi2c);
/* Last Byte is Transmitted */
/* Call FMPI2C Slave Sequential complete process */
FMPI2C_ITSlaveSequentialCplt(hfmpi2c);
}
else
{
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
}
}
else
{
/* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Set ErrorCode corresponding to a Non-Acknowledge */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
}
}
else if (((ITFlags & FMPI2C_FLAG_RXNE) != RESET) && ((ITSources & FMPI2C_IT_RXI) != RESET))
{
if (hfmpi2c->XferCount > 0U)
{
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
}
if ((hfmpi2c->XferCount == 0U) && \
(hfmpi2c->XferOptions != FMPI2C_NO_OPTION_FRAME))
{
/* Call FMPI2C Slave Sequential complete process */
FMPI2C_ITSlaveSequentialCplt(hfmpi2c);
}
}
else if (((ITFlags & FMPI2C_FLAG_ADDR) != RESET) && ((ITSources & FMPI2C_IT_ADDRI) != RESET))
{
FMPI2C_ITAddrCplt(hfmpi2c, ITFlags);
}
else if (((ITFlags & FMPI2C_FLAG_TXIS) != RESET) && ((ITSources & FMPI2C_IT_TXI) != RESET))
{
/* Write data to TXDR only if XferCount not reach "0" */
/* A TXIS flag can be set, during STOP treatment */
/* Check if all Datas have already been sent */
/* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */
if (hfmpi2c->XferCount > 0U)
{
/* Write data to TXDR */
hfmpi2c->Instance->TXDR = (*hfmpi2c->pBuffPtr++);
hfmpi2c->XferCount--;
hfmpi2c->XferSize--;
}
else
{
if ((hfmpi2c->XferOptions == FMPI2C_NEXT_FRAME) || (hfmpi2c->XferOptions == FMPI2C_FIRST_FRAME))
{
/* Last Byte is Transmitted */
/* Call FMPI2C Slave Sequential complete process */
FMPI2C_ITSlaveSequentialCplt(hfmpi2c);
}
}
}
/* Check if STOPF is set */
if (((ITFlags & FMPI2C_FLAG_STOPF) != RESET) && ((ITSources & FMPI2C_IT_STOPI) != RESET))
{
/* Call FMPI2C Slave complete process */
FMPI2C_ITSlaveCplt(hfmpi2c, ITFlags);
}
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode with DMA.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_Master_ISR_DMA(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources)
{
uint16_t devaddress = 0U;
uint32_t xfermode = 0U;
/* Process Locked */
__HAL_LOCK(hfmpi2c);
if (((ITFlags & FMPI2C_FLAG_AF) != RESET) && ((ITSources & FMPI2C_IT_NACKI) != RESET))
{
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Set corresponding Error Code */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
/* No need to generate STOP, it is automatically done */
/* But enable STOP interrupt, to treat it */
/* Error callback will be send during stop flag treatment */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_CPLT_IT);
/* Flush TX register */
FMPI2C_Flush_TXDR(hfmpi2c);
}
else if (((ITFlags & FMPI2C_FLAG_TCR) != RESET) && ((ITSources & FMPI2C_IT_TCI) != RESET))
{
/* Disable TC interrupt */
__HAL_FMPI2C_DISABLE_IT(hfmpi2c, FMPI2C_IT_TCI);
if (hfmpi2c->XferCount != 0U)
{
/* Recover Slave address */
devaddress = (hfmpi2c->Instance->CR2 & FMPI2C_CR2_SADD);
/* Prepare the new XferSize to transfer */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
xfermode = FMPI2C_RELOAD_MODE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
xfermode = FMPI2C_AUTOEND_MODE;
}
/* Set the new XferSize in Nbytes register */
FMPI2C_TransferConfig(hfmpi2c, devaddress, hfmpi2c->XferSize, xfermode, FMPI2C_NO_STARTSTOP);
/* Update XferCount value */
hfmpi2c->XferCount -= hfmpi2c->XferSize;
/* Enable DMA Request */
if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX)
{
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_RXDMAEN;
}
else
{
hfmpi2c->Instance->CR1 |= FMPI2C_CR1_TXDMAEN;
}
}
else
{
/* Wrong size Status regarding TCR flag event */
/* Call the corresponding callback to inform upper layer of End of Transfer */
FMPI2C_ITError(hfmpi2c, HAL_FMPI2C_ERROR_SIZE);
}
}
else if (((ITFlags & FMPI2C_FLAG_STOPF) != RESET) && ((ITSources & FMPI2C_IT_STOPI) != RESET))
{
/* Call FMPI2C Master complete process */
FMPI2C_ITMasterCplt(hfmpi2c, ITFlags);
}
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
/**
* @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode with DMA.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param ITFlags Interrupt flags to handle.
* @param ITSources Interrupt sources enabled.
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_Slave_ISR_DMA(struct __FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags, uint32_t ITSources)
{
/* Process locked */
__HAL_LOCK(hfmpi2c);
if (((ITFlags & FMPI2C_FLAG_AF) != RESET) && ((ITSources & FMPI2C_IT_NACKI) != RESET))
{
/* Check that FMPI2C transfer finished */
/* if yes, normal use case, a NACK is sent by the MASTER when Transfer is finished */
/* Mean XferCount == 0 */
/* So clear Flag NACKF only */
if (FMPI2C_GET_DMA_REMAIN_DATA(hfmpi2c) == 0U)
{
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
}
else
{
/* if no, error use case, a Non-Acknowledge of last Data is generated by the MASTER*/
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Set ErrorCode corresponding to a Non-Acknowledge */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
}
}
else if (((ITFlags & FMPI2C_FLAG_ADDR) != RESET) && ((ITSources & FMPI2C_IT_ADDRI) != RESET))
{
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
}
else if (((ITFlags & FMPI2C_FLAG_STOPF) != RESET) && ((ITSources & FMPI2C_IT_STOPI) != RESET))
{
/* Call FMPI2C Slave complete process */
FMPI2C_ITSlaveCplt(hfmpi2c, ITFlags);
}
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_OK;
}
/**
* @brief Master sends target device address followed by internal memory address for write request.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_RequestMemoryWrite(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart)
{
FMPI2C_TransferConfig(hfmpi2c, DevAddress, MemAddSize, FMPI2C_RELOAD_MODE, FMPI2C_GENERATE_START_WRITE);
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* If Memory address size is 8Bit */
if (MemAddSize == FMPI2C_MEMADD_SIZE_8BIT)
{
/* Send Memory Address */
hfmpi2c->Instance->TXDR = FMPI2C_MEM_ADD_LSB(MemAddress);
}
/* If Memory address size is 16Bit */
else
{
/* Send MSB of Memory Address */
hfmpi2c->Instance->TXDR = FMPI2C_MEM_ADD_MSB(MemAddress);
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Send LSB of Memory Address */
hfmpi2c->Instance->TXDR = FMPI2C_MEM_ADD_LSB(MemAddress);
}
/* Wait until TCR flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_TCR, RESET, Timeout, Tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
return HAL_OK;
}
/**
* @brief Master sends target device address followed by internal memory address for read request.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param DevAddress Target device address The device 7 bits address value
* in datasheet must be shifted to the left before calling the interface
* @param MemAddress Internal memory address
* @param MemAddSize Size of internal memory address
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_RequestMemoryRead(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart)
{
FMPI2C_TransferConfig(hfmpi2c, DevAddress, MemAddSize, FMPI2C_SOFTEND_MODE, FMPI2C_GENERATE_START_WRITE);
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* If Memory address size is 8Bit */
if (MemAddSize == FMPI2C_MEMADD_SIZE_8BIT)
{
/* Send Memory Address */
hfmpi2c->Instance->TXDR = FMPI2C_MEM_ADD_LSB(MemAddress);
}
/* If Memory address size is 16Bit */
else
{
/* Send MSB of Memory Address */
hfmpi2c->Instance->TXDR = FMPI2C_MEM_ADD_MSB(MemAddress);
/* Wait until TXIS flag is set */
if (FMPI2C_WaitOnTXISFlagUntilTimeout(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
if (hfmpi2c->ErrorCode == HAL_FMPI2C_ERROR_AF)
{
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Send LSB of Memory Address */
hfmpi2c->Instance->TXDR = FMPI2C_MEM_ADD_LSB(MemAddress);
}
/* Wait until TC flag is set */
if (FMPI2C_WaitOnFlagUntilTimeout(hfmpi2c, FMPI2C_FLAG_TC, RESET, Timeout, Tickstart) != HAL_OK)
{
return HAL_TIMEOUT;
}
return HAL_OK;
}
/**
* @brief FMPI2C Address complete process callback.
* @param hfmpi2c FMPI2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void FMPI2C_ITAddrCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags)
{
uint8_t transferdirection = 0;
uint16_t slaveaddrcode = 0;
uint16_t ownadd1code = 0;
uint16_t ownadd2code = 0;
/* Prevent unused argument(s) compilation warning */
UNUSED(ITFlags);
/* In case of Listen state, need to inform upper layer of address match code event */
if ((hfmpi2c->State & HAL_FMPI2C_STATE_LISTEN) == HAL_FMPI2C_STATE_LISTEN)
{
transferdirection = FMPI2C_GET_DIR(hfmpi2c);
slaveaddrcode = FMPI2C_GET_ADDR_MATCH(hfmpi2c);
ownadd1code = FMPI2C_GET_OWN_ADDRESS1(hfmpi2c);
ownadd2code = FMPI2C_GET_OWN_ADDRESS2(hfmpi2c);
/* If 10bits addressing mode is selected */
if (hfmpi2c->Init.AddressingMode == FMPI2C_ADDRESSINGMODE_10BIT)
{
if ((slaveaddrcode & SlaveAddr_MSK) == ((ownadd1code >> SlaveAddr_SHIFT) & SlaveAddr_MSK))
{
slaveaddrcode = ownadd1code;
hfmpi2c->AddrEventCount++;
if (hfmpi2c->AddrEventCount == 2U)
{
/* Reset Address Event counter */
hfmpi2c->AddrEventCount = 0U;
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call Slave Addr callback */
HAL_FMPI2C_AddrCallback(hfmpi2c, transferdirection, slaveaddrcode);
}
}
else
{
slaveaddrcode = ownadd2code;
/* Disable ADDR Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call Slave Addr callback */
HAL_FMPI2C_AddrCallback(hfmpi2c, transferdirection, slaveaddrcode);
}
}
/* else 7 bits addressing mode is selected */
else
{
/* Disable ADDR Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call Slave Addr callback */
HAL_FMPI2C_AddrCallback(hfmpi2c, transferdirection, slaveaddrcode);
}
}
/* Else clear address flag only */
else
{
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
}
}
/**
* @brief FMPI2C Master sequential complete process.
* @param hfmpi2c FMPI2C handle.
* @retval None
*/
static void FMPI2C_ITMasterSequentialCplt(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Reset FMPI2C handle mode */
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* No Generate Stop, to permit restart mode */
/* The stop will be done at the end of transfer, when FMPI2C_AUTOEND_MODE enable */
if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX)
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->PreviousState = FMPI2C_STATE_MASTER_BUSY_TX;
hfmpi2c->XferISR = NULL;
/* Disable Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_MasterTxCpltCallback(hfmpi2c);
}
/* hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX */
else
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->PreviousState = FMPI2C_STATE_MASTER_BUSY_RX;
hfmpi2c->XferISR = NULL;
/* Disable Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_MasterRxCpltCallback(hfmpi2c);
}
}
/**
* @brief FMPI2C Slave sequential complete process.
* @param hfmpi2c FMPI2C handle.
* @retval None
*/
static void FMPI2C_ITSlaveSequentialCplt(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* Reset FMPI2C handle mode */
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX_LISTEN)
{
/* Remove HAL_FMPI2C_STATE_SLAVE_BUSY_TX, keep only HAL_FMPI2C_STATE_LISTEN */
hfmpi2c->State = HAL_FMPI2C_STATE_LISTEN;
hfmpi2c->PreviousState = FMPI2C_STATE_SLAVE_BUSY_TX;
/* Disable Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the Tx complete callback to inform upper layer of the end of transmit process */
HAL_FMPI2C_SlaveTxCpltCallback(hfmpi2c);
}
else if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX_LISTEN)
{
/* Remove HAL_FMPI2C_STATE_SLAVE_BUSY_RX, keep only HAL_FMPI2C_STATE_LISTEN */
hfmpi2c->State = HAL_FMPI2C_STATE_LISTEN;
hfmpi2c->PreviousState = FMPI2C_STATE_SLAVE_BUSY_RX;
/* Disable Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the Rx complete callback to inform upper layer of the end of receive process */
HAL_FMPI2C_SlaveRxCpltCallback(hfmpi2c);
}
}
/**
* @brief FMPI2C Master complete process.
* @param hfmpi2c FMPI2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void FMPI2C_ITMasterCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags)
{
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
/* Reset handle parameters */
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->XferISR = NULL;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
if ((ITFlags & FMPI2C_FLAG_AF) != RESET)
{
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Set acknowledge error code */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
}
/* Flush TX register */
FMPI2C_Flush_TXDR(hfmpi2c);
/* Disable Interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_TX_IT | FMPI2C_XFER_RX_IT);
/* Call the corresponding callback to inform upper layer of End of Transfer */
if ((hfmpi2c->ErrorCode != HAL_FMPI2C_ERROR_NONE) || (hfmpi2c->State == HAL_FMPI2C_STATE_ABORT))
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
FMPI2C_ITError(hfmpi2c, hfmpi2c->ErrorCode);
}
/* hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX */
else if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX)
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
if (hfmpi2c->Mode == HAL_FMPI2C_MODE_MEM)
{
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_MemTxCpltCallback(hfmpi2c);
}
else
{
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_MasterTxCpltCallback(hfmpi2c);
}
}
/* hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX */
else if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX)
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
if (hfmpi2c->Mode == HAL_FMPI2C_MODE_MEM)
{
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
HAL_FMPI2C_MemRxCpltCallback(hfmpi2c);
}
else
{
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
HAL_FMPI2C_MasterRxCpltCallback(hfmpi2c);
}
}
}
/**
* @brief FMPI2C Slave complete process.
* @param hfmpi2c FMPI2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void FMPI2C_ITSlaveCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags)
{
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear ADDR flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_ADDR);
/* Disable all interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT | FMPI2C_XFER_TX_IT | FMPI2C_XFER_RX_IT);
/* Disable Address Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
/* Flush TX register */
FMPI2C_Flush_TXDR(hfmpi2c);
/* If a DMA is ongoing, Update handle size context */
if (((hfmpi2c->Instance->CR1 & FMPI2C_CR1_TXDMAEN) == FMPI2C_CR1_TXDMAEN) ||
((hfmpi2c->Instance->CR1 & FMPI2C_CR1_RXDMAEN) == FMPI2C_CR1_RXDMAEN))
{
hfmpi2c->XferCount = FMPI2C_GET_DMA_REMAIN_DATA(hfmpi2c);
}
/* All data are not transferred, so set error code accordingly */
if (hfmpi2c->XferCount != 0U)
{
/* Set ErrorCode corresponding to a Non-Acknowledge */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
}
/* Store Last receive data if any */
if (((ITFlags & FMPI2C_FLAG_RXNE) != RESET))
{
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
if ((hfmpi2c->XferSize > 0U))
{
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
/* Set ErrorCode corresponding to a Non-Acknowledge */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
}
}
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
hfmpi2c->XferISR = NULL;
if (hfmpi2c->ErrorCode != HAL_FMPI2C_ERROR_NONE)
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
FMPI2C_ITError(hfmpi2c, hfmpi2c->ErrorCode);
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
if (hfmpi2c->State == HAL_FMPI2C_STATE_LISTEN)
{
/* Call FMPI2C Listen complete process */
FMPI2C_ITListenCplt(hfmpi2c, ITFlags);
}
}
else if (hfmpi2c->XferOptions != FMPI2C_NO_OPTION_FRAME)
{
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
HAL_FMPI2C_ListenCpltCallback(hfmpi2c);
}
/* Call the corresponding callback to inform upper layer of End of Transfer */
else if (hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX)
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the Slave Rx Complete callback */
HAL_FMPI2C_SlaveRxCpltCallback(hfmpi2c);
}
else
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the Slave Tx Complete callback */
HAL_FMPI2C_SlaveTxCpltCallback(hfmpi2c);
}
}
/**
* @brief FMPI2C Listen complete process.
* @param hfmpi2c FMPI2C handle.
* @param ITFlags Interrupt flags to handle.
* @retval None
*/
static void FMPI2C_ITListenCplt(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ITFlags)
{
/* Reset handle parameters */
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
hfmpi2c->XferISR = NULL;
/* Store Last receive data if any */
if (((ITFlags & FMPI2C_FLAG_RXNE) != RESET))
{
/* Read data from RXDR */
(*hfmpi2c->pBuffPtr++) = hfmpi2c->Instance->RXDR;
if ((hfmpi2c->XferSize > 0U))
{
hfmpi2c->XferSize--;
hfmpi2c->XferCount--;
/* Set ErrorCode corresponding to a Non-Acknowledge */
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_AF;
}
}
/* Disable all Interrupts*/
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT | FMPI2C_XFER_RX_IT | FMPI2C_XFER_TX_IT);
/* Clear NACK Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
HAL_FMPI2C_ListenCpltCallback(hfmpi2c);
}
/**
* @brief FMPI2C interrupts error process.
* @param hfmpi2c FMPI2C handle.
* @param ErrorCode Error code to handle.
* @retval None
*/
static void FMPI2C_ITError(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t ErrorCode)
{
/* Reset handle parameters */
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
hfmpi2c->XferOptions = FMPI2C_NO_OPTION_FRAME;
hfmpi2c->XferCount = 0U;
/* Set new error code */
hfmpi2c->ErrorCode |= ErrorCode;
/* Disable Interrupts */
if ((hfmpi2c->State == HAL_FMPI2C_STATE_LISTEN) ||
(hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_TX_LISTEN) ||
(hfmpi2c->State == HAL_FMPI2C_STATE_BUSY_RX_LISTEN))
{
/* Disable all interrupts, except interrupts related to LISTEN state */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_RX_IT | FMPI2C_XFER_TX_IT);
/* keep HAL_FMPI2C_STATE_LISTEN if set */
hfmpi2c->State = HAL_FMPI2C_STATE_LISTEN;
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->XferISR = FMPI2C_Slave_ISR_IT;
}
else
{
/* Disable all interrupts */
FMPI2C_Disable_IRQ(hfmpi2c, FMPI2C_XFER_LISTEN_IT | FMPI2C_XFER_RX_IT | FMPI2C_XFER_TX_IT);
/* If state is an abort treatment on goind, don't change state */
/* This change will be do later */
if (hfmpi2c->State != HAL_FMPI2C_STATE_ABORT)
{
/* Set HAL_FMPI2C_STATE_READY */
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
}
hfmpi2c->PreviousState = FMPI2C_STATE_NONE;
hfmpi2c->XferISR = NULL;
}
/* Abort DMA TX transfer if any */
if ((hfmpi2c->Instance->CR1 & FMPI2C_CR1_TXDMAEN) == FMPI2C_CR1_TXDMAEN)
{
hfmpi2c->Instance->CR1 &= ~FMPI2C_CR1_TXDMAEN;
/* Set the FMPI2C DMA Abort callback :
will lead to call HAL_FMPI2C_ErrorCallback() at end of DMA abort procedure */
hfmpi2c->hdmatx->XferAbortCallback = FMPI2C_DMAAbort;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Abort DMA TX */
if (HAL_DMA_Abort_IT(hfmpi2c->hdmatx) != HAL_OK)
{
/* Call Directly XferAbortCallback function in case of error */
hfmpi2c->hdmatx->XferAbortCallback(hfmpi2c->hdmatx);
}
}
/* Abort DMA RX transfer if any */
else if ((hfmpi2c->Instance->CR1 & FMPI2C_CR1_RXDMAEN) == FMPI2C_CR1_RXDMAEN)
{
hfmpi2c->Instance->CR1 &= ~FMPI2C_CR1_RXDMAEN;
/* Set the FMPI2C DMA Abort callback :
will lead to call HAL_FMPI2C_ErrorCallback() at end of DMA abort procedure */
hfmpi2c->hdmarx->XferAbortCallback = FMPI2C_DMAAbort;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Abort DMA RX */
if (HAL_DMA_Abort_IT(hfmpi2c->hdmarx) != HAL_OK)
{
/* Call Directly hfmpi2c->hdmarx->XferAbortCallback function in case of error */
hfmpi2c->hdmarx->XferAbortCallback(hfmpi2c->hdmarx);
}
}
else if (hfmpi2c->State == HAL_FMPI2C_STATE_ABORT)
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_AbortCpltCallback(hfmpi2c);
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_ErrorCallback(hfmpi2c);
}
}
/**
* @brief FMPI2C Tx data register flush process.
* @param hfmpi2c FMPI2C handle.
* @retval None
*/
static void FMPI2C_Flush_TXDR(FMPI2C_HandleTypeDef *hfmpi2c)
{
/* If a pending TXIS flag is set */
/* Write a dummy data in TXDR to clear it */
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_TXIS) != RESET)
{
hfmpi2c->Instance->TXDR = 0x00U;
}
/* Flush TX register if not empty */
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_TXE) == RESET)
{
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_TXE);
}
}
/**
* @brief DMA FMPI2C master transmit process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void FMPI2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma)
{
FMPI2C_HandleTypeDef *hfmpi2c = (FMPI2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Disable DMA Request */
hfmpi2c->Instance->CR1 &= ~FMPI2C_CR1_TXDMAEN;
/* If last transfer, enable STOP interrupt */
if (hfmpi2c->XferCount == 0U)
{
/* Enable STOP interrupt */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_CPLT_IT);
}
/* else prepare a new DMA transfer and enable TCReload interrupt */
else
{
/* Update Buffer pointer */
hfmpi2c->pBuffPtr += hfmpi2c->XferSize;
/* Set the XferSize to transfer */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
}
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmatx, (uint32_t)hfmpi2c->pBuffPtr, (uint32_t)&hfmpi2c->Instance->TXDR, hfmpi2c->XferSize);
/* Enable TC interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RELOAD_IT);
}
}
/**
* @brief DMA FMPI2C slave transmit process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void FMPI2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdma);
/* No specific action, Master fully manage the generation of STOP condition */
/* Mean that this generation can arrive at any time, at the end or during DMA process */
/* So STOP condition should be manage through Interrupt treatment */
}
/**
* @brief DMA FMPI2C master receive process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void FMPI2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma)
{
FMPI2C_HandleTypeDef *hfmpi2c = (FMPI2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Disable DMA Request */
hfmpi2c->Instance->CR1 &= ~FMPI2C_CR1_RXDMAEN;
/* If last transfer, enable STOP interrupt */
if (hfmpi2c->XferCount == 0U)
{
/* Enable STOP interrupt */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_CPLT_IT);
}
/* else prepare a new DMA transfer and enable TCReload interrupt */
else
{
/* Update Buffer pointer */
hfmpi2c->pBuffPtr += hfmpi2c->XferSize;
/* Set the XferSize to transfer */
if (hfmpi2c->XferCount > MAX_NBYTE_SIZE)
{
hfmpi2c->XferSize = MAX_NBYTE_SIZE;
}
else
{
hfmpi2c->XferSize = hfmpi2c->XferCount;
}
/* Enable the DMA stream */
HAL_DMA_Start_IT(hfmpi2c->hdmarx, (uint32_t)&hfmpi2c->Instance->RXDR, (uint32_t)hfmpi2c->pBuffPtr, hfmpi2c->XferSize);
/* Enable TC interrupts */
FMPI2C_Enable_IRQ(hfmpi2c, FMPI2C_XFER_RELOAD_IT);
}
}
/**
* @brief DMA FMPI2C slave receive process complete callback.
* @param hdma DMA handle
* @retval None
*/
static void FMPI2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hdma);
/* No specific action, Master fully manage the generation of STOP condition */
/* Mean that this generation can arrive at any time, at the end or during DMA process */
/* So STOP condition should be manage through Interrupt treatment */
}
/**
* @brief DMA FMPI2C communication error callback.
* @param hdma DMA handle
* @retval None
*/
static void FMPI2C_DMAError(DMA_HandleTypeDef *hdma)
{
FMPI2C_HandleTypeDef *hfmpi2c = (FMPI2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Disable Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
/* Call the corresponding callback to inform upper layer of End of Transfer */
FMPI2C_ITError(hfmpi2c, HAL_FMPI2C_ERROR_DMA);
}
/**
* @brief DMA FMPI2C communication abort callback
* (To be called at end of DMA Abort procedure).
* @param hdma DMA handle.
* @retval None
*/
static void FMPI2C_DMAAbort(DMA_HandleTypeDef *hdma)
{
FMPI2C_HandleTypeDef *hfmpi2c = (FMPI2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
/* Disable Acknowledge */
hfmpi2c->Instance->CR2 |= FMPI2C_CR2_NACK;
/* Reset AbortCpltCallback */
hfmpi2c->hdmatx->XferAbortCallback = NULL;
hfmpi2c->hdmarx->XferAbortCallback = NULL;
/* Check if come from abort from user */
if (hfmpi2c->State == HAL_FMPI2C_STATE_ABORT)
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_AbortCpltCallback(hfmpi2c);
}
else
{
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_FMPI2C_ErrorCallback(hfmpi2c);
}
}
/**
* @brief This function handles FMPI2C Communication Timeout.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param Flag Specifies the FMPI2C flag to check.
* @param Status The new Flag status (SET or RESET).
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_WaitOnFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart)
{
while (__HAL_FMPI2C_GET_FLAG(hfmpi2c, Flag) == Status)
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout))
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @brief This function handles FMPI2C Communication Timeout for specific usage of TXIS flag.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_WaitOnTXISFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart)
{
while (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_TXIS) == RESET)
{
/* Check if a NACK is detected */
if (FMPI2C_IsAcknowledgeFailed(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout))
{
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_TIMEOUT;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @brief This function handles FMPI2C Communication Timeout for specific usage of STOP flag.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_WaitOnSTOPFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart)
{
while (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF) == RESET)
{
/* Check if a NACK is detected */
if (FMPI2C_IsAcknowledgeFailed(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Check for the Timeout */
if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout))
{
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_TIMEOUT;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @brief This function handles FMPI2C Communication Timeout for specific usage of RXNE flag.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_WaitOnRXNEFlagUntilTimeout(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart)
{
while (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_RXNE) == RESET)
{
/* Check if a NACK is detected */
if (FMPI2C_IsAcknowledgeFailed(hfmpi2c, Timeout, Tickstart) != HAL_OK)
{
return HAL_ERROR;
}
/* Check if a STOPF is detected */
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF) == SET)
{
/* Check if an RXNE is pending */
/* Store Last receive data if any */
if ((__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_RXNE) == SET) && (hfmpi2c->XferSize > 0U))
{
/* Return HAL_OK */
/* The Reading of data from RXDR will be done in caller function */
return HAL_OK;
}
else
{
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_NONE;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
}
/* Check for the Timeout */
if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout))
{
hfmpi2c->ErrorCode |= HAL_FMPI2C_ERROR_TIMEOUT;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @brief This function handles Acknowledge failed detection during an FMPI2C Communication.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param Timeout Timeout duration
* @param Tickstart Tick start value
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_IsAcknowledgeFailed(FMPI2C_HandleTypeDef *hfmpi2c, uint32_t Timeout, uint32_t Tickstart)
{
if (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_AF) == SET)
{
/* Wait until STOP Flag is reset */
/* AutoEnd should be initiate after AF */
while (__HAL_FMPI2C_GET_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF) == RESET)
{
/* Check for the Timeout */
if (Timeout != HAL_MAX_DELAY)
{
if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout))
{
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_TIMEOUT;
}
}
}
/* Clear NACKF Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_AF);
/* Clear STOP Flag */
__HAL_FMPI2C_CLEAR_FLAG(hfmpi2c, FMPI2C_FLAG_STOPF);
/* Flush TX register */
FMPI2C_Flush_TXDR(hfmpi2c);
/* Clear Configuration Register 2 */
FMPI2C_RESET_CR2(hfmpi2c);
hfmpi2c->ErrorCode = HAL_FMPI2C_ERROR_AF;
hfmpi2c->State = HAL_FMPI2C_STATE_READY;
hfmpi2c->Mode = HAL_FMPI2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hfmpi2c);
return HAL_ERROR;
}
return HAL_OK;
}
/**
* @brief Handles FMPI2Cx communication when starting transfer or during transfer (TC or TCR flag are set).
* @param hfmpi2c FMPI2C handle.
* @param DevAddress Specifies the slave address to be programmed.
* @param Size Specifies the number of bytes to be programmed.
* This parameter must be a value between 0 and 255.
* @param Mode New state of the FMPI2C START condition generation.
* This parameter can be one of the following values:
* @arg @ref FMPI2C_RELOAD_MODE Enable Reload mode .
* @arg @ref FMPI2C_AUTOEND_MODE Enable Automatic end mode.
* @arg @ref FMPI2C_SOFTEND_MODE Enable Software end mode.
* @param Request New state of the FMPI2C START condition generation.
* This parameter can be one of the following values:
* @arg @ref FMPI2C_NO_STARTSTOP Don't Generate stop and start condition.
* @arg @ref FMPI2C_GENERATE_STOP Generate stop condition (Size should be set to 0).
* @arg @ref FMPI2C_GENERATE_START_READ Generate Restart for read request.
* @arg @ref FMPI2C_GENERATE_START_WRITE Generate Restart for write request.
* @retval None
*/
static void FMPI2C_TransferConfig(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request)
{
/* Check the parameters */
assert_param(IS_FMPI2C_ALL_INSTANCE(hfmpi2c->Instance));
assert_param(IS_TRANSFER_MODE(Mode));
assert_param(IS_TRANSFER_REQUEST(Request));
/* update CR2 register */
MODIFY_REG(hfmpi2c->Instance->CR2, ((FMPI2C_CR2_SADD | FMPI2C_CR2_NBYTES | FMPI2C_CR2_RELOAD | FMPI2C_CR2_AUTOEND | (FMPI2C_CR2_RD_WRN & (uint32_t)(Request >> (31U - FMPI2C_CR2_RD_WRN_Pos))) | FMPI2C_CR2_START | FMPI2C_CR2_STOP)), \
(uint32_t)(((uint32_t)DevAddress & FMPI2C_CR2_SADD) | (((uint32_t)Size << FMPI2C_CR2_NBYTES_Pos) & FMPI2C_CR2_NBYTES) | (uint32_t)Mode | (uint32_t)Request));
}
/**
* @brief Manage the enabling of Interrupts.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param InterruptRequest Value of @ref FMPI2C_Interrupt_configuration_definition.
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_Enable_IRQ(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t InterruptRequest)
{
uint32_t tmpisr = 0U;
if ((hfmpi2c->XferISR == FMPI2C_Master_ISR_DMA) || \
(hfmpi2c->XferISR == FMPI2C_Slave_ISR_DMA))
{
if ((InterruptRequest & FMPI2C_XFER_LISTEN_IT) == FMPI2C_XFER_LISTEN_IT)
{
/* Enable ERR, STOP, NACK and ADDR interrupts */
tmpisr |= FMPI2C_IT_ADDRI | FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_ERRI;
}
if ((InterruptRequest & FMPI2C_XFER_ERROR_IT) == FMPI2C_XFER_ERROR_IT)
{
/* Enable ERR and NACK interrupts */
tmpisr |= FMPI2C_IT_ERRI | FMPI2C_IT_NACKI;
}
if ((InterruptRequest & FMPI2C_XFER_CPLT_IT) == FMPI2C_XFER_CPLT_IT)
{
/* Enable STOP interrupts */
tmpisr |= FMPI2C_IT_STOPI;
}
if ((InterruptRequest & FMPI2C_XFER_RELOAD_IT) == FMPI2C_XFER_RELOAD_IT)
{
/* Enable TC interrupts */
tmpisr |= FMPI2C_IT_TCI;
}
}
else
{
if ((InterruptRequest & FMPI2C_XFER_LISTEN_IT) == FMPI2C_XFER_LISTEN_IT)
{
/* Enable ERR, STOP, NACK, and ADDR interrupts */
tmpisr |= FMPI2C_IT_ADDRI | FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_ERRI;
}
if ((InterruptRequest & FMPI2C_XFER_TX_IT) == FMPI2C_XFER_TX_IT)
{
/* Enable ERR, TC, STOP, NACK and RXI interrupts */
tmpisr |= FMPI2C_IT_ERRI | FMPI2C_IT_TCI | FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_TXI;
}
if ((InterruptRequest & FMPI2C_XFER_RX_IT) == FMPI2C_XFER_RX_IT)
{
/* Enable ERR, TC, STOP, NACK and TXI interrupts */
tmpisr |= FMPI2C_IT_ERRI | FMPI2C_IT_TCI | FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_RXI;
}
if ((InterruptRequest & FMPI2C_XFER_CPLT_IT) == FMPI2C_XFER_CPLT_IT)
{
/* Enable STOP interrupts */
tmpisr |= FMPI2C_IT_STOPI;
}
}
/* Enable interrupts only at the end */
/* to avoid the risk of FMPI2C interrupt handle execution before */
/* all interrupts requested done */
__HAL_FMPI2C_ENABLE_IT(hfmpi2c, tmpisr);
return HAL_OK;
}
/**
* @brief Manage the disabling of Interrupts.
* @param hfmpi2c Pointer to a FMPI2C_HandleTypeDef structure that contains
* the configuration information for the specified FMPI2C.
* @param InterruptRequest Value of @ref FMPI2C_Interrupt_configuration_definition.
* @retval HAL status
*/
static HAL_StatusTypeDef FMPI2C_Disable_IRQ(FMPI2C_HandleTypeDef *hfmpi2c, uint16_t InterruptRequest)
{
uint32_t tmpisr = 0U;
if ((InterruptRequest & FMPI2C_XFER_TX_IT) == FMPI2C_XFER_TX_IT)
{
/* Disable TC and TXI interrupts */
tmpisr |= FMPI2C_IT_TCI | FMPI2C_IT_TXI;
if ((hfmpi2c->State & HAL_FMPI2C_STATE_LISTEN) != HAL_FMPI2C_STATE_LISTEN)
{
/* Disable NACK and STOP interrupts */
tmpisr |= FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_ERRI;
}
}
if ((InterruptRequest & FMPI2C_XFER_RX_IT) == FMPI2C_XFER_RX_IT)
{
/* Disable TC and RXI interrupts */
tmpisr |= FMPI2C_IT_TCI | FMPI2C_IT_RXI;
if ((hfmpi2c->State & HAL_FMPI2C_STATE_LISTEN) != HAL_FMPI2C_STATE_LISTEN)
{
/* Disable NACK and STOP interrupts */
tmpisr |= FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_ERRI;
}
}
if ((InterruptRequest & FMPI2C_XFER_LISTEN_IT) == FMPI2C_XFER_LISTEN_IT)
{
/* Disable ADDR, NACK and STOP interrupts */
tmpisr |= FMPI2C_IT_ADDRI | FMPI2C_IT_STOPI | FMPI2C_IT_NACKI | FMPI2C_IT_ERRI;
}
if ((InterruptRequest & FMPI2C_XFER_ERROR_IT) == FMPI2C_XFER_ERROR_IT)
{
/* Enable ERR and NACK interrupts */
tmpisr |= FMPI2C_IT_ERRI | FMPI2C_IT_NACKI;
}
if ((InterruptRequest & FMPI2C_XFER_CPLT_IT) == FMPI2C_XFER_CPLT_IT)
{
/* Enable STOP interrupts */
tmpisr |= FMPI2C_IT_STOPI;
}
if ((InterruptRequest & FMPI2C_XFER_RELOAD_IT) == FMPI2C_XFER_RELOAD_IT)
{
/* Enable TC interrupts */
tmpisr |= FMPI2C_IT_TCI;
}
/* Disable interrupts only at the end */
/* to avoid a breaking situation like at "t" time */
/* all disable interrupts request are not done */
__HAL_FMPI2C_DISABLE_IT(hfmpi2c, tmpisr);
return HAL_OK;
}
/**
* @}
*/
#endif /* STM32F410xx || STM32F446xx || STM32F412Zx || STM32F412Vx || STM32F412Rx || STM32F412Cx || STM32F413xx || STM32F423xx */
#endif /* HAL_FMPI2C_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
dawangjiaowolaixunshan/runtime | deps/libcxx/test/numerics/numarray/template.gslice.array/gslice.array.comp.assign/shift_left.pass.cpp | 44 | 2494 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <valarray>
// template <class T> class gslice_array
// void operator<<= (const valarray<value_type>& v) const;
#include <valarray>
#include <cassert>
int main()
{
int a1[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40};
int a2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};
std::valarray<int> v1(a1, sizeof(a1)/sizeof(a1[0]));
std::valarray<int> v2(a2, sizeof(a2)/sizeof(a2[0]));
std::size_t sz[] = {2, 4, 3};
std::size_t st[] = {19, 4, 1};
typedef std::valarray<std::size_t> sizes;
typedef std::valarray<std::size_t> strides;
v1[std::gslice(3, sizes(sz, sizeof(sz)/sizeof(sz[0])),
strides(st, sizeof(st)/sizeof(st[0])))] <<= v2;
assert(v1.size() == 41);
assert(v1[ 0] == 0);
assert(v1[ 1] == 1);
assert(v1[ 2] == 2);
assert(v1[ 3] == 6);
assert(v1[ 4] == 16);
assert(v1[ 5] == 40);
assert(v1[ 6] == 6);
assert(v1[ 7] == 112);
assert(v1[ 8] == 256);
assert(v1[ 9] == 576);
assert(v1[10] == 10);
assert(v1[11] == 1408);
assert(v1[12] == 3072);
assert(v1[13] == 6656);
assert(v1[14] == 14);
assert(v1[15] == 15360);
assert(v1[16] == 32768);
assert(v1[17] == 69632);
assert(v1[18] == 18);
assert(v1[19] == 19);
assert(v1[20] == 20);
assert(v1[21] == 21);
assert(v1[22] == 180224);
assert(v1[23] == 376832);
assert(v1[24] == 786432);
assert(v1[25] == 25);
assert(v1[26] == 1703936);
assert(v1[27] == 3538944);
assert(v1[28] == 7340032);
assert(v1[29] == 29);
assert(v1[30] == 15728640);
assert(v1[31] == 32505856);
assert(v1[32] == 67108864);
assert(v1[33] == 33);
assert(v1[34] == 142606336);
assert(v1[35] == 293601280);
assert(v1[36] == 603979776);
assert(v1[37] == 37);
assert(v1[38] == 38);
assert(v1[39] == 39);
assert(v1[40] == 40);
}
| apache-2.0 |
ICML14MoMCompare/spectral-learn | code/em/treba/gsl-1.16/cblas/test_trmm.c | 48 | 125454 | #include <gsl/gsl_test.h>
#include <gsl/gsl_ieee_utils.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_cblas.h>
#include "tests.h"
void
test_trmm (void) {
const double flteps = 1e-4, dbleps = 1e-6;
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.18f, 0.199f, 0.122f, -0.547f };
int lda = 2;
float B[] = { -0.874f, -0.383f, 0.458f, 0.124f, -0.221f, -0.107f };
int ldb = 3;
float B_expected[] = { 0.0397932f, 0.0338757f, -0.0183441f, 0.0203484f, -0.0362661f, -0.0175587f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1662)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.195f, -0.453f, -0.579f, 0.697f };
int lda = 2;
float B[] = { 0.736f, 0.131f, 0.533f, 0.692f, -0.672f, -0.435f };
int ldb = 3;
float B_expected[] = { -0.126757f, -0.130625f, -0.219017f, -0.2076f, 0.2016f, 0.1305f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1663)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.53f, 0.787f, 0.889f, -0.379f };
int lda = 2;
float B[] = { -0.355f, 0.002f, 0.266f, 0.972f, 0.712f, -0.353f };
int ldb = 3;
float B_expected[] = { -0.056445f, 3.18e-04f, 0.042294f, 0.205195f, 0.080421f, -0.111078f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1664)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.198f, -0.673f, 0.792f, 0.781f };
int lda = 2;
float B[] = { 0.901f, 0.719f, -0.339f, -0.36f, 0.539f, 0.192f };
int ldb = 3;
float B_expected[] = { -0.2703f, -0.2157f, 0.1017f, -0.106078f, -0.332534f, 0.0229464f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1665)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.522f, 0.851f, 0.586f, 0.196f };
int lda = 2;
float B[] = { 0.335f, 0.617f, 0.118f, -0.143f, 0.677f, 0.456f };
int ldb = 2;
float B_expected[] = { -0.0560076f, -0.0362796f, 0.0436182f, 0.0084084f, 0.0258534f, -0.0268128f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1666)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.006f, -0.613f, -0.966f, -0.758f };
int lda = 2;
float B[] = { 0.64f, -0.723f, -0.765f, 0.801f, 0.376f, 0.91f };
int ldb = 2;
float B_expected[] = { -0.401525f, 0.2169f, 0.46163f, -0.2403f, 0.150918f, -0.273f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1667)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.738f, 0.913f, -0.227f, 0.787f };
int lda = 2;
float B[] = { 0.194f, 0.988f, -0.274f, -0.652f, -0.281f, -0.359f };
int ldb = 2;
float B_expected[] = { -0.0429516f, -0.286403f, 0.0606636f, 0.228986f, 0.0622134f, 0.161726f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1668)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.952f, 0.598f, 0.25f, -0.508f };
int lda = 2;
float B[] = { 0.036f, 0.745f, -0.606f, 0.215f, 0.943f, -0.933f };
int ldb = 2;
float B_expected[] = { -0.0108f, -0.229958f, 0.1818f, 0.0442164f, -0.2829f, 0.110726f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1669)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.251f, 0.372f, -0.168f, 0.217f, -0.179f, 0.863f, -0.057f, 0.256f, 0.093f };
int lda = 3;
float B[] = { -0.727f, -0.461f, 0.162f, 0.579f, -0.305f, -0.735f };
int ldb = 3;
float B_expected[] = { -0.0547431f, 0.0563775f, 0.0781923f, 0.0435987f, -0.0809949f, 0.128653f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1670)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.014f, 0.204f, 0.163f, 0.842f, -0.918f, -0.748f, -0.859f, -0.463f, 0.292f };
int lda = 3;
float B[] = { -0.587f, -0.625f, -0.994f, 0.681f, -0.577f, -0.434f };
int ldb = 3;
float B_expected[] = { 0.1761f, 0.223424f, 0.186654f, -0.2043f, 0.131423f, -0.0325797f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1671)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.682f, -0.71f, 0.475f, -0.59f, -0.748f, 0.548f, 0.245f, 0.761f, -0.4f };
int lda = 3;
float B[] = { 0.565f, 0.967f, -0.969f, 0.184f, 0.349f, -0.552f };
int ldb = 3;
float B_expected[] = { 0.357979f, 0.438217f, -0.11628f, 0.139991f, 0.204337f, -0.06624f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1672)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.617f, -0.998f, -0.97f, 0.364f, 0.09f, 0.588f, -0.263f, 0.584f, 0.463f };
int lda = 3;
float B[] = { 0.773f, 0.074f, -0.388f, 0.825f, -0.608f, 0.788f };
int ldb = 3;
float B_expected[] = { -0.270594f, 0.0457776f, 0.1164f, -0.118933f, 0.0443424f, -0.2364f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1673)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.217f, -0.672f, -0.378f, -0.005f, -0.586f, -0.426f, 0.765f, -0.239f, -0.145f };
int lda = 3;
float B[] = { 0.01f, 0.387f, -0.953f, -0.374f, -0.673f, -0.724f };
int ldb = 2;
float B_expected[] = { -6.51e-04f, -0.0251937f, -0.167522f, -0.0651687f, -0.0999006f, -0.147126f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1674)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { 0.962f, 0.515f, 0.292f, 0.354f, -0.366f, 0.455f, 0.134f, -0.564f, -0.303f };
int lda = 3;
float B[] = { -0.337f, 0.718f, -0.866f, -0.454f, -0.439f, -0.668f };
int ldb = 2;
float B_expected[] = { 0.1011f, -0.2154f, 0.295589f, 0.0599484f, -0.0012798f, 0.0947196f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1675)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.228f, -0.097f, 0.205f, 0.875f, -0.162f, 0.542f, -0.839f, -0.935f, 0.2f };
int lda = 3;
float B[] = { -0.125f, -0.676f, 0.181f, 0.741f, 0.216f, 0.766f };
int ldb = 2;
float B_expected[] = { -0.0165669f, -0.0717843f, -0.026325f, -0.088539f, -0.01296f, -0.04596f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1676)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha = -0.3f;
float A[] = { -0.854f, -0.502f, 0.591f, -0.934f, -0.729f, 0.063f, 0.352f, 0.126f, -0.905f };
int lda = 3;
float B[] = { -0.626f, -0.694f, -0.889f, -0.251f, -0.42f, -0.353f };
int ldb = 2;
float B_expected[] = { 0.128383f, 0.232986f, 0.274638f, 0.0819717f, 0.126f, 0.1059f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1677)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.755f, 0.12f, 0.525f, 0.917f };
int lda = 2;
float B[] = { -0.927f, -0.813f, 0.624f, -0.366f, -0.864f, -0.046f };
int ldb = 3;
float B_expected[] = { 0.0699885f, 0.0613815f, -0.047112f, -0.0446862f, -0.0889848f, 0.0032698f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1678)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.444f, 0.515f, 0.081f, -0.69f };
int lda = 2;
float B[] = { 0.571f, -0.098f, -0.226f, -0.587f, 0.788f, -0.629f };
int ldb = 3;
float B_expected[] = { 0.0571f, -0.0098f, -0.0226f, -0.0292935f, 0.073753f, -0.074539f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1679)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.954f, 0.651f, -0.982f, 0.388f };
int lda = 2;
float B[] = { -0.927f, -0.281f, -0.918f, -0.527f, -0.652f, -0.393f };
int ldb = 3;
float B_expected[] = { 0.140187f, 0.0908338f, 0.12617f, -0.0204476f, -0.0252976f, -0.0152484f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1680)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { 0.811f, 0.852f, 0.224f, 0.443f };
int lda = 2;
float B[] = { -0.493f, -0.497f, -0.605f, 0.433f, -0.082f, -0.077f };
int ldb = 3;
float B_expected[] = { -0.0396008f, -0.0515368f, -0.0622248f, 0.0433f, -0.0082f, -0.0077f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1681)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.777f, 0.812f, 0.254f, 0.97f };
int lda = 2;
float B[] = { -0.509f, 0.171f, 0.986f, -0.644f, -0.97f, 0.814f };
int ldb = 2;
float B_expected[] = { 0.0395493f, 0.0036584f, -0.0766122f, -0.0374236f, 0.075369f, 0.05432f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1682)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { 0.962f, 0.912f, -0.238f, -0.336f };
int lda = 2;
float B[] = { -0.666f, 0.066f, -0.176f, 0.402f, 0.286f, -0.703f };
int ldb = 2;
float B_expected[] = { -0.0666f, 0.0224508f, -0.0176f, 0.0443888f, 0.0286f, -0.0771068f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1683)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { 0.859f, -0.547f, 0.076f, 0.542f };
int lda = 2;
float B[] = { 0.402f, 0.945f, -0.242f, -0.062f, 0.714f, 0.468f };
int ldb = 2;
float B_expected[] = { -0.0171597f, 0.051219f, -0.0173964f, -0.0033604f, 0.035733f, 0.0253656f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1684)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.779f, 0.435f, 0.612f, -0.723f };
int lda = 2;
float B[] = { 0.512f, -0.987f, -0.167f, 0.047f, -0.701f, -0.25f };
int ldb = 2;
float B_expected[] = { 0.0082655f, -0.0987f, -0.0146555f, 0.0047f, -0.080975f, -0.025f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1685)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.757f, 0.396f, -0.927f, -0.558f, -0.289f, -0.66f, 0.83f, 0.363f, -0.13f };
int lda = 3;
float B[] = { 0.041f, 0.333f, -0.682f, 0.193f, 0.581f, 0.963f };
int ldb = 3;
float B_expected[] = { 0.0733045f, 0.0353883f, 0.008866f, -0.0808726f, -0.0803489f, -0.012519f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1686)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.75f, 0.674f, -0.576f, 0.376f, -0.46f, -0.813f, 0.419f, 0.792f, 0.226f };
int lda = 3;
float B[] = { 0.511f, -0.544f, 0.938f, -0.126f, -0.873f, 0.118f };
int ldb = 3;
float B_expected[] = { -0.0395944f, -0.130659f, 0.0938f, -0.078237f, -0.0968934f, 0.0118f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1687)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.045f, -0.809f, 0.654f, 0.611f, -0.038f, -0.105f, -0.946f, 0.474f, -0.097f };
int lda = 3;
float B[] = { -0.625f, -0.123f, -0.48f, -0.088f, -0.757f, 0.974f };
int ldb = 3;
float B_expected[] = { 0.0028125f, -0.0377201f, 0.0579508f, 3.96e-04f, -0.0025002f, -0.0370048f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1688)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { 0.713f, 0.781f, 0.084f, -0.498f, 0.692f, 0.125f, 0.706f, -0.118f, -0.907f };
int lda = 3;
float B[] = { 0.442f, -0.563f, 0.065f, -0.18f, 0.63f, -0.328f };
int ldb = 3;
float B_expected[] = { 0.0442f, -0.0783116f, 0.0443486f, -0.018f, 0.071964f, -0.052942f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1689)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.442f, 0.566f, 0.064f, 0.962f, -0.669f, 0.416f, 0.761f, -0.359f, 0.863f };
int lda = 3;
float B[] = { 0.261f, -0.659f, -0.536f, 0.694f, -0.305f, -0.675f };
int ldb = 2;
float B_expected[] = { -0.0863099f, 0.0445231f, 0.0468079f, -0.0221961f, -0.0263215f, -0.0582525f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1690)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { 0.386f, 0.643f, -0.028f, -0.758f, -0.63f, -0.043f, 0.666f, -0.088f, 0.382f };
int lda = 3;
float B[] = { -0.241f, 0.766f, 0.656f, -0.977f, 0.274f, 0.565f };
int ldb = 2;
float B_expected[] = { -0.0555764f, 0.188286f, 0.0631888f, -0.102672f, 0.0274f, 0.0565f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1691)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.855f, -0.587f, 0.062f, 0.372f, 0.48f, -0.63f, -0.786f, -0.437f, -0.431f };
int lda = 3;
float B[] = { 0.116f, 0.534f, 0.043f, 0.73f, 0.945f, 0.528f };
int ldb = 2;
float B_expected[] = { -0.009918f, -0.045657f, -0.0047452f, 0.0036942f, -0.0427193f, -0.065436f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1692)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha = 0.1f;
float A[] = { -0.068f, 0.119f, -0.244f, -0.05f, 0.685f, 0.752f, -0.059f, -0.935f, -0.571f };
int lda = 3;
float B[] = { -0.753f, -0.319f, 0.164f, 0.979f, 0.885f, -0.822f };
int ldb = 2;
float B_expected[] = { -0.0753f, -0.0319f, 0.0074393f, 0.0941039f, 0.119206f, -7.956e-04f };
cblas_strmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], flteps, "strmm(case 1693)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.174, -0.308, 0.997, -0.484 };
int lda = 2;
double B[] = { -0.256, -0.178, 0.098, 0.004, 0.97, -0.408 };
int ldb = 3;
double B_expected[] = { 0.0137328, 0.0989196, -0.0428148, 5.808e-04, 0.140844, -0.0592416 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1694)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.722, -0.372, 0.466, -0.831 };
int lda = 2;
double B[] = { 0.322, -0.183, 0.849, -0.051, -0.343, -0.98 };
int ldb = 3;
double B_expected[] = { -0.1022916, 0.0166212, -0.364068, 0.0153, 0.1029, 0.294 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1695)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.656, -0.066, 0.582, 0.141 };
int lda = 2;
double B[] = { 0.73, 0.407, 0.721, 0.086, -0.294, 0.941 };
int ldb = 3;
double B_expected[] = { 0.143664, 0.0800976, 0.1418928, -0.1310958, -0.058626, -0.1656909 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1696)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.341, 0.386, -0.578, 0.863 };
int lda = 2;
double B[] = { -0.306, -0.047, -0.162, -0.784, 0.472, 0.137 };
int ldb = 3;
double B_expected[] = { 0.0918, 0.0141, 0.0486, 0.1821396, -0.1497498, -0.0691908 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1697)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.844, -0.832, 0.179, -0.775 };
int lda = 2;
double B[] = { -0.415, -0.547, -0.023, 0.42, 0.917, 0.485 };
int ldb = 2;
double B_expected[] = { 0.1344519, -0.1271775, -0.0167304, 0.09765, -0.2582289, 0.1127625 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1698)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.239, 0.34, 0.964, -0.575 };
int lda = 2;
double B[] = { 0.762, -0.038, -0.8, 0.626, -0.701, 0.639 };
int ldb = 2;
double B_expected[] = { -0.2176104, 0.0114, 0.0589608, -0.1878, 0.0255012, -0.1917 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1699)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.785, -0.0, -0.592, -0.661 };
int lda = 2;
double B[] = { -0.215, 0.953, 0.527, -0.418, -0.675, 0.283 };
int ldb = 2;
double B_expected[] = { 0.0506325, 0.1889799, -0.1241085, -0.0828894, 0.1589625, 0.0561189 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1700)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.423, -0.807, -0.683, -0.225 };
int lda = 2;
double B[] = { 0.149, -0.129, 0.149, -0.234, 0.275, 0.658 };
int ldb = 2;
double B_expected[] = { -0.0447, 0.0747729, -0.0447, 0.1062729, -0.0825, -0.1308225 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1701)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.276, 0.434, 0.917, 0.682, -0.32, 0.557, -0.302, 0.989, -0.043 };
int lda = 3;
double B[] = { -0.943, 0.839, 0.759, 0.752, 0.807, 0.288 };
int ldb = 3;
double B_expected[] = { -0.0780804, 0.2033226, 0.1290135, 0.0622656, -0.0204384, -0.3380097 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1702)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.731, -0.953, -0.666, 0.684, 0.38, 0.419, -0.361, 0.378, -0.423 };
int lda = 3;
double B[] = { -0.983, 0.479, -0.136, 0.048, 0.745, -0.408 };
int ldb = 3;
double B_expected[] = { 0.2949, -0.4247397, -0.2158137, -0.0144, -0.2097768, 0.0383439 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1703)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.953, -0.983, 0.237, 0.128, -0.378, 0.607, 0.41, 0.418, -0.221 };
int lda = 3;
double B[] = { -0.561, -0.114, -0.148, 0.488, 0.146, -0.688 };
int ldb = 3;
double B_expected[] = { -0.1378083, 0.0056316, -0.0098124, 0.2185368, 0.1028316, -0.0456144 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1704)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.277, -0.587, 0.885, -0.933, -0.582, 0.528, 0.268, -0.804, 0.62 };
int lda = 3;
double B[] = { -0.831, -0.319, -0.547, -0.577, 0.295, -0.31 };
int ldb = 3;
double B_expected[] = { 0.2039907, -0.0362364, 0.1641, 0.2805945, -0.163272, 0.093 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1705)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.256, 0.554, 0.342, 0.318, -0.824, -0.119, -0.399, -0.653, -0.83 };
int lda = 3;
double B[] = { -0.577, 0.861, -0.439, -0.916, 0.452, -0.168 };
int ldb = 2;
double B_expected[] = { 0.0443136, -0.0661248, -0.053475, -0.3085746, -0.042519, -0.1182147 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1706)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.837, -0.03, 0.552, -0.43, 0.841, 0.035, 0.7, 0.637, 0.095 };
int lda = 3;
double B[] = { -0.82, -0.362, -0.252, -0.062, -0.942, -0.299 };
int ldb = 2;
double B_expected[] = { 0.246, 0.1086, -0.03018, -0.028098, 0.5029572, 0.1775682 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1707)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { -0.074, 0.49, 0.802, -0.454, 0.626, 0.123, -0.959, 0.971, 0.75 };
int lda = 3;
double B[] = { -0.545, -0.107, 0.096, 0.183, 0.185, -0.218 };
int ldb = 2;
double B_expected[] = { -0.070722, 0.0231744, -0.0248553, -0.0263232, -0.041625, 0.04905 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1708)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha = -0.3;
double A[] = { 0.048, 0.148, 0.834, -0.98, -0.009, -0.727, 0.241, 0.276, 0.518 };
int lda = 3;
double B[] = { -0.664, -0.136, -0.793, -0.742, 0.126, -0.131 };
int ldb = 2;
double B_expected[] = { 0.202884, 0.106521, 0.2653806, 0.1940289, -0.0378, 0.0393 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1709)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.427, 0.495, 0.282, 0.158 };
int lda = 2;
double B[] = { 0.899, -0.375, 0.376, -0.831, 0.431, -0.387 };
int ldb = 3;
double B_expected[] = { 0.0383873, -0.0160125, 0.0160552, 0.0313707, -0.0117527, 0.0124974 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1710)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.632, -0.174, 0.608, -0.669 };
int lda = 2;
double B[] = { -0.335, 0.535, -0.978, 0.31, 0.023, -0.853 };
int ldb = 3;
double B_expected[] = { -0.0335, 0.0535, -0.0978, 0.036829, -0.007009, -0.0682828 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1711)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.779, -0.73, 0.343, -0.665 };
int lda = 2;
double B[] = { -0.976, -0.2, 0.661, -0.975, -0.965, -0.861 };
int ldb = 3;
double B_expected[] = { 0.0425879, -0.0175195, -0.0810242, 0.0648375, 0.0641725, 0.0572565 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1712)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.127, -0.634, -0.384, -0.815 };
int lda = 2;
double B[] = { -0.348, 0.748, 0.893, 0.91, 0.153, -0.408 };
int ldb = 3;
double B_expected[] = { -0.069744, 0.0689248, 0.1049672, 0.091, 0.0153, -0.0408 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1713)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.603, -0.617, 0.402, -0.918 };
int lda = 2;
double B[] = { 0.051, -0.096, 0.476, 0.377, 0.931, 0.291 };
int ldb = 2;
double B_expected[] = { -0.0030753, 0.010863, -0.0287028, -0.0154734, -0.0561393, 0.0107124 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1714)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.67, -0.475, 0.032, -0.036 };
int lda = 2;
double B[] = { -0.19, 0.829, 0.942, 0.885, 0.087, 0.321 };
int ldb = 2;
double B_expected[] = { -0.019, 0.082292, 0.0942, 0.0915144, 0.0087, 0.0323784 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1715)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.64, 0.595, 0.642, -0.921 };
int lda = 2;
double B[] = { -0.278, -0.83, 0.922, -0.701, -0.598, -0.232 };
int ldb = 2;
double B_expected[] = { -0.031593, 0.076443, -0.1007175, 0.0645621, 0.024468, 0.0213672 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1716)");
}
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.842, 0.625, 0.967, 0.341 };
int lda = 2;
double B[] = { -0.679, -0.846, -0.921, 0.672, 0.292, 0.752 };
int ldb = 2;
double B_expected[] = { -0.120775, -0.0846, -0.0501, 0.0672, 0.0762, 0.0752 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1717)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.612, 0.593, 0.113, -0.658, 0.703, -0.023, -0.384, 0.439, 0.958 };
int lda = 3;
double B[] = { -0.858, -0.559, 0.499, -0.114, 0.57, 0.847 };
int ldb = 3;
double B_expected[] = { 0.0249996, -0.0404454, 0.0478042, 0.0503489, 0.0381229, 0.0811426 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1718)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.844, 0.205, -0.692, -0.401, -0.823, 0.342, -0.384, 0.344, 0.18 };
int lda = 3;
double B[] = { 0.823, -0.181, 0.141, 0.932, 0.097, -0.636 };
int ldb = 3;
double B_expected[] = { 0.0688323, -0.0132778, 0.0141, 0.1391997, -0.0120512, -0.0636 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1719)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.065, 0.678, 0.044, -0.472, 0.932, -0.388, 0.432, -0.167, -0.277 };
int lda = 3;
double B[] = { 0.675, -0.468, -0.564, 0.71, -0.624, 0.023 };
int ldb = 3;
double B_expected[] = { 0.0043875, -0.0754776, 0.0525984, 0.004615, -0.0916688, 0.0404557 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1720)");
}
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.649, -0.171, -0.462, 0.593, 0.131, -0.317, -0.254, -0.948, 0.002 };
int lda = 3;
double B[] = { -0.519, -0.501, -0.024, -0.767, -0.591, -0.738 };
int ldb = 3;
double B_expected[] = { -0.0519, -0.0808767, 0.0582774, -0.0767, -0.1045831, 0.0017086 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1721)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.023, -0.872, -0.313, -0.698, 0.06, -0.838, -0.455, -0.715, -0.257 };
int lda = 3;
double B[] = { -0.17, -0.184, -0.243, 0.907, -0.423, 0.665 };
int ldb = 2;
double B_expected[] = { 0.0365989, -0.0931429, 0.0287865, -0.0421055, 0.0108711, -0.0170905 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1722)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.792, 0.338, -0.155, 0.009, 0.485, -0.633, -0.08, -0.579, 0.223 };
int lda = 3;
double B[] = { -0.19, 0.201, 0.685, 0.663, 0.302, -0.506 };
int ldb = 2;
double B_expected[] = { -0.0207995, 0.0247447, 0.0510142, 0.0955974, 0.0302, -0.0506 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1723)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { -0.076, 0.103, -0.021, -0.866, 0.777, 0.723, 0.378, 0.98, -0.32 };
int lda = 3;
double B[] = { 0.739, -0.996, 0.182, 0.626, 0.291, -0.267 };
int ldb = 2;
double B_expected[] = { -0.0056164, 0.0075696, 0.0217531, 0.0383814, 0.0022947, 0.0558954 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1724)");
}
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha = 0.1;
double A[] = { 0.469, 0.822, -0.619, 0.953, -0.706, 0.318, 0.559, -0.68, -0.208 };
int lda = 3;
double B[] = { 0.362, 0.719, -0.661, -0.504, 0.595, -0.771 };
int ldb = 2;
double B_expected[] = { 0.0362, 0.0719, -0.0363436, 0.0087018, 0.0160724, -0.1376333 };
cblas_dtrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[i], B_expected[i], dbleps, "dtrmm(case 1725)");
}
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.023f, 0.762f, -0.687f, -0.039f, -0.459f, 0.047f, 0.189f, 0.33f };
int lda = 2;
float B[] = { 0.827f, -0.561f, 0.641f, -0.229f, -0.884f, -0.533f, -0.624f, -0.138f, 0.073f, 0.924f, -0.501f, -0.164f };
int ldb = 3;
float B_expected[] = { -0.831767f, -0.762219f, -0.14564f, 0.143926f, -0.764269f, 0.529142f, 0.072396f, 0.232002f, 0.291123f, -0.198726f, 0.040569f, 0.196326f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1726) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1726) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.24f, 0.581f, 0.06f, 0.064f, 0.981f, 0.792f, 0.242f, -0.529f };
int lda = 2;
float B[] = { -0.649f, -0.774f, -0.43f, -0.447f, -0.266f, 0.285f, 0.787f, 0.274f, 0.449f, -0.912f, 0.435f, 0.601f };
int ldb = 3;
float B_expected[] = { 0.619316f, 0.707192f, 0.344692f, 0.472984f, 0.278364f, -0.3489f, -0.787f, -0.274f, -0.449f, 0.912f, -0.435f, -0.601f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1727) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1727) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.68f, -0.728f, -0.59f, -0.434f, -0.936f, 0.915f, 0.236f, -0.118f };
int lda = 2;
float B[] = { 0.461f, 0.48f, 0.224f, 0.215f, -0.419f, -0.525f, 0.113f, -0.582f, 0.468f, 0.269f, 0.943f, -0.587f };
int ldb = 3;
float B_expected[] = { -0.66292f, 0.009208f, -0.30884f, 0.016872f, 0.66712f, 0.051968f, 0.912704f, 0.178151f, 0.264199f, -0.01198f, -1.02584f, 0.141791f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1728) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1728) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.699f, -0.709f, -0.775f, 0.779f, 0.5f, 0.774f, -0.399f, -0.843f };
int lda = 2;
float B[] = { 0.538f, 0.556f, -0.186f, -0.678f, -0.413f, -0.612f, -0.216f, -0.519f, -0.344f, -0.578f, -0.938f, -0.848f };
int ldb = 3;
float B_expected[] = { -0.538f, -0.556f, 0.186f, 0.678f, 0.413f, 0.612f, 0.377344f, -0.175412f, -0.087772f, 1.06096f, 0.670812f, 1.47366f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1729) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1729) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.527f, 0.318f, -0.224f, 0.547f, -0.765f, -0.469f, 0.233f, 0.023f };
int lda = 2;
float B[] = { 0.54f, -0.418f, -0.892f, -0.118f, -0.296f, 0.019f, 0.786f, -0.145f, 0.136f, 0.472f, 0.731f, 0.333f };
int ldb = 2;
float B_expected[] = { -1.04454f, -0.460052f, 0.205122f, 0.04801f, 0.831329f, 0.341824f, -0.186473f, 0.015707f, 0.481462f, 0.305592f, -0.162664f, -0.094402f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1730) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1730) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.109f, -0.852f, 0.395f, 0.871f, 0.378f, -0.493f, 0.51f, 0.973f };
int lda = 2;
float B[] = { -0.867f, -0.758f, 0.687f, -0.596f, -0.912f, -0.561f, -0.389f, 0.21f, -0.561f, 0.132f, 0.689f, 0.653f };
int ldb = 2;
float B_expected[] = { 0.901142f, 1.32198f, -0.687f, 0.596f, 0.955512f, 0.289843f, 0.389f, -0.21f, -0.021371f, -0.039157f, -0.689f, -0.653f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1731) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1731) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.686f, 0.349f, 0.299f, -0.462f, 0.009f, -0.693f, -0.478f, -0.617f };
int lda = 2;
float B[] = { -0.409f, 0.986f, -0.854f, 0.346f, 0.444f, -0.659f, 0.027f, 0.007f, 0.842f, -0.473f, 0.825f, 0.866f };
int ldb = 2;
float B_expected[] = { 0.624688f, -0.533655f, -0.954935f, -0.845302f, -0.534575f, 0.297118f, 0.180289f, 0.422174f, -0.742689f, 0.03062f, -0.173204f, 1.4534f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1732) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1732) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.286f, 0.661f, 0.372f, 0.28f, 0.482f, 0.267f, -0.436f, 0.844f };
int lda = 2;
float B[] = { 0.0f, -0.513f, 0.91f, 0.109f, 0.587f, -0.183f, 0.112f, 0.362f, -0.256f, -0.518f, -0.933f, 0.066f };
int ldb = 2;
float B_expected[] = { 0.0f, 0.513f, -1.05364f, 0.081836f, -0.587f, 0.183f, -0.381604f, -0.458284f, 0.256f, 0.518f, 0.883192f, 0.198376f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1733) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1733) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.678f, 0.717f, 0.228f, 0.001f, -0.16f, -0.387f, -0.281f, -0.002f, 0.623f, 0.162f, -0.594f, 0.632f, 0.566f, 0.352f, -0.411f, 0.574f, 0.314f, -0.139f };
int lda = 3;
float B[] = { -0.823f, -0.042f, 0.171f, -0.928f, 0.66f, 0.965f, 0.472f, 0.006f, -0.083f, 0.937f, -0.814f, 0.9f };
int ldb = 3;
float B_expected[] = { 0.52788f, 0.618567f, -0.069267f, 0.560841f, -0.941723f, -1.19579f, -0.315714f, -0.342492f, 0.095893f, -0.572145f, 0.746576f, 0.396912f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1734) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1734) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.346f, 0.915f, -0.227f, -0.066f, -0.166f, -0.921f, -0.373f, 0.312f, -0.824f, 0.699f, -0.114f, -0.152f, 0.862f, -0.077f, 0.221f, -0.757f, -0.413f, -0.494f };
int lda = 3;
float B[] = { -0.02f, -0.247f, -0.62f, 0.651f, -0.07f, -0.491f, 0.042f, 0.936f, 0.272f, -0.582f, 0.012f, -0.534f };
int ldb = 3;
float B_expected[] = { 0.02f, 0.247f, 0.631762f, -0.708389f, 0.124535f, 0.411552f, -0.042f, -0.936f, -0.324242f, 0.797244f, -0.747612f, 0.703054f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1735) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1735) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.493f, -0.882f, -0.82f, 0.627f, 0.301f, -0.903f, -0.092f, 0.787f, -0.426f, -0.854f, -0.993f, 0.118f, 0.615f, 0.362f, -0.238f, -0.076f, 0.817f, -0.286f };
int lda = 3;
float B[] = { 0.395f, 0.074f, -0.191f, -0.548f, 0.858f, 0.323f, -0.734f, 0.612f, 0.895f, 0.849f, 0.811f, 0.402f };
int ldb = 3;
float B_expected[] = { -0.730125f, -0.024468f, 0.566282f, -0.25448f, -0.793364f, -0.018503f, -0.504384f, -1.51274f, -0.18131f, 1.28332f, -0.777559f, -0.096488f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1736) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1736) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.033f, -0.383f, 0.116f, 0.797f, -0.99f, 0.765f, 0.915f, 0.002f, 0.228f, 0.077f, 0.597f, -0.454f, -0.629f, 0.424f, -0.89f, 0.339f, -0.484f, 0.169f };
int lda = 3;
float B[] = { -0.377f, -0.451f, -0.464f, -0.673f, 0.231f, -0.712f, -0.457f, -0.588f, 0.373f, -0.754f, -0.468f, 0.433f };
int ldb = 3;
float B_expected[] = { 0.643625f, 0.521931f, 0.428222f, -0.038989f, -0.231f, 0.712f, 0.003417f, 1.74795f, -0.642733f, 1.29802f, 0.468f, -0.433f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1737) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1737) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.946f, -0.007f, 0.677f, -0.923f, 0.651f, -0.685f, 0.591f, 0.135f, 0.171f, 0.979f, -0.029f, -0.008f, -0.049f, 0.174f, 0.578f, 0.388f, 0.187f, -0.479f };
int lda = 3;
float B[] = { -0.607f, -0.907f, -0.156f, -0.141f, -0.254f, 0.364f, 0.209f, 0.955f, 0.93f, 0.962f, 0.494f, 0.079f };
int ldb = 2;
float B_expected[] = { 0.580571f, 0.853773f, 0.148563f, 0.132294f, 0.636082f, 0.804404f, 0.972367f, -0.263525f, -0.534225f, 0.214911f, 0.087341f, -0.390994f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1738) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1738) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.203f, -0.791f, -0.415f, -0.56f, 0.782f, -0.691f, -0.441f, 0.545f, -0.09f, 0.595f, -0.438f, 0.952f, 0.88f, 0.944f, -0.55f, -0.762f, -0.035f, -0.949f };
int lda = 3;
float B[] = { -0.035f, 0.448f, 0.487f, -0.108f, -0.482f, -0.708f, -0.317f, 0.816f, -0.547f, 0.22f, -0.654f, 0.57f };
int ldb = 2;
float B_expected[] = { 0.035f, -0.448f, -0.487f, 0.108f, 0.710725f, 0.924643f, 0.472907f, -1.12904f, 1.27511f, -1.33788f, -0.672654f, -0.727442f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1739) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1739) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { -0.09f, 0.742f, 0.081f, 0.459f, -0.54f, 0.04f, 0.574f, -0.858f, 0.704f, 0.686f, -0.9f, -0.519f, 0.538f, -0.934f, 0.467f, 0.376f, 0.149f, 0.322f };
int lda = 3;
float B[] = { 0.307f, 0.294f, -0.428f, -0.7f, 0.496f, 0.167f, -0.611f, 0.904f, -0.846f, -0.411f, 0.29f, 0.004f };
int ldb = 2;
float B_expected[] = { -0.191025f, -0.630625f, 0.063267f, 0.452361f, -0.782713f, -1.2668f, 1.30921f, -0.06316f, -0.006288f, 0.333651f, -0.041922f, -0.093976f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1740) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1740) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-1.0f, 0.0f};
float A[] = { 0.434f, 0.691f, 0.983f, -0.481f, -0.156f, -0.117f, -0.231f, 0.526f, 0.935f, 0.417f, -0.142f, -0.541f, 0.529f, 0.014f, 0.266f, 0.086f, 0.666f, 0.033f };
int lda = 3;
float B[] = { 0.972f, -0.219f, -0.735f, -0.967f, 0.084f, -0.355f, -0.152f, -0.156f, 0.267f, 0.928f, 0.708f, -0.267f };
int ldb = 2;
float B_expected[] = { -0.950741f, 0.784376f, 1.10114f, 1.08842f, -0.548134f, 0.631223f, 0.396983f, 0.501114f, -0.267f, -0.928f, -0.708f, 0.267f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1741) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1741) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.25f, -0.779f, -0.138f, -0.017f, -0.319f, -0.555f, 0.674f, -0.256f };
int lda = 2;
float B[] = { -0.651f, -0.525f, 0.409f, -0.932f, 0.359f, 0.321f, 0.419f, 0.027f, 0.67f, 0.328f, 0.446f, -0.615f };
int ldb = 3;
float B_expected[] = { 0.0100296f, -0.216136f, 0.257045f, -0.0571445f, -0.0121016f, 0.124004f, -0.110514f, 0.0386878f, -0.1561f, -0.0050383f, 0.028185f, 0.183634f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1742) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1742) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.012f, 0.978f, 0.617f, -0.361f, -0.349f, 0.712f, 0.008f, 0.305f };
int lda = 2;
float B[] = { -0.771f, -0.335f, -0.565f, 0.866f, -0.516f, -0.869f, -0.097f, -0.711f, 0.308f, 0.207f, -0.459f, 0.766f };
int ldb = 3;
float B_expected[] = { 0.2648f, 0.0234f, 0.0829f, -0.3163f, 0.2417f, 0.2091f, 0.272029f, 0.122445f, -0.176135f, -0.256384f, 0.285714f, -0.233939f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1743) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1743) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.063f, -0.605f, 0.473f, 0.763f, 0.548f, -0.167f, -0.825f, 0.011f };
int lda = 2;
float B[] = { -0.262f, 0.135f, -0.333f, -0.671f, 0.91f, 0.874f, 0.305f, -0.255f, 0.882f, 0.883f, 0.088f, -0.473f };
int ldb = 3;
float B_expected[] = { -0.0627538f, 0.0344746f, -0.131779f, -0.149516f, -0.0442507f, 0.307921f, 0.053273f, -0.089001f, 0.293086f, 0.141896f, -0.0189002f, -0.124098f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1744) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1744) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.493f, -0.852f, -0.567f, 0.21f, 0.168f, 0.666f, -0.328f, 0.803f };
int lda = 2;
float B[] = { 0.24f, -0.578f, 0.293f, -0.233f, -0.348f, -0.853f, -0.145f, 0.192f, -0.785f, -0.72f, -0.508f, 0.023f };
int ldb = 3;
float B_expected[] = { 0.037901f, 0.201471f, -0.104515f, 0.327095f, 0.253345f, 0.311373f, 0.0243f, -0.0721f, 0.3075f, 0.1375f, 0.1501f, -0.0577f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1745) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1745) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.089f, -0.135f, 0.987f, 0.936f, 0.353f, 0.638f, 0.845f, 0.343f };
int lda = 2;
float B[] = { 0.744f, 0.445f, 0.835f, 0.273f, 0.702f, 0.03f, -0.618f, 0.141f, -0.303f, -0.399f, 0.63f, -0.037f };
int ldb = 2;
float B_expected[] = { 0.0158468f, 0.0413994f, -0.292082f, -0.285588f, 0.0272724f, 0.0233892f, 0.0660084f, -0.143882f, 0.0004278f, -0.0256146f, -0.19286f, 0.114065f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1746) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1746) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.187f, -0.741f, 0.287f, -0.599f, -0.293f, -0.297f, 0.778f, -0.056f };
int lda = 2;
float B[] = { -0.335f, -0.713f, 0.081f, -0.589f, -0.256f, -0.809f, -0.473f, 0.418f, 0.646f, -0.447f, -0.147f, 0.314f };
int ldb = 2;
float B_expected[] = { 0.1718f, 0.1804f, 0.0378414f, 0.0809182f, 0.1577f, 0.2171f, 0.118373f, -0.283147f, -0.1491f, 0.1987f, 0.1154f, -0.122836f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1747) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1747) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.259f, -0.645f, -0.09f, 0.709f, 0.729f, -0.023f, -0.792f, 0.03f };
int lda = 2;
float B[] = { 0.904f, -0.402f, 0.753f, 0.104f, 0.38f, 0.944f, -0.715f, -0.378f, -0.16f, 0.254f, -0.68f, 0.183f };
int ldb = 2;
float B_expected[] = { 0.185924f, -0.0771597f, 0.185827f, -0.0420162f, -0.156592f, 0.373034f, -0.201079f, -0.0256158f, 0.0051007f, 0.152025f, -0.143387f, 0.102908f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1748) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1748) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.938f, 0.25f, -0.509f, 0.377f, -0.063f, 0.166f, 0.227f, -0.24f };
int lda = 2;
float B[] = { 0.756f, -0.08f, -0.657f, -0.837f, -0.714f, 0.781f, 0.239f, -0.953f, 0.26f, 0.696f, -0.183f, 0.668f };
int ldb = 2;
float B_expected[] = { -0.431623f, 0.111093f, 0.2808f, 0.1854f, 0.007293f, -0.454491f, 0.0236f, 0.3098f, -0.059093f, -0.075968f, -0.0119f, -0.2187f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1749) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1749) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.055f, -0.682f, 0.361f, 0.521f, -0.192f, -0.664f, -0.167f, 0.731f, -0.668f, 0.983f, 0.608f, 0.533f, -0.513f, -0.781f, 0.878f, 0.875f, 0.804f, -0.179f };
int lda = 3;
float B[] = { -0.038f, -0.787f, -0.209f, -0.686f, -0.073f, -0.662f, 0.938f, -0.301f, -0.871f, 0.699f, 0.561f, 0.823f };
int ldb = 3;
float B_expected[] = { 0.224558f, -0.0087435f, -0.317863f, 0.168822f, 0.105075f, 0.138035f, 0.256887f, 0.377119f, 0.113231f, 0.136832f, -0.235636f, -0.108546f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1750) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1750) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.397f, -0.154f, -0.944f, -0.137f, 0.65f, -0.49f, -0.883f, 0.273f, -0.137f, 0.655f, 0.531f, 0.676f, 0.052f, 0.03f, -0.602f, 0.002f, 0.005f, 0.984f };
int lda = 3;
float B[] = { -0.446f, 0.091f, 0.793f, -0.221f, 0.386f, 0.354f, -0.063f, 0.105f, -0.128f, 0.189f, -0.079f, 0.749f };
int ldb = 3;
float B_expected[] = { 0.216958f, -0.149634f, -0.25039f, 0.0074932f, -0.1512f, -0.0676f, -0.166784f, -0.100965f, 0.14955f, -0.227622f, -0.0512f, -0.2326f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1751) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1751) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.976f, -0.488f, -0.762f, -0.057f, 0.812f, 0.006f, 0.06f, -0.271f, 0.832f, -0.232f, 0.188f, -0.466f, -0.051f, -0.745f, 0.909f, -0.091f, -0.559f, 0.595f };
int lda = 3;
float B[] = { 0.644f, -0.584f, 0.456f, 0.443f, -0.909f, 0.43f, 0.771f, -0.075f, -0.408f, 0.303f, 0.03f, 0.529f };
int ldb = 3;
float B_expected[] = { 0.24849f, -0.168067f, -0.114085f, 0.0202884f, 0.0152508f, 0.284926f, 0.267034f, 0.0120048f, 0.0596364f, -0.0643158f, 0.284594f, 0.0837608f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1752) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1752) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.924f, -0.247f, -0.131f, 0.932f, -0.415f, 0.454f, -0.539f, 0.693f, -0.725f, -0.601f, 0.565f, 0.002f, -0.118f, 0.626f, -0.968f, 0.874f, 0.156f, -0.227f };
int lda = 3;
float B[] = { 0.793f, -0.15f, -0.967f, 0.821f, 0.37f, -0.572f, -0.156f, 0.106f, -0.877f, -0.297f, 0.448f, -0.576f };
int ldb = 3;
float B_expected[] = { -0.2229f, 0.1243f, 0.242003f, -0.564467f, -0.0068716f, 0.568213f, 0.0362f, -0.0474f, 0.306136f, 0.0520352f, -0.336053f, 0.500406f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1753) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1753) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.671f, 0.477f, 0.227f, 0.685f, -0.648f, 0.277f, -0.295f, -0.632f, 0.509f, -0.798f, 0.875f, 0.89f, -0.34f, -0.786f, -0.453f, 0.511f, -0.189f, 0.385f };
int lda = 3;
float B[] = { -0.895f, -0.148f, 0.934f, 0.229f, 0.958f, -0.55f, 0.49f, 0.586f, -0.871f, 0.618f, -0.0f, -0.543f };
int ldb = 2;
float B_expected[] = { 0.162976f, 0.110656f, -0.12507f, -0.0587256f, 0.138701f, 0.543589f, -0.313677f, 0.0534812f, 0.067207f, 0.12831f, -0.0729792f, -0.0098826f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1754) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1754) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.438f, -0.618f, 0.524f, 0.525f, -0.268f, -0.502f, -0.685f, 0.28f, 0.508f, 0.664f, -0.492f, 0.772f, -0.997f, 0.693f, 0.63f, -0.328f, -0.521f, -0.869f };
int lda = 3;
float B[] = { 0.527f, 0.999f, -0.078f, 0.599f, 0.004f, -0.615f, -0.281f, -0.328f, 0.456f, -0.666f, 0.309f, -0.69f };
int ldb = 2;
float B_expected[] = { -0.45115f, -0.650085f, -0.277633f, -0.456478f, 0.0965652f, 0.362528f, 0.1802f, 0.227951f, -0.0702f, 0.2454f, -0.0237f, 0.2379f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1755) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1755) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.454f, 0.517f, -0.794f, -0.181f, 0.292f, 0.954f, -0.93f, -0.128f, 0.123f, -0.997f, 0.325f, -0.317f, -0.988f, 0.732f, 0.637f, 0.457f, -0.665f, 0.529f };
int lda = 3;
float B[] = { -0.055f, 0.803f, -0.981f, -0.627f, 0.147f, -0.656f, -0.824f, -0.366f, -0.445f, -0.151f, 0.686f, -0.368f };
int ldb = 2;
float B_expected[] = { 0.156354f, 0.078881f, -0.208608f, 0.143709f, 0.219569f, 0.211768f, -0.204943f, -0.415655f, 0.191227f, 0.0071854f, 0.136999f, 0.0773624f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1756) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1756) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.623f, -0.129f, -0.419f, -0.006f, 0.21f, -0.165f, 0.218f, 0.915f, 0.736f, 0.07f, 0.502f, -0.809f, 0.242f, -0.015f, 0.67f, -0.956f, 0.153f, 0.365f };
int lda = 3;
float B[] = { -0.927f, 0.383f, -0.471f, 0.443f, -0.731f, -0.949f, -0.142f, -0.65f, 0.159f, -0.624f, -0.822f, 0.107f };
int ldb = 2;
float B_expected[] = { 0.2398f, -0.2076f, 0.097f, -0.18f, 0.212478f, 0.297146f, 0.065877f, 0.255638f, 0.359717f, -0.0280276f, 0.426852f, -0.164392f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1757) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1757) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.628f, -0.771f, 0.827f, -0.979f, 0.395f, -0.166f, 0.88f, 0.958f };
int lda = 2;
float B[] = { 0.297f, 0.49f, 0.425f, -0.386f, 0.672f, 0.992f, -0.077f, 0.761f, 0.393f, -0.605f, -0.273f, 0.725f };
int ldb = 3;
float B_expected[] = { 0.177165f, -0.0328107f, -0.0662201f, -0.167954f, 0.366541f, -0.0872256f, -0.2721f, -0.389113f, -0.0674816f, 0.293174f, -0.249446f, -0.709453f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1758) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1758) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.876f, 0.752f, -0.148f, 0.972f, -0.508f, -0.752f, -0.861f, 0.074f };
int lda = 2;
float B[] = { 0.878f, -0.987f, -0.896f, 0.519f, -0.355f, -0.117f, 0.329f, 0.068f, -0.644f, 0.344f, -0.187f, -0.343f };
int ldb = 3;
float B_expected[] = { -0.1647f, 0.3839f, 0.2169f, -0.2453f, 0.1182f, -0.0004f, 0.292026f, 0.115771f, -0.111733f, -0.342122f, 0.0725176f, -0.0306312f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1759) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1759) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.072f, -0.966f, 0.648f, 0.43f, -0.623f, -0.221f, -0.622f, 0.977f };
int lda = 2;
float B[] = { 0.0f, 0.028f, 0.857f, -0.171f, -0.933f, 0.159f, 0.315f, -0.297f, -0.864f, 0.519f, -0.601f, -0.119f };
int ldb = 3;
float B_expected[] = { 0.0216306f, -0.0927642f, -0.225266f, -0.0253344f, 0.0408658f, 0.302549f, 0.158132f, -0.0117036f, -0.365472f, -0.0519459f, -0.143387f, -0.172603f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1760) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1760) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.903f, -0.972f, -0.812f, 0.605f, 0.085f, -0.025f, -0.443f, 0.518f };
int lda = 2;
float B[] = { -0.725f, -0.451f, 0.779f, 0.969f, 0.25f, 0.021f, 0.029f, -0.382f, 0.022f, 0.957f, 0.704f, 0.832f };
int ldb = 3;
float B_expected[] = { 0.26217f, 0.073525f, -0.332173f, -0.239574f, -0.097644f, -0.003892f, 0.0295f, 0.1175f, -0.1023f, -0.2849f, -0.2944f, -0.1792f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1761) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1761) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.322f, -0.981f, 0.193f, -0.604f, 0.87f, -0.384f, 0.463f, -0.502f };
int lda = 2;
float B[] = { -0.447f, 0.21f, 0.928f, -0.496f, 0.889f, -0.354f, -0.258f, -0.149f, 0.98f, -0.958f, 0.106f, -0.579f };
int ldb = 2;
float B_expected[] = { 0.0692355f, 0.14563f, -0.0874638f, -0.0532654f, -0.116915f, -0.289728f, -0.242902f, 0.136003f, -0.314257f, -0.318533f, -0.400862f, 0.357622f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1762) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1762) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.924f, -0.553f, 0.985f, -0.793f, 0.406f, 0.741f, -0.956f, 0.945f };
int lda = 2;
float B[] = { 0.736f, -0.81f, 0.028f, 0.474f, 0.14f, -0.03f, -0.756f, 0.923f, -0.515f, 0.532f, -0.321f, 0.326f };
int ldb = 2;
float B_expected[] = { -0.1398f, 0.3166f, 0.122042f, 0.0927314f, -0.039f, 0.023f, 0.135709f, -0.314263f, 0.1013f, -0.2111f, -0.0515973f, -0.29067f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1763) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1763) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.04f, -0.41f, -0.643f, 0.988f, 0.86f, -0.281f, -0.017f, 0.389f };
int lda = 2;
float B[] = { 0.204f, 0.524f, -0.558f, -0.736f, 0.26f, -0.202f, -0.757f, 0.346f, 0.917f, 0.541f, -0.108f, -0.965f };
int ldb = 2;
float B_expected[] = { 0.059601f, -0.396251f, 0.060088f, -0.096554f, -0.338942f, -0.0950055f, -0.073098f, -0.071831f, 0.208251f, -0.444353f, 0.106223f, -0.05488f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1764) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1764) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.375f, 0.153f, -0.343f, -0.742f, 0.563f, 0.473f, 0.451f, -0.433f };
int lda = 2;
float B[] = { -0.804f, -0.016f, -0.715f, -0.902f, -0.89f, 0.155f, -0.408f, 0.419f, 0.078f, -0.691f, -0.717f, -0.637f };
int ldb = 2;
float B_expected[] = { -0.0094443f, 0.0821961f, 0.3047f, 0.1991f, 0.347432f, -0.0186595f, 0.0805f, -0.1665f, -0.138523f, 0.381015f, 0.2788f, 0.1194f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1765) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1765) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.867f, -0.597f, -0.577f, 0.735f, 0.827f, -0.104f, -0.861f, -0.802f, -0.288f, 0.293f, 0.593f, 0.228f, -0.469f, 0.942f, 0.193f, 0.591f, 0.241f, 0.382f };
int lda = 3;
float B[] = { -0.812f, -0.874f, -0.18f, -0.81f, 0.023f, 0.352f, 0.559f, 0.237f, -0.835f, 0.037f, -0.762f, 0.782f };
int ldb = 3;
float B_expected[] = { -0.331628f, -0.278177f, -0.0214727f, -0.156013f, -0.0496067f, -0.0088131f, 0.119788f, -0.469291f, -0.0804714f, -0.263663f, -0.0824792f, -0.132356f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1766) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1766) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.258f, -0.812f, -0.858f, -0.107f, -0.151f, 0.785f, 0.717f, 0.992f, -0.649f, -0.242f, -0.454f, 0.916f, 0.86f, 0.834f, -0.244f, 0.391f, 0.818f, -0.714f };
int lda = 3;
float B[] = { 0.163f, 0.441f, 0.54f, 0.679f, 0.071f, -0.76f, 0.345f, -0.956f, 0.654f, -0.217f, -0.892f, 0.106f };
int ldb = 3;
float B_expected[] = { 0.296566f, -0.0905963f, -0.0393822f, -0.306541f, 0.0547f, 0.2351f, -0.0059345f, 0.0071855f, -0.402014f, -0.049978f, 0.257f, -0.121f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1767) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1767) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.525f, 0.182f, 0.851f, -0.348f, -0.046f, 0.839f, -0.045f, -0.149f, -0.992f, 0.588f, -0.01f, -0.409f, 0.527f, 0.263f, -0.509f, -0.026f, 0.284f, 0.507f };
int lda = 3;
float B[] = { 0.909f, 0.216f, 0.38f, 0.198f, -0.412f, -0.102f, -0.456f, 0.079f, 0.504f, -0.782f, -0.88f, 0.079f };
int ldb = 3;
float B_expected[] = { -0.149757f, 0.0672651f, 0.129501f, 0.054878f, -0.0469462f, 0.0277224f, 0.0550599f, -0.0598423f, 0.244521f, -0.217471f, 0.0955519f, -0.37895f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1768) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1768) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.893f, -0.758f, 0.145f, 0.623f, -0.018f, -0.733f, -0.144f, -0.192f, 0.53f, 0.773f, -0.771f, 0.36f, 0.932f, -0.771f, 0.997f, -0.671f, 0.574f, -0.771f };
int lda = 3;
float B[] = { 0.592f, 0.985f, -0.62f, -0.095f, -0.344f, -0.607f, 0.759f, 0.085f, -0.609f, 0.068f, -0.084f, -0.575f };
int ldb = 3;
float B_expected[] = { -0.2761f, -0.2363f, 0.280628f, -0.052484f, 0.306154f, -0.187624f, -0.2362f, 0.0504f, 0.200236f, -0.133908f, 0.0536278f, 0.0659354f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1769) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1769) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.503f, -0.057f, -0.581f, -0.77f, -0.907f, -0.843f, 0.56f, -0.554f, 0.054f, 0.988f, 0.868f, -0.627f, 0.645f, -0.246f, -0.958f, 0.66f, 0.956f, 0.99f };
int lda = 3;
float B[] = { 0.282f, -0.442f, 0.564f, -0.691f, -0.743f, 0.113f, -0.395f, 0.312f, -0.167f, -0.568f, 0.508f, 0.912f };
int ldb = 2;
float B_expected[] = { 0.180092f, 0.260648f, -0.045069f, -0.102868f, -0.0964434f, -0.432702f, -0.0404678f, 0.280779f, 0.254359f, 0.0411062f, -0.453454f, 0.0281672f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1770) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1770) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { -0.851f, 0.296f, -0.683f, -0.53f, 0.38f, -0.837f, 0.977f, 0.189f, -0.624f, -0.664f, 0.73f, -0.882f, 0.105f, -0.868f, 0.362f, -0.006f, -0.435f, 0.757f };
int lda = 3;
float B[] = { -0.259f, -0.091f, 0.606f, -0.983f, -0.238f, 0.057f, 0.358f, 0.18f, -0.71f, 0.058f, 0.511f, 0.717f };
int ldb = 2;
float B_expected[] = { 0.241746f, 0.119591f, -0.0907286f, 0.148899f, 0.141237f, -0.0716576f, -0.205866f, -0.078918f, 0.2072f, -0.0884f, -0.225f, -0.164f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1771) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1771) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.956f, 0.972f, 0.771f, 0.187f, 0.948f, 0.303f, -0.854f, 0.123f, 0.704f, 0.152f, 0.347f, 0.595f, -0.865f, 0.75f, -0.041f, -0.572f, 0.749f, 0.216f };
int lda = 3;
float B[] = { -0.821f, -0.098f, 0.347f, -0.639f, 0.314f, -0.009f, -0.725f, 0.45f, 0.536f, 0.801f, 0.431f, 0.936f };
int ldb = 2;
float B_expected[] = { 0.193607f, -0.29931f, 0.18163f, 0.255513f, 0.127098f, -0.0503344f, 0.101243f, 0.0097718f, -0.0060322f, -0.148016f, -0.251411f, -0.0777231f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1772) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1772) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
float alpha[2] = {-0.3f, 0.1f};
float A[] = { 0.78f, -0.205f, 0.073f, -0.859f, 0.568f, -0.599f, -0.947f, -0.514f, 0.835f, 0.176f, 0.27f, -0.617f, 0.171f, -0.074f, 0.939f, -0.469f, -0.471f, 0.25f };
int lda = 3;
float B[] = { -0.279f, 0.16f, -0.495f, 0.658f, 0.071f, 0.557f, -0.116f, 0.095f, -0.104f, 0.503f, -0.775f, -0.03f };
int ldb = 2;
float B_expected[] = { 0.0677f, -0.0759f, 0.0827f, -0.2469f, -0.0068598f, -0.107386f, 0.243424f, 0.0129156f, 0.142748f, -0.254568f, 0.461939f, -0.154419f };
cblas_ctrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], flteps, "ctrmm(case 1773) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], flteps, "ctrmm(case 1773) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.463, 0.033, -0.929, 0.949, 0.864, 0.986, 0.393, 0.885 };
int lda = 2;
double B[] = { -0.321, -0.852, -0.337, -0.175, 0.607, -0.613, 0.688, 0.973, -0.331, -0.35, 0.719, -0.553 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1774) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1774) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.608, -0.393, 0.921, 0.282, -0.857, -0.286, -0.31, -0.057 };
int lda = 2;
double B[] = { -0.548, 0.728, 0.391, -0.506, 0.186, 0.97, -0.435, 0.375, -0.995, -0.496, 0.99, 0.186 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1775) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1775) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.253, 0.969, 0.654, -0.016, -0.774, -0.11, -0.101, -0.287 };
int lda = 2;
double B[] = { -0.34, -0.268, -0.52, 0.021, -0.875, 0.98, 0.255, 0.564, -0.478, -0.818, -0.043, 0.224 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1776) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1776) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.64, -0.222, 0.922, 0.417, -0.724, 0.012, 0.418, 0.39 };
int lda = 2;
double B[] = { 0.619, -0.024, -0.068, 0.219, 0.374, -0.937, 0.79, 0.166, -0.92, 0.753, -0.017, 0.076 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1777) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1777) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.57, 0.987, 0.116, -0.691, -0.603, -0.778, 0.14, -0.073 };
int lda = 2;
double B[] = { 0.421, -0.055, 0.92, 0.664, 0.835, 0.861, -0.392, -0.897, -0.346, 0.516, -0.068, -0.156 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1778) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1778) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.754, 0.904, 0.089, 0.206, 0.974, -0.946, -0.55, -0.675 };
int lda = 2;
double B[] = { -0.42, -0.372, 0.628, 0.148, 0.344, -0.924, -0.802, -0.307, 0.427, 0.116, 0.916, -0.384 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1779) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1779) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.152, -0.898, -0.024, 0.719, 0.992, -0.841, 0.901, 0.202 };
int lda = 2;
double B[] = { 0.243, -0.811, 0.68, 0.118, 0.946, -0.632, 0.729, -0.942, 0.308, 0.507, -0.838, 0.594 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1780) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1780) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.119, -0.849, 0.425, -0.273, -0.918, 0.196, -0.871, -0.39 };
int lda = 2;
double B[] = { 0.709, 0.33, -0.207, 0.012, -0.017, 0.787, -0.385, 0.739, -0.874, 0.188, -0.039, 0.692 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1781) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1781) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.837, -0.603, 0.755, -0.92, 0.892, -0.009, -0.741, 0.271, -0.325, -0.861, 0.902, -0.088, 0.091, 0.256, 0.209, -0.724, 0.28, -0.604 };
int lda = 3;
double B[] = { 0.455, -0.215, -0.668, 0.917, -0.985, 0.477, 0.564, -0.524, -0.202, -0.53, -0.88, -0.688 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1782) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1782) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.991, 0.253, 0.813, 0.497, -0.268, 0.623, 0.82, -0.946, -0.883, 0.333, -0.265, -0.371, 0.131, -0.812, -0.365, 0.45, 0.929, -0.704 };
int lda = 3;
double B[] = { 0.783, -0.756, 0.635, 0.56, 0.434, -0.831, -0.34, -0.531, -0.277, 0.874, 0.986, 0.157 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1783) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1783) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.265, -0.592, -0.721, -0.838, -0.952, 0.115, -0.34, -0.789, -0.265, -0.779, -0.676, 0.048, 0.78, -0.272, -0.651, 0.272, 0.8, -0.693 };
int lda = 3;
double B[] = { -0.609, 0.028, -0.818, 0.289, -0.41, -0.25, -0.917, 0.463, 0.942, 0.692, -0.516, 0.378 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1784) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1784) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.962, 0.945, -0.58, -0.358, -0.769, 0.751, -0.068, -0.321, 0.938, 0.183, -0.17, 0.251, -0.248, -0.092, -0.818, 0.928, -0.059, -0.222 };
int lda = 3;
double B[] = { 0.015, -0.852, -0.565, 0.16, -0.095, 0.073, 0.405, 0.509, 0.082, -0.478, -0.365, 0.824 };
int ldb = 3;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1785) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1785) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.616, 0.669, 0.323, -0.238, 0.153, 0.891, -0.4, 0.996, 0.689, -0.736, -0.259, -0.707, 0.993, 0.13, -0.829, -0.564, -0.09, 0.118 };
int lda = 3;
double B[] = { 0.113, 0.724, 0.148, -0.309, -0.833, -0.791, 0.354, -0.528, 0.313, 0.421, 0.28, 0.371 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1786) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1786) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { 0.957, -0.713, 0.976, 0.183, -0.145, -0.858, -0.497, -0.605, -0.742, 0.686, 0.272, 0.83, -0.606, -0.099, -0.807, 0.767, 0.254, 0.244 };
int lda = 3;
double B[] = { -0.124, -0.19, 0.665, -0.74, 0.505, -0.194, 0.588, -0.421, -0.727, 0.308, -0.802, -0.278 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1787) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1787) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.649, 0.856, 0.969, 0.382, 0.963, 0.567, 0.599, 0.018, -0.924, 0.578, -0.531, -0.091, -0.454, -0.834, 0.97, -0.126, -0.859, 0.879 };
int lda = 3;
double B[] = { 0.35, 0.824, -0.084, 0.662, -0.752, 0.872, 0.129, 0.969, -0.539, 0.907, 0.316, -0.675 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1788) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1788) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 111;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0};
double A[] = { -0.315, -0.459, 0.327, -0.132, -0.283, 0.173, -0.356, -0.427, 0.508, 0.347, -0.804, -0.849, 0.779, 0.673, 0.019, -0.869, 0.999, -0.338 };
int lda = 3;
double B[] = { 0.678, -0.171, 0.136, -0.268, -0.578, -0.431, 0.978, -0.749, 0.333, -0.757, 0.658, 0.456 };
int ldb = 2;
double B_expected[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1789) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1789) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.532, -0.877, 0.308, -0.807, 0.013, 0.891, 0.077, -0.004 };
int lda = 2;
double B[] = { 0.634, -0.969, 0.228, -0.097, 0.419, 0.903, 0.21, 0.313, -0.819, -0.028, 0.574, -0.762 };
int ldb = 3;
double B_expected[] = { 0.004051, -0.1187101, 0.0148352, -0.0206365, 0.0847859, 0.0569023, 0.0786829, -0.0569289, 0.0212752, -0.007123, 0.0120979, 0.0898923 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1790) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1790) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.77, -0.037, -0.021, -0.831, -0.663, -0.241, -0.273, -0.023 };
int lda = 2;
double B[] = { 0.354, -0.95, -0.944, -0.497, 0.741, 0.084, -0.3, 0.023, -0.056, 0.063, -0.117, -0.498 };
int ldb = 3;
double B_expected[] = { 0.095, 0.0354, 0.0497, -0.0944, -0.0084, 0.0741, 0.0251224, -0.1096884, -0.0857901, -0.0449183, 0.1115535, -0.0062757 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1791) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1791) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.623, 0.379, 0.903, -0.378, -0.088, 0.24, -0.964, 0.558 };
int lda = 2;
double B[] = { -0.137, 0.706, 0.457, 0.399, -0.69, -0.7, 0.34, 0.479, 0.539, -0.133, 0.876, -0.347 };
int ldb = 3;
double B_expected[] = { 0.0452313, -0.0327103, -0.006569, -0.0451444, -0.0415366, 0.0701362, 0.0272036, -0.0595042, -0.0428974, -0.0445382, -0.0823316, -0.0650838 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1792) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1792) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.253, 0.657, 0.636, 0.827, -0.107, 0.353, 0.425, -0.365 };
int lda = 2;
double B[] = { -0.402, -0.409, 0.421, -0.333, -0.771, -0.099, 0.697, -0.812, -0.653, 0.823, 0.994, 0.998 };
int ldb = 3;
double B_expected[] = { 0.0076075, -0.0189943, 0.065157, 0.0200352, -0.0145096, -0.1229652, 0.0812, 0.0697, -0.0823, -0.0653, -0.0998, 0.0994 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1793) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1793) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.57, -0.805, -0.66, -0.421, 0.643, -0.534, -0.988, -0.581 };
int lda = 2;
double B[] = { -0.279, -0.253, 0.976, -0.051, 0.294, 0.451, 0.187, -0.177, 0.31, -0.714, -0.104, -0.177 };
int ldb = 2;
double B_expected[] = { -0.0368805, -0.0044635, 0.0530361, -0.1308418, 0.049374, 0.0195475, -0.0199226, 0.0142283, -0.015743, -0.075147, 0.0389342, -0.0182031 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1794) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1794) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.594, 0.273, 0.457, 0.295, 0.434, -0.227, -0.662, 0.623 };
int lda = 2;
double B[] = { -0.582, -0.581, 0.259, -0.833, -0.864, -0.284, 0.965, -0.459, -0.539, -0.551, -0.969, 0.09 };
int ldb = 2;
double B_expected[] = { 0.0581, -0.0582, 0.095304, -0.0125475, 0.0284, -0.0864, 0.0386128, 0.0525556, 0.0551, -0.0539, 0.0026781, -0.1328003 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1795) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1795) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.398, 0.323, 0.31, 0.718, 0.181, 0.665, 0.402, 0.317 };
int lda = 2;
double B[] = { 0.812, -0.244, -0.415, 0.602, 0.901, -0.017, 0.786, -0.119, 0.448, -0.75, 0.851, 0.172 };
int ldb = 2;
double B_expected[] = { -0.0053814, -0.0158898, -0.0110449, -0.0357664, -0.0811715, 0.0693191, -0.0201324, 0.0353695, -0.0510542, 0.0560868, -0.0338911, 0.0287578 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1796) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1796) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.265, -0.578, 0.218, -0.093, -0.172, 0.414, 0.448, 0.696 };
int lda = 2;
double B[] = { 0.02, -0.254, 0.152, 0.304, 0.289, 0.247, 0.705, 0.419, -0.735, 0.788, -0.942, -0.71 };
int ldb = 2;
double B_expected[] = { 0.0201864, 0.0081408, -0.0304, 0.0152, -0.0272777, 0.0481657, -0.0419, 0.0705, -0.0720826, -0.1006386, 0.071, -0.0942 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1797) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1797) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.971, 0.532, 0.175, 0.455, 0.191, 0.493, 0.882, -0.944, 0.358, 0.142, -0.065, 0.632, -0.319, -0.101, 0.578, 0.476, -0.773, 0.912 };
int lda = 3;
double B[] = { 0.018, -0.131, 0.964, -0.467, -0.729, -0.794, 0.874, 0.361, 0.744, -0.958, 0.162, 0.555 };
int ldb = 3;
double B_expected[] = { 0.0271781, 0.0720558, 0.0439416, 0.0960619, 0.0051086, 0.1287645, -0.117224, 0.0980019, 0.0171007, 0.0041098, 0.0281271, -0.0631386 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1798) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1798) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.506, -0.263, -0.994, 0.681, 0.889, -0.5, -0.912, 0.741, -0.329, -0.912, 0.332, -0.001, -0.484, 0.942, -0.728, -0.104, -0.216, 0.679 };
int lda = 3;
double B[] = { 0.562, -0.354, 0.742, -0.177, -0.627, -0.762, 0.476, 0.758, 0.675, -0.504, -0.33, 0.186 };
int ldb = 3;
double B_expected[] = { 0.0036678, -0.0993414, 0.0429357, 0.0533074, 0.0762, -0.0627, -0.2049005, -0.0052096, 0.0441918, 0.0565626, -0.0186, -0.033 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1799) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1799) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.341, -0.27, 0.001, 0.939, 0.714, 0.803, -0.508, -0.331, -0.563, -0.725, -0.902, -0.793, 0.461, 0.127, -0.597, -0.498, 0.394, -0.019 };
int lda = 3;
double B[] = { 0.015, 0.803, 0.497, 0.667, 0.803, 0.775, 0.026, 0.908, 0.535, -0.111, 0.379, -0.036 };
int ldb = 3;
double B_expected[] = { 0.0277873, 0.0211695, 0.1148735, 0.0461937, -0.0016476, 0.0271498, 0.0316648, 0.0236294, 0.0795252, -0.009434, -0.0200342, -0.0329361 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1800) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1800) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.132, 0.903, -0.235, -0.294, -0.09, 0.74, -0.707, -0.855, 0.632, 0.543, -0.558, -0.416, -0.99, -0.088, -0.189, -0.371, -0.844, -0.737 };
int lda = 3;
double B[] = { -0.257, 0.159, 0.689, 0.785, 0.398, -0.128, -0.098, -0.735, -0.307, 0.032, 0.517, 0.049 };
int ldb = 3;
double B_expected[] = { -0.0159, -0.0257, -0.0892322, 0.1006644, 0.0666778, 0.0827436, 0.0735, -0.0098, -0.0635435, -0.0866139, -0.0893123, 0.0619235 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1801) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1801) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.993, 0.709, 0.225, -0.704, -0.396, 0.656, -0.588, -0.085, -0.024, 0.264, -0.988, -0.67, 0.665, -0.165, -0.778, -0.43, 0.71, -0.35 };
int lda = 3;
double B[] = { 0.321, 0.614, 0.058, 0.983, 0.153, -0.647, 0.342, -0.518, -0.071, -0.533, -0.424, 0.283 };
int ldb = 2;
double B_expected[] = { -0.0861992, -0.0396692, -0.155091, -0.1119744, -0.0501124, -0.0006816, -0.0064866, 0.0580106, 0.035358, -0.023696, -0.034933, -0.020199 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1802) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1802) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.034, -0.02, -0.401, -0.892, 0.329, -0.799, -0.018, 0.564, 0.095, 0.965, -0.105, 0.756, -0.583, -0.706, -0.436, -0.145, 0.921, 0.416 };
int lda = 3;
double B[] = { 0.972, 0.157, -0.029, 0.674, 0.914, 0.434, 0.132, -0.116, -0.907, 0.316, -0.423, 0.321 };
int ldb = 2;
double B_expected[] = { -0.1120798, 0.1462649, -0.0862031, 0.0507283, -0.0427739, 0.1355272, 0.0194621, 0.0362973, -0.0316, -0.0907, -0.0321, -0.0423 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1803) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1803) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { -0.195, -0.36, 0.834, -0.505, -0.87, -0.787, 0.997, 0.965, -0.046, -0.591, 0.082, 0.552, 0.414, -0.013, -0.048, -0.766, 0.728, 0.088 };
int lda = 3;
double B[] = { -0.916, -0.162, -0.863, 0.67, -0.079, -0.27, -0.191, 0.995, 0.981, -0.25, -0.149, 0.248 };
int ldb = 2;
double B_expected[] = { -0.036135, 0.01203, -0.018003, 0.0409485, -0.0386581, -0.100169, -0.1061706, 0.0215439, -0.0700412, 0.1548156, -0.0239871, 0.0582902 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1804) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1804) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 112;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 0.1};
double A[] = { 0.553, -0.63, -0.079, 0.351, 0.865, -0.062, 0.165, -0.634, -0.513, 0.216, -0.521, 0.349, 0.54, 0.545, -0.719, -0.306, 0.501, 0.757 };
int lda = 3;
double B[] = { -0.311, 0.088, -0.328, 0.977, 0.659, -0.06, -0.276, 0.872, -0.734, -0.01, -0.668, -0.327 };
int ldb = 2;
double B_expected[] = { -0.0088, -0.0311, -0.0977, -0.0328, 0.0176113, 0.0652681, -0.0679689, -0.0593015, -0.0346653, -0.1319958, 0.0012195, -0.1051678 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1805) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1805) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.993, -0.018, 0.162, -0.222, 0.188, 0.672, -0.675, -0.345 };
int lda = 2;
double B[] = { 0.476, -0.009, 0.725, -0.925, -0.245, 0.308, 0.515, 0.1, -0.072, -0.757, 0.212, 0.571 };
int ldb = 3;
double B_expected[] = { 0.000369, 0.47283, 0.905475, 0.736575, -0.301434, -0.248829, -0.214389, -0.303015, -0.497235, 0.632565, 0.316779, -0.448161 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1806) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1806) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.78, 0.346, -0.663, -0.86, -0.496, -0.154, 0.356, 0.228 };
int lda = 2;
double B[] = { 0.578, 0.492, 0.775, 0.353, 0.198, -0.519, -0.52, -0.677, -0.438, 0.313, 0.941, -0.56 };
int ldb = 3;
double B_expected[] = { -0.492, 0.578, -0.353, 0.775, 0.519, 0.198, 0.506116, -1.326334, -0.745461, -1.255405, 0.045623, 1.256066 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1807) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1807) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.455, 0.442, 0.062, 0.815, 0.03, 0.55, 0.592, -0.487 };
int lda = 2;
double B[] = { -0.451, 0.01, 0.174, -0.775, 0.22, -0.644, 0.858, -0.004, 0.59, -0.395, -0.943, 0.824 };
int ldb = 3;
double B_expected[] = { 0.268128, -0.177245, 0.765883, -0.46293, -0.15311, 0.240362, -0.415478, 0.509884, -0.05349, 0.541645, -0.028567, -0.959544 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1808) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1808) imag");
};
};
};
{
int order = 101;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.268, -0.886, -0.805, 0.875, 0.481, 0.095, -0.057, 0.605 };
int lda = 2;
double B[] = { 0.708, -0.638, 0.408, -0.512, 0.175, 0.181, -0.919, -0.126, 0.708, -0.51, 0.212, 0.114 };
int ldb = 3;
double B_expected[] = { 0.611301, 0.253991, 0.82457, 0.700098, -0.215694, 0.287802, 0.126, -0.919, 0.51, 0.708, -0.114, 0.212 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1809) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1809) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.881, 0.555, 0.774, 0.148, -0.915, 0.336, 0.103, 0.381 };
int lda = 2;
double B[] = { 0.163, 0.963, -0.017, 0.921, 0.809, 0.846, 0.905, -0.43, 0.894, -0.371, -0.988, -0.487 };
int ldb = 2;
double B_expected[] = { -0.757938, 0.678068, 0.834573, 0.523573, -0.296331, 1.182259, 1.435009, -0.526594, 0.823021, 0.581709, -0.365348, -1.229977 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1810) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1810) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.719, -0.513, 0.169, -0.524, 0.352, 0.823, -0.741, -0.355 };
int lda = 2;
double B[] = { 0.717, 0.052, -0.777, 0.277, -0.962, 0.894, 0.905, -0.216, -0.707, 0.016, 0.481, 0.935 };
int ldb = 2;
double B_expected[] = { -0.052, 0.717, 0.294787, -0.48182, -0.894, -0.962, -0.890414, 1.302138, -0.016, -0.707, -1.522493, 0.245304 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1811) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1811) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.501, -0.136, -0.502, 0.669, -0.498, -0.4, -0.518, 0.833 };
int lda = 2;
double B[] = { -0.385, 0.88, 0.726, 0.911, 0.839, 0.573, -0.881, -0.517, -0.861, -0.278, 0.941, 0.822 };
int ldb = 2;
double B_expected[] = { 0.554496, -0.067558, 1.076656, 0.382795, -1.2501, 0.4388, -1.001679, 0.025697, 1.298547, -0.316017, 1.209649, 0.197288 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1812) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1812) imag");
};
};
};
{
int order = 102;
int side = 141;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.049, 0.641, -0.9, 0.246, -0.734, -0.686, 0.76, -0.869 };
int lda = 2;
double B[] = { -0.37, 0.206, -0.731, -0.573, 0.638, -0.417, -0.29, -0.719, 0.107, -0.333, 0.556, 0.124 };
int ldb = 2;
double B_expected[] = { -0.901526, 0.146942, 0.573, -0.731, -0.30144, 0.722126, 0.719, -0.29, 0.581376, -0.362896, -0.124, 0.556 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1813) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1813) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.553, 0.338, 0.229, -0.828, -0.594, -0.036, -0.335, -0.249, 0.083, -0.197, 0.995, 0.85, -0.988, 0.596, -0.254, 0.179, 0.441, -0.859 };
int lda = 3;
double B[] = { -0.058, -0.225, 0.884, 0.348, 0.123, -0.151, 0.891, 0.711, -0.792, 0.552, 0.033, -0.178 };
int ldb = 3;
double B_expected[] = { -0.800945, -0.261458, 0.051763, -0.001149, -0.039066, 0.183952, 0.330423, 0.081423, 0.315368, -0.292945, 0.050151, 0.167455 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1814) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1814) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.257, -0.565, -0.123, 0.129, 0.817, -0.516, -0.613, -0.42, -0.494, 0.122, -0.593, -0.972, -0.695, -0.968, 0.848, -0.2, -0.17, 0.436 };
int lda = 3;
double B[] = { -0.274, 0.105, -0.899, -0.33, -0.318, -0.096, -0.237, 0.327, 0.046, 0.584, -0.459, -0.182 };
int ldb = 3;
double B_expected[] = { -0.019041, -0.416263, 0.582168, -0.617114, 0.096, -0.318, 0.136304, -0.448413, -0.245778, 0.495091, 0.182, -0.459 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1815) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1815) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.127, 0.025, 0.036, 0.612, 0.773, 0.953, 0.074, -0.006, 0.373, 0.292, -0.052, -0.319, -0.878, -0.401, 0.486, -0.493, -0.316, 0.003 };
int lda = 3;
double B[] = { 0.794, -0.666, -0.406, 0.622, -0.512, -0.761, 0.161, -0.137, -0.626, 0.408, 0.536, 0.66 };
int ldb = 3;
double B_expected[] = { -0.064732, -0.117488, -0.306038, 0.092938, -1.247288, -0.774519, -0.013374, -0.023872, -0.325804, -0.101626, 0.135651, -0.759197 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1816) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1816) imag");
};
};
};
{
int order = 101;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.724, -0.423, 0.028, 0.043, 0.812, -0.568, 0.294, -0.375, -0.85, -0.119, -0.338, -0.415, 0.976, 0.507, 0.913, 0.697, 0.323, 0.206 };
int lda = 3;
double B[] = { 0.427, 0.621, -0.212, -0.942, -0.08, 0.416, 0.465, -0.972, -0.529, -0.252, -0.19, 0.073 };
int ldb = 3;
double B_expected[] = { -0.621, 0.427, 0.599301, -0.319337, -0.093325, -0.198531, 0.972, 0.465, 0.363393, -0.02779, 0.97279, -0.887585 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1817) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1817) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.501, -0.632, 0.663, 0.151, -0.523, -0.71, -0.811, 0.8, -0.06, 0.994, -0.962, 0.827, -0.543, 0.719, -0.264, -0.942, 0.365, 0.051 };
int lda = 3;
double B[] = { -0.974, 0.094, -0.533, 0.633, -0.982, -0.383, -0.297, 0.734, -0.092, -0.15, 0.215, -0.232 };
int ldb = 2;
double B_expected[] = { -0.675337, -0.115274, 0.406006, -0.122575, -0.952024, -0.156194, -0.514956, 0.9092, 0.050058, -0.04123, 0.095645, 0.066643 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1818) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1818) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 121;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { 0.669, 0.332, -0.661, 0.611, 0.279, -0.133, -0.033, 0.06, 0.788, -0.407, -0.644, 0.958, 0.247, -0.161, 0.125, -0.184, 0.041, -0.045 };
int lda = 3;
double B[] = { -0.603, 0.88, 0.668, -0.152, 0.082, 0.033, 0.733, -0.557, 0.722, 0.024, -0.754, 0.458 };
int ldb = 2;
double B_expected[] = { -0.996161, -0.429256, 0.185867, 0.350415, -0.168848, 0.167834, 0.638486, 0.554478, -0.024, 0.722, -0.458, -0.754 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1819) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1819) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 131;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.91, 0.05, -0.944, 0.748, -0.712, 0.619, -0.28, -0.906, 0.314, 0.943, -0.719, -0.983, 0.474, -0.115, -0.859, 0.837, 0.364, -0.164 };
int lda = 3;
double B[] = { -0.278, -0.34, 0.584, 0.43, -0.794, -0.465, -0.65, 0.461, 0.24, 0.003, 0.948, -0.778 };
int ldb = 2;
double B_expected[] = { -0.3233, 0.23598, 0.4205, -0.50994, -1.131636, -0.679699, 0.085048, 0.000967, -0.008447, 1.102325, 1.765785, 0.337213 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1820) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1820) imag");
};
};
};
{
int order = 102;
int side = 142;
int uplo = 122;
int trans = 113;
int diag = 132;
int M = 2;
int N = 3;
double alpha[2] = {0, 1};
double A[] = { -0.39, -0.916, 0.257, -0.082, -0.802, 0.215, -0.155, 0.911, -0.099, 0.41, 0.057, 0.105, 0.94, -0.17, -0.714, -0.861, 0.292, -0.231 };
int lda = 3;
double B[] = { -0.453, -0.542, 0.135, 0.518, -0.199, 0.776, 0.784, -0.28, -0.499, -0.377, -0.795, -0.965 };
int ldb = 2;
double B_expected[] = { 0.542, -0.453, -0.518, 0.135, -0.59956, -0.270977, 0.135804, 0.776219, -0.220206, -0.182087, 1.507741, -0.776612 };
cblas_ztrmm(order, side, uplo, trans, diag, M, N, alpha, A, lda, B, ldb);
{
int i;
for (i = 0; i < 6; i++) {
gsl_test_rel(B[2*i], B_expected[2*i], dbleps, "ztrmm(case 1821) real");
gsl_test_rel(B[2*i+1], B_expected[2*i+1], dbleps, "ztrmm(case 1821) imag");
};
};
};
}
| apache-2.0 |
unseenlaser/python-for-android | python3-alpha/ncurses-5.9/ncurses/tinfo/tinfo_driver.c | 50 | 32619 | /****************************************************************************
* Copyright (c) 2008-2009,2010 Free Software Foundation, Inc. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a *
* copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, distribute with modifications, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included *
* in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
* IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
* THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Juergen Pfeifer *
* *
****************************************************************************/
#include <curses.priv.h>
#define CUR ((TERMINAL*)TCB)->type.
#include <tic.h>
#if HAVE_NANOSLEEP
#include <time.h>
#if HAVE_SYS_TIME_H
#include <sys/time.h> /* needed for MacOS X DP3 */
#endif
#endif
#if HAVE_SIZECHANGE
# if !defined(sun) || !TERMIOS
# if HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
# endif
# endif
#endif
MODULE_ID("$Id: tinfo_driver.c,v 1.13 2010/12/20 01:47:09 tom Exp $")
/*
* SCO defines TIOCGSIZE and the corresponding struct. Other systems (SunOS,
* Solaris, IRIX) define TIOCGWINSZ and struct winsize.
*/
#ifdef TIOCGSIZE
# define IOCTL_WINSIZE TIOCGSIZE
# define STRUCT_WINSIZE struct ttysize
# define WINSIZE_ROWS(n) (int)n.ts_lines
# define WINSIZE_COLS(n) (int)n.ts_cols
#else
# ifdef TIOCGWINSZ
# define IOCTL_WINSIZE TIOCGWINSZ
# define STRUCT_WINSIZE struct winsize
# define WINSIZE_ROWS(n) (int)n.ws_row
# define WINSIZE_COLS(n) (int)n.ws_col
# endif
#endif
/*
* These should be screen structure members. They need to be globals for
* historical reasons. So we assign them in start_color() and also in
* set_term()'s screen-switching logic.
*/
#if USE_REENTRANT
NCURSES_EXPORT(int)
NCURSES_PUBLIC_VAR(COLOR_PAIRS) (void)
{
return CURRENT_SCREEN ? CURRENT_SCREEN->_pair_count : -1;
}
NCURSES_EXPORT(int)
NCURSES_PUBLIC_VAR(COLORS) (void)
{
return CURRENT_SCREEN ? CURRENT_SCREEN->_color_count : -1;
}
#else
NCURSES_EXPORT_VAR(int) COLOR_PAIRS = 0;
NCURSES_EXPORT_VAR(int) COLORS = 0;
#endif
#define TCBMAGIC NCDRV_MAGIC(NCDRV_TINFO)
#define AssertTCB() assert(TCB!=0 && TCB->magic==TCBMAGIC)
#define SetSP() assert(TCB->csp!=0); sp = TCB->csp
/*
* This routine needs to do all the work to make curscr look
* like newscr.
*/
static int
drv_doupdate(TERMINAL_CONTROL_BLOCK * TCB)
{
AssertTCB();
return TINFO_DOUPDATE(TCB->csp);
}
#define ret_error(code, fmt, arg) if (errret) {\
*errret = code;\
return(FALSE); \
} else {\
fprintf(stderr, fmt, arg);\
exit(EXIT_FAILURE);\
}
#define ret_error0(code, msg) if (errret) {\
*errret = code;\
return(FALSE);\
} else {\
fprintf(stderr, msg);\
exit(EXIT_FAILURE);\
}
static bool
drv_CanHandle(TERMINAL_CONTROL_BLOCK * TCB, const char *tname, int *errret)
{
bool result = FALSE;
int status;
TERMINAL *termp;
SCREEN *sp;
assert(TCB != 0 && tname != 0);
termp = (TERMINAL *) TCB;
sp = TCB->csp;
TCB->magic = TCBMAGIC;
#if (USE_DATABASE || USE_TERMCAP)
status = _nc_setup_tinfo(tname, &termp->type);
#else
status = TGETENT_NO;
#endif
/* try fallback list if entry on disk */
if (status != TGETENT_YES) {
const TERMTYPE *fallback = _nc_fallback(tname);
if (fallback) {
termp->type = *fallback;
status = TGETENT_YES;
}
}
if (status != TGETENT_YES) {
NCURSES_SP_NAME(del_curterm) (NCURSES_SP_ARGx termp);
if (status == TGETENT_ERR) {
ret_error0(status, "terminals database is inaccessible\n");
} else if (status == TGETENT_NO) {
ret_error(status, "'%s': unknown terminal type.\n", tname);
}
}
result = TRUE;
#if !USE_REENTRANT
strncpy(ttytype, termp->type.term_names, NAMESIZE - 1);
ttytype[NAMESIZE - 1] = '\0';
#endif
if (command_character)
_nc_tinfo_cmdch(termp, *command_character);
if (generic_type) {
ret_error(TGETENT_NO, "'%s': I need something more specific.\n", tname);
}
if (hard_copy) {
ret_error(TGETENT_YES, "'%s': I can't handle hardcopy terminals.\n", tname);
}
return result;
}
static int
drv_dobeepflash(TERMINAL_CONTROL_BLOCK * TCB, bool beepFlag)
{
SCREEN *sp;
int res = ERR;
AssertTCB();
SetSP();
/* FIXME: should make sure that we are not in altchar mode */
if (beepFlag) {
if (bell) {
res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "bell", bell);
NCURSES_SP_NAME(_nc_flush) (sp);
} else if (flash_screen) {
res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
"flash_screen",
flash_screen);
NCURSES_SP_NAME(_nc_flush) (sp);
}
} else {
if (flash_screen) {
res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
"flash_screen",
flash_screen);
NCURSES_SP_NAME(_nc_flush) (sp);
} else if (bell) {
res = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "bell", bell);
NCURSES_SP_NAME(_nc_flush) (sp);
}
}
return res;
}
/*
* SVr4 curses is known to interchange color codes (1,4) and (3,6), possibly
* to maintain compatibility with a pre-ANSI scheme. The same scheme is
* also used in the FreeBSD syscons.
*/
static int
toggled_colors(int c)
{
if (c < 16) {
static const int table[] =
{0, 4, 2, 6, 1, 5, 3, 7,
8, 12, 10, 14, 9, 13, 11, 15};
c = table[c];
}
return c;
}
static int
drv_print(TERMINAL_CONTROL_BLOCK * TCB, char *data, int len)
{
SCREEN *sp;
AssertTCB();
SetSP();
#if NCURSES_EXT_FUNCS
return NCURSES_SP_NAME(mcprint) (TCB->csp, data, len);
#else
return ERR;
#endif
}
static int
drv_defaultcolors(TERMINAL_CONTROL_BLOCK * TCB, int fg, int bg)
{
SCREEN *sp;
int code = ERR;
AssertTCB();
SetSP();
if (sp != 0 && orig_pair && orig_colors && (initialize_pair != 0)) {
#if NCURSES_EXT_FUNCS
sp->_default_color = isDefaultColor(fg) || isDefaultColor(bg);
sp->_has_sgr_39_49 = (NCURSES_SP_NAME(tigetflag) (NCURSES_SP_ARGx
"AX")
== TRUE);
sp->_default_fg = isDefaultColor(fg) ? COLOR_DEFAULT : (fg & C_MASK);
sp->_default_bg = isDefaultColor(bg) ? COLOR_DEFAULT : (bg & C_MASK);
if (sp->_color_pairs != 0) {
bool save = sp->_default_color;
sp->_default_color = TRUE;
NCURSES_SP_NAME(init_pair) (NCURSES_SP_ARGx
0,
(short)fg,
(short)bg);
sp->_default_color = save;
}
#endif
code = OK;
}
return (code);
}
static void
drv_setcolor(TERMINAL_CONTROL_BLOCK * TCB,
bool fore,
int color,
NCURSES_SP_OUTC outc)
{
SCREEN *sp;
AssertTCB();
SetSP();
if (fore) {
if (set_a_foreground) {
TPUTS_TRACE("set_a_foreground");
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
TPARM_1(set_a_foreground, color), 1, outc);
} else {
TPUTS_TRACE("set_foreground");
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
TPARM_1(set_foreground,
toggled_colors(color)), 1, outc);
}
} else {
if (set_a_background) {
TPUTS_TRACE("set_a_background");
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
TPARM_1(set_a_background, color), 1, outc);
} else {
TPUTS_TRACE("set_background");
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
TPARM_1(set_background,
toggled_colors(color)), 1, outc);
}
}
}
static bool
drv_rescol(TERMINAL_CONTROL_BLOCK * TCB)
{
bool result = FALSE;
SCREEN *sp;
AssertTCB();
SetSP();
if (orig_pair != 0) {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "orig_pair", orig_pair);
result = TRUE;
}
return result;
}
static bool
drv_rescolors(TERMINAL_CONTROL_BLOCK * TCB)
{
int result = FALSE;
SCREEN *sp;
AssertTCB();
SetSP();
if (orig_colors != 0) {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "orig_colors", orig_colors);
result = TRUE;
}
return result;
}
static int
drv_size(TERMINAL_CONTROL_BLOCK * TCB, int *linep, int *colp)
{
SCREEN *sp;
bool useEnv = TRUE;
AssertTCB();
sp = TCB->csp; /* can be null here */
if (sp) {
useEnv = sp->_use_env;
} else
useEnv = _nc_prescreen.use_env;
/* figure out the size of the screen */
T(("screen size: terminfo lines = %d columns = %d", lines, columns));
*linep = (int) lines;
*colp = (int) columns;
if (useEnv) {
int value;
#ifdef __EMX__
{
int screendata[2];
_scrsize(screendata);
*colp = screendata[0];
*linep = screendata[1];
T(("EMX screen size: environment LINES = %d COLUMNS = %d",
*linep, *colp));
}
#endif
#if HAVE_SIZECHANGE
/* try asking the OS */
{
TERMINAL *termp = (TERMINAL *) TCB;
if (isatty(termp->Filedes)) {
STRUCT_WINSIZE size;
errno = 0;
do {
if (ioctl(termp->Filedes, IOCTL_WINSIZE, &size) >= 0) {
*linep = ((sp != 0 && sp->_filtered)
? 1
: WINSIZE_ROWS(size));
*colp = WINSIZE_COLS(size);
T(("SYS screen size: environment LINES = %d COLUMNS = %d",
*linep, *colp));
break;
}
} while
(errno == EINTR);
}
}
#endif /* HAVE_SIZECHANGE */
/*
* Finally, look for environment variables.
*
* Solaris lets users override either dimension with an environment
* variable.
*/
if ((value = _nc_getenv_num("LINES")) > 0) {
*linep = value;
T(("screen size: environment LINES = %d", *linep));
}
if ((value = _nc_getenv_num("COLUMNS")) > 0) {
*colp = value;
T(("screen size: environment COLUMNS = %d", *colp));
}
/* if we can't get dynamic info about the size, use static */
if (*linep <= 0) {
*linep = (int) lines;
}
if (*colp <= 0) {
*colp = (int) columns;
}
/* the ultimate fallback, assume fixed 24x80 size */
if (*linep <= 0) {
*linep = 24;
}
if (*colp <= 0) {
*colp = 80;
}
/*
* Put the derived values back in the screen-size caps, so
* tigetnum() and tgetnum() will do the right thing.
*/
lines = (short) (*linep);
columns = (short) (*colp);
}
T(("screen size is %dx%d", *linep, *colp));
return OK;
}
static int
drv_getsize(TERMINAL_CONTROL_BLOCK * TCB, int *l, int *c)
{
AssertTCB();
assert(l != 0 && c != 0);
*l = lines;
*c = columns;
return OK;
}
static int
drv_setsize(TERMINAL_CONTROL_BLOCK * TCB, int l, int c)
{
AssertTCB();
lines = (short) l;
columns = (short) c;
return OK;
}
static int
drv_sgmode(TERMINAL_CONTROL_BLOCK * TCB, bool setFlag, TTY * buf)
{
SCREEN *sp = TCB->csp;
TERMINAL *_term = (TERMINAL *) TCB;
int result = OK;
AssertTCB();
if (setFlag) {
for (;;) {
if (SET_TTY(_term->Filedes, buf) != 0) {
if (errno == EINTR)
continue;
if (errno == ENOTTY) {
if (sp)
sp->_notty = TRUE;
}
result = ERR;
}
break;
}
} else {
for (;;) {
if (GET_TTY(_term->Filedes, buf) != 0) {
if (errno == EINTR)
continue;
result = ERR;
}
break;
}
}
return result;
}
static int
drv_mode(TERMINAL_CONTROL_BLOCK * TCB, bool progFlag, bool defFlag)
{
SCREEN *sp;
TERMINAL *_term = (TERMINAL *) TCB;
int code = ERR;
AssertTCB();
sp = TCB->csp;
if (progFlag) /* prog mode */
{
if (defFlag) {
/* def_prog_mode */
/*
* Turn off the XTABS bit in the tty structure if it was on.
*/
if ((drv_sgmode(TCB, FALSE, &(_term->Nttyb)) == OK)) {
#ifdef TERMIOS
_term->Nttyb.c_oflag &= (unsigned) ~OFLAGS_TABS;
#else
_term->Nttyb.sg_flags &= (unsigned) ~XTABS;
#endif
code = OK;
}
} else {
/* reset_prog_mode */
if (drv_sgmode(TCB, TRUE, &(_term->Nttyb)) == OK) {
if (sp) {
if (sp->_keypad_on)
_nc_keypad(sp, TRUE);
NC_BUFFERED(sp, TRUE);
}
code = OK;
}
}
} else { /* shell mode */
if (defFlag) {
/* def_shell_mode */
/*
* If XTABS was on, remove the tab and backtab capabilities.
*/
if (drv_sgmode(TCB, FALSE, &(_term->Ottyb)) == OK) {
#ifdef TERMIOS
if (_term->Ottyb.c_oflag & OFLAGS_TABS)
tab = back_tab = NULL;
#else
if (_term->Ottyb.sg_flags & XTABS)
tab = back_tab = NULL;
#endif
code = OK;
}
} else {
/* reset_shell_mode */
if (sp) {
_nc_keypad(sp, FALSE);
NCURSES_SP_NAME(_nc_flush) (sp);
NC_BUFFERED(sp, FALSE);
}
code = drv_sgmode(TCB, TRUE, &(_term->Ottyb));
}
}
return (code);
}
static void
drv_wrap(SCREEN *sp)
{
if (sp) {
sp->_mouse_wrap(sp);
NCURSES_SP_NAME(_nc_screen_wrap) (sp);
NCURSES_SP_NAME(_nc_mvcur_wrap) (sp); /* wrap up cursor addressing */
}
}
static void
drv_release(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED)
{
}
# define SGR0_TEST(mode) (mode != 0) && (exit_attribute_mode == 0 || strcmp(mode, exit_attribute_mode))
static void
drv_screen_init(SCREEN *sp)
{
TERMINAL_CONTROL_BLOCK *TCB = TCBOf(sp);
AssertTCB();
/*
* Check for mismatched graphic-rendition capabilities. Most SVr4
* terminfo trees contain entries that have rmul or rmso equated to
* sgr0 (Solaris curses copes with those entries). We do this only
* for curses, since many termcap applications assume that
* smso/rmso and smul/rmul are paired, and will not function
* properly if we remove rmso or rmul. Curses applications
* shouldn't be looking at this detail.
*/
sp->_use_rmso = SGR0_TEST(exit_standout_mode);
sp->_use_rmul = SGR0_TEST(exit_underline_mode);
/*
* Check whether we can optimize scrolling under dumb terminals in
* case we do not have any of these capabilities, scrolling
* optimization will be useless.
*/
sp->_scrolling = ((scroll_forward && scroll_reverse) ||
((parm_rindex ||
parm_insert_line ||
insert_line) &&
(parm_index ||
parm_delete_line ||
delete_line)));
NCURSES_SP_NAME(baudrate) (sp);
NCURSES_SP_NAME(_nc_mvcur_init) (sp);
/* initialize terminal to a sane state */
NCURSES_SP_NAME(_nc_screen_init) (sp);
}
static void
drv_init(TERMINAL_CONTROL_BLOCK * TCB)
{
SCREEN *sp;
TERMINAL *trm;
AssertTCB();
trm = (TERMINAL *) TCB;
sp = TCB->csp;
TCB->info.initcolor = initialize_color;
TCB->info.canchange = can_change;
TCB->info.hascolor = ((VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
&& (((set_foreground != NULL)
&& (set_background != NULL))
|| ((set_a_foreground != NULL)
&& (set_a_background != NULL))
|| set_color_pair)) ? TRUE : FALSE);
TCB->info.caninit = !(exit_ca_mode && non_rev_rmcup);
TCB->info.maxpairs = VALID_NUMERIC(max_pairs) ? max_pairs : 0;
TCB->info.maxcolors = VALID_NUMERIC(max_colors) ? max_colors : 0;
TCB->info.numlabels = VALID_NUMERIC(num_labels) ? num_labels : 0;
TCB->info.labelwidth = VALID_NUMERIC(label_width) ? label_width : 0;
TCB->info.labelheight = VALID_NUMERIC(label_height) ? label_height : 0;
TCB->info.nocolorvideo = VALID_NUMERIC(no_color_video) ? no_color_video
: 0;
TCB->info.tabsize = VALID_NUMERIC(init_tabs) ? (int) init_tabs : 8;
TCB->info.defaultPalette = hue_lightness_saturation ? _nc_hls_palette : _nc_cga_palette;
/*
* If an application calls setupterm() rather than initscr() or
* newterm(), we will not have the def_prog_mode() call in
* _nc_setupscreen(). Do it now anyway, so we can initialize the
* baudrate.
*/
if (isatty(trm->Filedes)) {
TCB->drv->mode(TCB, TRUE, TRUE);
}
}
#define MAX_PALETTE 8
#define InPalette(n) ((n) >= 0 && (n) < MAX_PALETTE)
static void
drv_initpair(TERMINAL_CONTROL_BLOCK * TCB, short pair, short f, short b)
{
SCREEN *sp;
AssertTCB();
SetSP();
if ((initialize_pair != NULL) && InPalette(f) && InPalette(b)) {
const color_t *tp = InfoOf(sp).defaultPalette;
TR(TRACE_ATTRS,
("initializing pair: pair = %d, fg=(%d,%d,%d), bg=(%d,%d,%d)",
pair,
tp[f].red, tp[f].green, tp[f].blue,
tp[b].red, tp[b].green, tp[b].blue));
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
"initialize_pair",
TPARM_7(initialize_pair,
pair,
tp[f].red, tp[f].green, tp[f].blue,
tp[b].red, tp[b].green, tp[b].blue));
}
}
static int
default_fg(SCREEN *sp)
{
#if NCURSES_EXT_FUNCS
return (sp != 0) ? sp->_default_fg : COLOR_WHITE;
#else
return COLOR_WHITE;
#endif
}
static int
default_bg(SCREEN *sp)
{
#if NCURSES_EXT_FUNCS
return sp != 0 ? sp->_default_bg : COLOR_BLACK;
#else
return COLOR_BLACK;
#endif
}
static void
drv_initcolor(TERMINAL_CONTROL_BLOCK * TCB,
short color, short r, short g, short b)
{
SCREEN *sp = TCB->csp;
AssertTCB();
if (initialize_color != NULL) {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
"initialize_color",
TPARM_4(initialize_color, color, r, g, b));
}
}
static void
drv_do_color(TERMINAL_CONTROL_BLOCK * TCB,
short old_pair,
short pair,
bool reverse,
NCURSES_SP_OUTC outc)
{
SCREEN *sp = TCB->csp;
NCURSES_COLOR_T fg = COLOR_DEFAULT;
NCURSES_COLOR_T bg = COLOR_DEFAULT;
NCURSES_COLOR_T old_fg, old_bg;
AssertTCB();
if (sp == 0)
return;
if (pair < 0 || pair >= COLOR_PAIRS) {
return;
} else if (pair != 0) {
if (set_color_pair) {
TPUTS_TRACE("set_color_pair");
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
TPARM_1(set_color_pair, pair), 1, outc);
return;
} else if (sp != 0) {
NCURSES_SP_NAME(pair_content) (NCURSES_SP_ARGx
(short) pair,
&fg,
&bg);
}
}
if (old_pair >= 0
&& sp != 0
&& NCURSES_SP_NAME(pair_content) (NCURSES_SP_ARGx
old_pair,
&old_fg,
&old_bg) !=ERR) {
if ((isDefaultColor(fg) && !isDefaultColor(old_fg))
|| (isDefaultColor(bg) && !isDefaultColor(old_bg))) {
#if NCURSES_EXT_FUNCS
/*
* A minor optimization - but extension. If "AX" is specified in
* the terminal description, treat it as screen's indicator of ECMA
* SGR 39 and SGR 49, and assume the two sequences are independent.
*/
if (sp->_has_sgr_39_49
&& isDefaultColor(old_bg)
&& !isDefaultColor(old_fg)) {
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx "\033[39m", 1, outc);
} else if (sp->_has_sgr_39_49
&& isDefaultColor(old_fg)
&& !isDefaultColor(old_bg)) {
NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx "\033[49m", 1, outc);
} else
#endif
drv_rescol(TCB);
}
} else {
drv_rescol(TCB);
if (old_pair < 0)
return;
}
#if NCURSES_EXT_FUNCS
if (isDefaultColor(fg))
fg = (NCURSES_COLOR_T) default_fg(sp);
if (isDefaultColor(bg))
bg = (NCURSES_COLOR_T) default_bg(sp);
#endif
if (reverse) {
NCURSES_COLOR_T xx = fg;
fg = bg;
bg = xx;
}
TR(TRACE_ATTRS, ("setting colors: pair = %d, fg = %d, bg = %d", pair,
fg, bg));
if (!isDefaultColor(fg)) {
drv_setcolor(TCB, TRUE, fg, outc);
}
if (!isDefaultColor(bg)) {
drv_setcolor(TCB, FALSE, bg, outc);
}
}
#define xterm_kmous "\033[M"
static void
init_xterm_mouse(SCREEN *sp)
{
sp->_mouse_type = M_XTERM;
sp->_mouse_xtermcap = NCURSES_SP_NAME(tigetstr) (NCURSES_SP_ARGx "XM");
if (!VALID_STRING(sp->_mouse_xtermcap))
sp->_mouse_xtermcap = "\033[?1000%?%p1%{1}%=%th%el%;";
}
static void
drv_initmouse(TERMINAL_CONTROL_BLOCK * TCB)
{
SCREEN *sp;
AssertTCB();
SetSP();
/* we know how to recognize mouse events under "xterm" */
if (sp != 0) {
if (key_mouse != 0) {
if (!strcmp(key_mouse, xterm_kmous)
|| strstr(TerminalOf(sp)->type.term_names, "xterm") != 0) {
init_xterm_mouse(sp);
}
} else if (strstr(TerminalOf(sp)->type.term_names, "xterm") != 0) {
if (_nc_add_to_try(&(sp->_keytry), xterm_kmous, KEY_MOUSE) == OK)
init_xterm_mouse(sp);
}
}
}
static int
drv_testmouse(TERMINAL_CONTROL_BLOCK * TCB, int delay)
{
int rc = 0;
SCREEN *sp;
AssertTCB();
SetSP();
#if USE_SYSMOUSE
if ((sp->_mouse_type == M_SYSMOUSE)
&& (sp->_sysmouse_head < sp->_sysmouse_tail)) {
rc = TW_MOUSE;
} else
#endif
{
rc = TCBOf(sp)->drv->twait(TCBOf(sp),
TWAIT_MASK,
delay,
(int *) 0
EVENTLIST_2nd(evl));
#if USE_SYSMOUSE
if ((sp->_mouse_type == M_SYSMOUSE)
&& (sp->_sysmouse_head < sp->_sysmouse_tail)
&& (rc == 0)
&& (errno == EINTR)) {
rc |= TW_MOUSE;
}
#endif
}
return rc;
}
static int
drv_mvcur(TERMINAL_CONTROL_BLOCK * TCB, int yold, int xold, int ynew, int xnew)
{
SCREEN *sp = TCB->csp;
AssertTCB();
return TINFO_MVCUR(sp, yold, xold, ynew, xnew);
}
static void
drv_hwlabel(TERMINAL_CONTROL_BLOCK * TCB, int labnum, char *text)
{
SCREEN *sp = TCB->csp;
AssertTCB();
if (labnum > 0 && labnum <= num_labels) {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx
"plab_norm",
TPARM_2(plab_norm, labnum, text));
}
}
static void
drv_hwlabelOnOff(TERMINAL_CONTROL_BLOCK * TCB, bool OnFlag)
{
SCREEN *sp = TCB->csp;
AssertTCB();
if (OnFlag) {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "label_on", label_on);
} else {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "label_off", label_off);
}
}
static chtype
drv_conattr(TERMINAL_CONTROL_BLOCK * TCB)
{
SCREEN *sp = TCB->csp;
chtype attrs = A_NORMAL;
AssertTCB();
if (enter_alt_charset_mode)
attrs |= A_ALTCHARSET;
if (enter_blink_mode)
attrs |= A_BLINK;
if (enter_bold_mode)
attrs |= A_BOLD;
if (enter_dim_mode)
attrs |= A_DIM;
if (enter_reverse_mode)
attrs |= A_REVERSE;
if (enter_standout_mode)
attrs |= A_STANDOUT;
if (enter_protected_mode)
attrs |= A_PROTECT;
if (enter_secure_mode)
attrs |= A_INVIS;
if (enter_underline_mode)
attrs |= A_UNDERLINE;
if (sp && sp->_coloron)
attrs |= A_COLOR;
return (attrs);
}
static void
drv_setfilter(TERMINAL_CONTROL_BLOCK * TCB)
{
AssertTCB();
clear_screen = 0;
cursor_down = parm_down_cursor = 0;
cursor_address = 0;
cursor_up = parm_up_cursor = 0;
row_address = 0;
cursor_home = carriage_return;
}
static void
drv_initacs(TERMINAL_CONTROL_BLOCK * TCB, chtype *real_map, chtype *fake_map)
{
SCREEN *sp = TCB->csp;
AssertTCB();
assert(sp != 0);
if (ena_acs != NULL) {
NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx "ena_acs", ena_acs);
}
#if NCURSES_EXT_FUNCS
/*
* Linux console "supports" the "PC ROM" character set by the coincidence
* that smpch/rmpch and smacs/rmacs have the same values. ncurses has
* no codepage support (see SCO Merge for an example). Outside of the
* values defined in acsc, there are no definitions for the "PC ROM"
* character set (assumed by some applications to be codepage 437), but we
* allow those applications to use those codepoints.
*
* test/blue.c uses this feature.
*/
#define PCH_KLUDGE(a,b) (a != 0 && b != 0 && !strcmp(a,b))
if (PCH_KLUDGE(enter_pc_charset_mode, enter_alt_charset_mode) &&
PCH_KLUDGE(exit_pc_charset_mode, exit_alt_charset_mode)) {
size_t i;
for (i = 1; i < ACS_LEN; ++i) {
if (real_map[i] == 0) {
real_map[i] = i;
if (real_map != fake_map) {
if (sp != 0)
sp->_screen_acs_map[i] = TRUE;
}
}
}
}
#endif
if (acs_chars != NULL) {
size_t i = 0;
size_t length = strlen(acs_chars);
while (i + 1 < length) {
if (acs_chars[i] != 0 && UChar(acs_chars[i]) < ACS_LEN) {
real_map[UChar(acs_chars[i])] = UChar(acs_chars[i + 1]) | A_ALTCHARSET;
if (sp != 0)
sp->_screen_acs_map[UChar(acs_chars[i])] = TRUE;
}
i += 2;
}
}
#ifdef TRACE
/* Show the equivalent mapping, noting if it does not match the
* given attribute, whether by re-ordering or duplication.
*/
if (USE_TRACEF(TRACE_CALLS)) {
size_t n, m;
char show[ACS_LEN * 2 + 1];
for (n = 1, m = 0; n < ACS_LEN; n++) {
if (real_map[n] != 0) {
show[m++] = (char) n;
show[m++] = (char) ChCharOf(real_map[n]);
}
}
show[m] = 0;
if (acs_chars == NULL || strcmp(acs_chars, show))
_tracef("%s acs_chars %s",
(acs_chars == NULL) ? "NULL" : "READ",
_nc_visbuf(acs_chars));
_tracef("%s acs_chars %s",
(acs_chars == NULL)
? "NULL"
: (strcmp(acs_chars, show)
? "DIFF"
: "SAME"),
_nc_visbuf(show));
_nc_unlock_global(tracef);
}
#endif /* TRACE */
}
#define ENSURE_TINFO(sp) (TCBOf(sp)->drv->isTerminfo)
NCURSES_EXPORT(void)
_nc_cookie_init(SCREEN *sp)
{
bool support_cookies = USE_XMC_SUPPORT;
TERMINAL_CONTROL_BLOCK *TCB = (TERMINAL_CONTROL_BLOCK *) (sp->_term);
if (sp == 0 || !ENSURE_TINFO(sp))
return;
#if USE_XMC_SUPPORT
/*
* If we have no magic-cookie support compiled-in, or if it is suppressed
* in the environment, reset the support-flag.
*/
if (magic_cookie_glitch >= 0) {
if (getenv("NCURSES_NO_MAGIC_COOKIE") != 0) {
support_cookies = FALSE;
}
}
#endif
if (!support_cookies && magic_cookie_glitch >= 0) {
T(("will disable attributes to work w/o magic cookies"));
}
if (magic_cookie_glitch > 0) { /* tvi, wyse */
sp->_xmc_triggers = sp->_ok_attributes & (
A_STANDOUT |
A_UNDERLINE |
A_REVERSE |
A_BLINK |
A_DIM |
A_BOLD |
A_INVIS |
A_PROTECT
);
#if 0
/*
* We "should" treat colors as an attribute. The wyse350 (and its
* clones) appear to be the only ones that have both colors and magic
* cookies.
*/
if (has_colors()) {
sp->_xmc_triggers |= A_COLOR;
}
#endif
sp->_xmc_suppress = sp->_xmc_triggers & (chtype) ~(A_BOLD);
T(("magic cookie attributes %s", _traceattr(sp->_xmc_suppress)));
/*
* Supporting line-drawing may be possible. But make the regular
* video attributes work first.
*/
acs_chars = ABSENT_STRING;
ena_acs = ABSENT_STRING;
enter_alt_charset_mode = ABSENT_STRING;
exit_alt_charset_mode = ABSENT_STRING;
#if USE_XMC_SUPPORT
/*
* To keep the cookie support simple, suppress all of the optimization
* hooks except for clear_screen and the cursor addressing.
*/
if (support_cookies) {
clr_eol = ABSENT_STRING;
clr_eos = ABSENT_STRING;
set_attributes = ABSENT_STRING;
}
#endif
} else if (magic_cookie_glitch == 0) { /* hpterm */
}
/*
* If magic cookies are not supported, cancel the strings that set
* video attributes.
*/
if (!support_cookies && magic_cookie_glitch >= 0) {
magic_cookie_glitch = ABSENT_NUMERIC;
set_attributes = ABSENT_STRING;
enter_blink_mode = ABSENT_STRING;
enter_bold_mode = ABSENT_STRING;
enter_dim_mode = ABSENT_STRING;
enter_reverse_mode = ABSENT_STRING;
enter_standout_mode = ABSENT_STRING;
enter_underline_mode = ABSENT_STRING;
}
/* initialize normal acs before wide, since we use mapping in the latter */
#if !USE_WIDEC_SUPPORT
if (_nc_unicode_locale() && _nc_locale_breaks_acs(sp->_term)) {
acs_chars = NULL;
ena_acs = NULL;
enter_alt_charset_mode = NULL;
exit_alt_charset_mode = NULL;
set_attributes = NULL;
}
#endif
}
static int
drv_twait(TERMINAL_CONTROL_BLOCK * TCB,
int mode,
int milliseconds,
int *timeleft
EVENTLIST_2nd(_nc_eventlist * evl))
{
SCREEN *sp;
AssertTCB();
SetSP();
return _nc_timed_wait(sp, mode, milliseconds, timeleft EVENTLIST_2nd(evl));
}
static int
drv_read(TERMINAL_CONTROL_BLOCK * TCB, int *buf)
{
SCREEN *sp;
unsigned char c2 = 0;
int n;
AssertTCB();
assert(buf);
SetSP();
# if USE_PTHREADS_EINTR
if ((pthread_self) && (pthread_kill) && (pthread_equal))
_nc_globals.read_thread = pthread_self();
# endif
n = read(sp->_ifd, &c2, 1);
#if USE_PTHREADS_EINTR
_nc_globals.read_thread = 0;
#endif
*buf = (int) c2;
return n;
}
static int
drv_nap(TERMINAL_CONTROL_BLOCK * TCB GCC_UNUSED, int ms)
{
#if HAVE_NANOSLEEP
{
struct timespec request, remaining;
request.tv_sec = ms / 1000;
request.tv_nsec = (ms % 1000) * 1000000;
while (nanosleep(&request, &remaining) == -1
&& errno == EINTR) {
request = remaining;
}
}
#else
_nc_timed_wait(0, 0, ms, (int *) 0 EVENTLIST_2nd(0));
#endif
return OK;
}
static int
__nc_putp(SCREEN *sp, const char *name GCC_UNUSED, const char *value)
{
int rc = ERR;
if (value) {
rc = NCURSES_SP_NAME(_nc_putp) (NCURSES_SP_ARGx name, value);
}
return rc;
}
static int
__nc_putp_flush(SCREEN *sp, const char *name, const char *value)
{
int rc = __nc_putp(sp, name, value);
if (rc != ERR) {
NCURSES_SP_NAME(_nc_flush) (sp);
}
return rc;
}
static int
drv_kpad(TERMINAL_CONTROL_BLOCK * TCB, bool flag)
{
int ret = ERR;
SCREEN *sp;
AssertTCB();
sp = TCB->csp;
if (sp) {
if (flag) {
(void) __nc_putp_flush(sp, "keypad_xmit", keypad_xmit);
} else if (!flag && keypad_local) {
(void) __nc_putp_flush(sp, "keypad_local", keypad_local);
}
if (flag && !sp->_tried) {
_nc_init_keytry(sp);
sp->_tried = TRUE;
}
ret = OK;
}
return ret;
}
static int
drv_keyok(TERMINAL_CONTROL_BLOCK * TCB, int c, bool flag)
{
SCREEN *sp;
int code = ERR;
int count = 0;
char *s;
AssertTCB();
SetSP();
if (c >= 0) {
unsigned ch = (unsigned) c;
if (flag) {
while ((s = _nc_expand_try(sp->_key_ok, ch, &count, 0)) != 0
&& _nc_remove_key(&(sp->_key_ok), ch)) {
code = _nc_add_to_try(&(sp->_keytry), s, ch);
free(s);
count = 0;
if (code != OK)
break;
}
} else {
while ((s = _nc_expand_try(sp->_keytry, ch, &count, 0)) != 0
&& _nc_remove_key(&(sp->_keytry), ch)) {
code = _nc_add_to_try(&(sp->_key_ok), s, ch);
free(s);
count = 0;
if (code != OK)
break;
}
}
}
return (code);
}
static bool
drv_kyExist(TERMINAL_CONTROL_BLOCK * TCB, int key)
{
bool res = FALSE;
AssertTCB();
if (TCB->csp)
res = TINFO_HAS_KEY(TCB->csp, key) == 0 ? FALSE : TRUE;
return res;
}
NCURSES_EXPORT_VAR (TERM_DRIVER) _nc_TINFO_DRIVER = {
TRUE,
drv_CanHandle, /* CanHandle */
drv_init, /* init */
drv_release, /* release */
drv_size, /* size */
drv_sgmode, /* sgmode */
drv_conattr, /* conattr */
drv_mvcur, /* hwcur */
drv_mode, /* mode */
drv_rescol, /* rescol */
drv_rescolors, /* rescolors */
drv_setcolor, /* color */
drv_dobeepflash, /* doBeepOrFlash */
drv_initpair, /* initpair */
drv_initcolor, /* initcolor */
drv_do_color, /* docolor */
drv_initmouse, /* initmouse */
drv_testmouse, /* testmouse */
drv_setfilter, /* setfilter */
drv_hwlabel, /* hwlabel */
drv_hwlabelOnOff, /* hwlabelOnOff */
drv_doupdate, /* update */
drv_defaultcolors, /* defaultcolors */
drv_print, /* print */
drv_getsize, /* getsize */
drv_setsize, /* setsize */
drv_initacs, /* initacs */
drv_screen_init, /* scinit */
drv_wrap, /* scexit */
drv_twait, /* twait */
drv_read, /* read */
drv_nap, /* nap */
drv_kpad, /* kpad */
drv_keyok, /* kyOk */
drv_kyExist /* kyExist */
};
| apache-2.0 |
struempelix/mbed | libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/osc/fsl_osc_hal.c | 51 | 7741 | /*
* Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of Freescale Semiconductor, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fsl_osc_hal.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* Code
******************************************************************************/
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_SetExternalRefClkCmd
* Description : Enable/disable the external reference clock
* This function will enable/disable the external reference clock output
* for oscillator - that is the OSCERCLK. This clock will be used by many
* peripherals. It should be enabled at early system init stage to ensure the
* peripherals could select it and use it.
*
*END**************************************************************************/
void OSC_HAL_SetExternalRefClkCmd(uint32_t baseAddr, bool enable)
{
BW_OSC_CR_ERCLKEN(baseAddr, enable);
}
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_GetExternalRefClkCmd
* Description : Get the external reference clock enable setting for osc
* This function will get the external reference clock output enable setting
* for oscillator - that is the OSCERCLK. This clock will be used by many
* peripherals. It should be enabled at early system init stage to ensure the
* peripherals could select it and use it.
*
*END**************************************************************************/
bool OSC_HAL_GetExternalRefClkCmd(uint32_t baseAddr)
{
return (bool)BR_OSC_CR_ERCLKEN(baseAddr);
}
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_SetExternalRefClkInStopModeCmd
* Description : Enable/disable the external ref clock in stop mode
* This function will enable/disable the external reference clock (OSCERCLK)
* when MCU enters Stop mode.
*
*END**************************************************************************/
void OSC_HAL_SetExternalRefClkInStopModeCmd(uint32_t baseAddr, bool enable)
{
BW_OSC_CR_EREFSTEN(baseAddr, enable);
}
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_GetExternalRefClkInStopModeCmd
* Description : Get the external ref clock enable setting for osc in stop mode
* This function will get the external reference clock (OSCERCLK) setting when
* MCU enters Stop mode.
*
*END**************************************************************************/
bool OSC_HAL_GetExternalRefClkInStopModeCmd(uint32_t baseAddr)
{
return (bool)BR_OSC_CR_EREFSTEN(baseAddr);
}
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_SetCapacitorCmd
* Description : Enable/disable the capacitor configuration for oscillator
* This function will enable/disable the specified capacitors configuration for
* oscillator. This should be done in early system level init function call
* based on system configuration.
*
*END**************************************************************************/
void OSC_HAL_SetCapacitorCmd(uint32_t baseAddr,
osc_capacitor_config_t capacitorConfig,
bool enable)
{
if (capacitorConfig == kOscCapacitor2p)
{
BW_OSC_CR_SC2P(baseAddr, enable);
}
else if (capacitorConfig == kOscCapacitor4p)
{
BW_OSC_CR_SC4P(baseAddr, enable);
}
else if (capacitorConfig == kOscCapacitor8p)
{
BW_OSC_CR_SC8P(baseAddr, enable);
}
else if (capacitorConfig == kOscCapacitor16p)
{
BW_OSC_CR_SC16P(baseAddr, enable);
}
}
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_GetCapacitorCmd
* Description : Get the capacitor configuration for specific oscillator
* This function will get the specified capacitors configuration for the
* oscillator.
*
*END**************************************************************************/
bool OSC_HAL_GetCapacitorCmd(uint32_t baseAddr,
osc_capacitor_config_t capacitorConfig)
{
if (capacitorConfig == kOscCapacitor2p)
{
return (bool)BR_OSC_CR_SC2P(baseAddr);
}
else if (capacitorConfig == kOscCapacitor4p)
{
return (bool)BR_OSC_CR_SC4P(baseAddr);
}
else if (capacitorConfig == kOscCapacitor8p)
{
return (bool)BR_OSC_CR_SC8P(baseAddr);
}
else if (capacitorConfig == kOscCapacitor16p)
{
return (bool)BR_OSC_CR_SC16P(baseAddr);
}
return 0;
}
#if FSL_FEATURE_OSC_HAS_EXT_REF_CLOCK_DIVIDER
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_SetExternalRefClkDivCmd
* Description : Set the external reference clock divider setting for osc
* This function will get the external reference clock divider setting
* for oscillator - that is the OSCERCLK. This clock will be used by many
* peripherals.
*
*END**************************************************************************/
void OSC_HAL_SetExternalRefClkDivCmd(uint32_t baseAddr, uint32_t divider)
{
BW_OSC_DIV_ERPS(baseAddr, divider);
}
/*FUNCTION**********************************************************************
*
* Function Name : OSC_HAL_GetExternalRefClkDivCmd
* Description : Get the external reference clock divider setting for osc
* This function will get the external reference clock divider setting
* for oscillator - that is the OSCERCLK. This clock will be used by many
* peripherals.
*
*END**************************************************************************/
uint32_t OSC_HAL_GetExternalRefClkDivCmd(uint32_t baseAddr)
{
return BR_OSC_DIV_ERPS(baseAddr);
}
#endif
/*******************************************************************************
* EOF
******************************************************************************/
| apache-2.0 |
enternoescape/sagetv | third_party/ffmpeg/libavcodec/binkidct.c | 51 | 3361 | /*
* Bink IDCT algorithm
* Copyright (c) 2009 Kostya Shishkov
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Bink IDCT algorithm
*/
#include "dsputil.h"
#define A1 2896 /* (1/sqrt(2))<<12 */
#define A2 2217
#define A3 3784
#define A4 -5352
#define IDCT_TRANSFORM(dest,s0,s1,s2,s3,s4,s5,s6,s7,d0,d1,d2,d3,d4,d5,d6,d7,munge,src) {\
const int a0 = (src)[s0] + (src)[s4]; \
const int a1 = (src)[s0] - (src)[s4]; \
const int a2 = (src)[s2] + (src)[s6]; \
const int a3 = (A1*((src)[s2] - (src)[s6])) >> 11; \
const int a4 = (src)[s5] + (src)[s3]; \
const int a5 = (src)[s5] - (src)[s3]; \
const int a6 = (src)[s1] + (src)[s7]; \
const int a7 = (src)[s1] - (src)[s7]; \
const int b0 = a4 + a6; \
const int b1 = (A3*(a5 + a7)) >> 11; \
const int b2 = ((A4*a5) >> 11) - b0 + b1; \
const int b3 = (A1*(a6 - a4) >> 11) - b2; \
const int b4 = ((A2*a7) >> 11) + b3 - b1; \
(dest)[d0] = munge(a0+a2 +b0); \
(dest)[d1] = munge(a1+a3-a2+b2); \
(dest)[d2] = munge(a1-a3+a2+b3); \
(dest)[d3] = munge(a0-a2 -b4); \
(dest)[d4] = munge(a0-a2 +b4); \
(dest)[d5] = munge(a1-a3+a2-b3); \
(dest)[d6] = munge(a1+a3-a2-b2); \
(dest)[d7] = munge(a0+a2 -b0); \
}
/* end IDCT_TRANSFORM macro */
#define MUNGE_NONE(x) (x)
#define IDCT_COL(dest,src) IDCT_TRANSFORM(dest,0,8,16,24,32,40,48,56,0,8,16,24,32,40,48,56,MUNGE_NONE,src)
#define MUNGE_ROW(x) (((x) + 0x7F)>>8)
#define IDCT_ROW(dest,src) IDCT_TRANSFORM(dest,0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,MUNGE_ROW,src)
static inline void bink_idct_col(DCTELEM *dest, const DCTELEM *src)
{
if ((src[8]|src[16]|src[24]|src[32]|src[40]|src[48]|src[56])==0) {
dest[0] =
dest[8] =
dest[16] =
dest[24] =
dest[32] =
dest[40] =
dest[48] =
dest[56] = src[0];
} else {
IDCT_COL(dest, src);
}
}
void ff_bink_idct_c(DCTELEM *block)
{
int i;
DCTELEM temp[64];
for (i = 0; i < 8; i++)
bink_idct_col(&temp[i], &block[i]);
for (i = 0; i < 8; i++) {
IDCT_ROW( (&block[8*i]), (&temp[8*i]) );
}
}
void ff_bink_idct_add_c(uint8_t *dest, int linesize, DCTELEM *block)
{
int i, j;
ff_bink_idct_c(block);
for (i = 0; i < 8; i++, dest += linesize, block += 8)
for (j = 0; j < 8; j++)
dest[j] += block[j];
}
void ff_bink_idct_put_c(uint8_t *dest, int linesize, DCTELEM *block)
{
int i;
DCTELEM temp[64];
for (i = 0; i < 8; i++)
bink_idct_col(&temp[i], &block[i]);
for (i = 0; i < 8; i++) {
IDCT_ROW( (&dest[i*linesize]), (&temp[8*i]) );
}
}
| apache-2.0 |
JLUCPGROUP/cuda8_sac | cuda8_sac/include/xercesc/util/regx/TokenFactory.cpp | 53 | 7421 | /*
* 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.
*/
/*
* $Id: TokenFactory.cpp 678879 2008-07-22 20:05:05Z amassari $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/TokenFactory.hpp>
#include <xercesc/util/regx/TokenInc.hpp>
#include <xercesc/util/regx/XMLRangeFactory.hpp>
#include <xercesc/util/regx/ASCIIRangeFactory.hpp>
#include <xercesc/util/regx/UnicodeRangeFactory.hpp>
#include <xercesc/util/regx/BlockRangeFactory.hpp>
#include <xercesc/util/regx/RangeTokenMap.hpp>
#include <xercesc/util/regx/RegxDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// TokenFactory: Constructors and Destructor
// ---------------------------------------------------------------------------
TokenFactory::TokenFactory(MemoryManager* const manager) :
fTokens(new (manager) RefVectorOf<Token> (16, true, manager))
, fEmpty(0)
, fLineBegin(0)
, fLineEnd(0)
, fDot(0)
, fMemoryManager(manager)
{
}
TokenFactory::~TokenFactory() {
delete fTokens;
fTokens = 0;
}
// ---------------------------------------------------------------------------
// TokenFactory - Factory methods
// ---------------------------------------------------------------------------
Token* TokenFactory::createToken(const Token::tokType tkType) {
if (tkType == Token::T_EMPTY && fEmpty != 0)
return fEmpty;
Token* tmpTok = new (fMemoryManager) Token(tkType, fMemoryManager);
if (tkType == Token::T_EMPTY) {
fEmpty = tmpTok;
}
fTokens->addElement(tmpTok);
return tmpTok;
}
ParenToken* TokenFactory::createParenthesis(Token* const token,
const int noGroups) {
ParenToken* tmpTok = new (fMemoryManager) ParenToken(Token::T_PAREN, token, noGroups, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
ClosureToken* TokenFactory::createClosure(Token* const token,
bool isNonGreedy) {
ClosureToken* tmpTok = isNonGreedy ? new (fMemoryManager) ClosureToken(Token::T_NONGREEDYCLOSURE, token, fMemoryManager)
: new (fMemoryManager) ClosureToken(Token::T_CLOSURE, token, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
ConcatToken* TokenFactory::createConcat(Token* const token1,
Token* const token2) {
ConcatToken* tmpTok = new (fMemoryManager) ConcatToken(token1, token2, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
UnionToken* TokenFactory::createUnion(const bool isConcat) {
UnionToken* tmpTok = isConcat ? new (fMemoryManager) UnionToken(Token::T_CONCAT, fMemoryManager)
: new (fMemoryManager) UnionToken(Token::T_UNION, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
RangeToken* TokenFactory::createRange(const bool isNegRange){
RangeToken* tmpTok = isNegRange ? new (fMemoryManager) RangeToken(Token::T_NRANGE, fMemoryManager)
: new (fMemoryManager) RangeToken(Token::T_RANGE, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
CharToken* TokenFactory::createChar(const XMLUInt32 ch, const bool isAnchor) {
CharToken* tmpTok = isAnchor ? new (fMemoryManager) CharToken(Token::T_ANCHOR, ch, fMemoryManager)
: new (fMemoryManager) CharToken(Token::T_CHAR, ch, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
StringToken* TokenFactory::createBackReference(const int noRefs) {
StringToken* tmpTok = new (fMemoryManager) StringToken(Token::T_BACKREFERENCE, 0, noRefs, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
StringToken* TokenFactory::createString(const XMLCh* const literal) {
StringToken* tmpTok = new (fMemoryManager) StringToken(Token::T_STRING, literal, 0, fMemoryManager);
fTokens->addElement(tmpTok);
return tmpTok;
}
// ---------------------------------------------------------------------------
// TokenFactory - Getter methods
// ---------------------------------------------------------------------------
RangeToken* TokenFactory::staticGetRange(const XMLCh* const keyword,
const bool complement) {
return RangeTokenMap::instance()->getRange(keyword, complement);
}
Token* TokenFactory::getLineBegin() {
if (fLineBegin == 0)
fLineBegin = createChar(chCaret, true);
return fLineBegin;
}
Token* TokenFactory::getLineEnd() {
if (fLineEnd == 0)
fLineEnd = createChar(chDollarSign, true);
return fLineEnd;
}
Token* TokenFactory::getDot() {
if (fDot == 0)
fDot = createToken(Token::T_DOT);
return fDot;
}
/*
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if XERCES_USE_TRANSCODER_ICU
#include <unicode/uchar.h>
#endif
#include <stdio.h>
void TokenFactory::printUnicode() {
#if XERCES_USE_TRANSCODER_ICU
//
// Write it out to a temp file to be read back into this source later.
//
printf("Printing\n");
//sprintf(msg, "Printing\n");
FILE* outFl = fopen("table.out", "wt+");
fprintf(outFl, "const XMLByte fgUniCharsTable[0x10000] =\n{ ");
for (unsigned int index = 0; index <= 0xFFFF; index += 16)
{
fprintf(outFl
, " , 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X\n"
, (unsigned int)u_charType(index)
, (unsigned int)u_charType(index+1)
, (unsigned int)u_charType(index+2)
, (unsigned int)u_charType(index+3)
, (unsigned int)u_charType(index+4)
, (unsigned int)u_charType(index+5)
, (unsigned int)u_charType(index+6)
, (unsigned int)u_charType(index+7)
, (unsigned int)u_charType(index+8)
, (unsigned int)u_charType(index+9)
, (unsigned int)u_charType(index+10)
, (unsigned int)u_charType(index+11)
, (unsigned int)u_charType(index+12)
, (unsigned int)u_charType(index+13)
, (unsigned int)u_charType(index+14)
, (unsigned int)u_charType(index+15));
}
fprintf(outFl, "};\n");
fclose(outFl);
#endif
}
*/
XERCES_CPP_NAMESPACE_END
/**
* End of file TokenFactory.cpp
*/
| apache-2.0 |
Willem23/mbed | libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F3/stm32f3xx_hal_gpio.c | 56 | 20007 | /**
******************************************************************************
* @file stm32f3xx_hal_gpio.c
* @author MCD Application Team
* @version V1.1.0
* @date 12-Sept-2014
* @brief GPIO HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the General Purpose Input/Output (GPIO) peripheral:
* + Initialization/de-initialization functions
* + IO operation functions
*
@verbatim
==============================================================================
##### GPIO specific features #####
==============================================================================
[..]
Each port bit of the general-purpose I/O (GPIO) ports can be individually
configured by software in several modes:
(+) Input mode
(+) Analog mode
(+) Output mode
(+) Alternate function mode
(+) External interrupt/event lines
[..]
During and just after reset, the alternate functions and external interrupt
lines are not active and the I/O ports are configured in input floating mode.
[..]
All GPIO pins have weak internal pull-up and pull-down resistors, which can be
activated or not.
[..]
In Output or Alternate mode, each IO can be configured on open-drain or push-pull
type and the IO speed can be selected depending on the VDD value.
[..]
The microcontroller IO pins are connected to onboard peripherals/modules through a
multiplexer that allows only one peripherals alternate function (AF) connected
to an IO pin at a time. In this way, there can be no conflict between peripherals
sharing the same IO pin.
[..]
All ports have external interrupt/event capability. To use external interrupt
lines, the port must be configured in input mode. All available GPIO pins are
connected to the 16 external interrupt/event lines from EXTI0 to EXTI15.
[..]
The external interrupt/event controller consists of up to 23 edge detectors
(16 lines are connected to GPIO) for generating event/interrupt requests (each
input line can be independently configured to select the type (interrupt or event)
and the corresponding trigger event (rising or falling or both). Each line can
also be masked independently.
##### How to use this driver #####
==============================================================================
[..]
(#) Enable the GPIO AHB clock using the following function : __GPIOx_CLK_ENABLE().
(#) Configure the GPIO pin(s) using HAL_GPIO_Init().
(++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure
(++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef
structure.
(++) In case of Output or alternate function mode selection: the speed is
configured through "Speed" member from GPIO_InitTypeDef structure,
the speed is configurable: 2 MHz, 10 MHz and 50 MHz.
(++) If alternate mode is selected, the alternate function connected to the IO
is configured through "Alternate" member from GPIO_InitTypeDef structure
(++) Analog mode is required when a pin is to be used as ADC channel
or DAC output.
(++) In case of external interrupt/event selection the "Mode" member from
GPIO_InitTypeDef structure select the type (interrupt or event) and
the corresponding trigger event (rising or falling or both).
(#) In case of external interrupt/event mode selection, configure NVIC IRQ priority
mapped to the EXTI line using HAL_NVIC_SetPriority() and enable it using
HAL_NVIC_EnableIRQ().
(#) To get the level of a pin configured in input mode use HAL_GPIO_ReadPin().
(#) To set/reset the level of a pin configured in output mode use
HAL_GPIO_WritePin()/HAL_GPIO_TogglePin().
(#) To lock pin configuration until next reset use HAL_GPIO_LockPin().
(#) During and just after reset, the alternate functions are not
active and the GPIO pins are configured in input floating mode (except JTAG
pins).
(#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose
(PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has
priority over the GPIO function.
(#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as
general purpose Px0 and Px1, respectively, when the HSE oscillator is off.
The HSE has priority over the GPIO function.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* 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 "stm32f3xx_hal.h"
/** @addtogroup STM32F3xx_HAL_Driver
* @{
*/
/** @defgroup GPIO GPIO HAL module driver
* @brief GPIO HAL module driver
* @{
*/
#ifdef HAL_GPIO_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/** @defgroup GPIO_Private_Macros GPIO Private Macros
* @{
*/
#define GET_GPIO_SOURCE(__GPIOx__) \
(((uint32_t)(__GPIOx__) == ((uint32_t)GPIOA_BASE))? 0U :\
((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0400)))? 1U :\
((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0800)))? 2U :\
((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0C00)))? 3U :\
((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1000)))? 4U :\
((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1400)))? 5U : 6U)
#define GPIO_MODE ((uint32_t)0x00000003)
#define EXTI_MODE ((uint32_t)0x10000000)
#define GPIO_MODE_IT ((uint32_t)0x00010000)
#define GPIO_MODE_EVT ((uint32_t)0x00020000)
#define RISING_EDGE ((uint32_t)0x00100000)
#define FALLING_EDGE ((uint32_t)0x00200000)
#define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010)
#define GPIO_NUMBER ((uint32_t)16)
/**
* @}
*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup GPIO_Exported_Functions GPIO Exported Functions
* @{
*/
/** @defgroup GPIO_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init.
* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F3 family devices
* @param GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains
* the configuration information for the specified GPIO peripheral.
* @retval None
*/
void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
{
uint32_t position;
uint32_t ioposition = 0x00;
uint32_t iocurrent = 0x00;
uint32_t temp = 0x00;
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
/* Configure the port pins */
for (position = 0; position < GPIO_NUMBER; position++)
{
/* Get the IO position */
ioposition = ((uint32_t)0x01) << position;
/* Get the current IO position */
iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition;
if (iocurrent == ioposition)
{
/*--------------------- GPIO Mode Configuration ------------------------*/
/* In case of Alternate function mode selection */
if((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD))
{
/* Check the Alternate function parameter */
assert_param(IS_GPIO_AF(GPIO_Init->Alternate));
/* Configure Alternate function mapped with the current IO */
temp = GPIOx->AFR[position >> 3];
temp &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ;
temp |= ((uint32_t)(GPIO_Init->Alternate) << (((uint32_t)position & (uint32_t)0x07) * 4));
GPIOx->AFR[position >> 3] = temp;
}
/* Configure IO Direction mode (Input, Output, Alternate or Analog) */
temp = GPIOx->MODER;
temp &= ~(GPIO_MODER_MODER0 << (position * 2));
temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2));
GPIOx->MODER = temp;
/* In case of Output or Alternate function mode selection */
if ((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) ||
(GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD))
{
/* Check the Speed parameter */
assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
/* Configure the IO Speed */
temp = GPIOx->OSPEEDR;
temp &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2));
temp |= (GPIO_Init->Speed << (position * 2));
GPIOx->OSPEEDR = temp;
/* Configure the IO Output Type */
temp = GPIOx->OTYPER;
temp &= ~(GPIO_OTYPER_OT_0 << position) ;
temp |= (((GPIO_Init->Mode & GPIO_OUTPUT_TYPE) >> 4) << position);
GPIOx->OTYPER = temp;
}
/* Activate the Pull-up or Pull down resistor for the current IO */
temp = GPIOx->PUPDR;
temp &= ~(GPIO_PUPDR_PUPDR0 << (position * 2));
temp |= ((GPIO_Init->Pull) << (position * 2));
GPIOx->PUPDR = temp;
/*--------------------- EXTI Mode Configuration ------------------------*/
/* Configure the External Interrupt or event for the current IO */
if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
{
/* Enable SYSCFG Clock */
__SYSCFG_CLK_ENABLE();
temp = SYSCFG->EXTICR[position >> 2];
temp &= ~(((uint32_t)0x0F) << (4 * (position & 0x03)));
temp |= ((uint32_t)(GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03)));
SYSCFG->EXTICR[position >> 2] = temp;
/* Clear EXTI line configuration */
temp = EXTI->IMR;
temp &= ~((uint32_t)iocurrent);
if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
{
temp |= iocurrent;
}
EXTI->IMR = temp;
temp = EXTI->EMR;
temp &= ~((uint32_t)iocurrent);
if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
{
temp |= iocurrent;
}
EXTI->EMR = temp;
/* Clear Rising Falling edge configuration */
temp = EXTI->RTSR;
temp &= ~((uint32_t)iocurrent);
if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
{
temp |= iocurrent;
}
EXTI->RTSR = temp;
temp = EXTI->FTSR;
temp &= ~((uint32_t)iocurrent);
if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
{
temp |= iocurrent;
}
EXTI->FTSR = temp;
}
}
}
}
/**
* @brief De-initializes the GPIOx peripheral registers to their default reset values.
* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F30X device or STM32F37X device
* @param GPIO_Pin: specifies the port bit to be written.
* This parameter can be one of GPIO_PIN_x where x can be (0..15).
* @retval None
*/
void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin)
{
uint32_t position;
uint32_t ioposition = 0x00;
uint32_t iocurrent = 0x00;
uint32_t tmp = 0x00;
/* Configure the port pins */
for (position = 0; position < GPIO_NUMBER; position++)
{
/* Get the IO position */
ioposition = ((uint32_t)0x01) << position;
/* Get the current IO position */
iocurrent = (GPIO_Pin) & ioposition;
if (iocurrent == ioposition)
{
/*------------------------- GPIO Mode Configuration --------------------*/
/* Configure IO Direction in Input Floting Mode */
GPIOx->MODER &= ~(GPIO_MODER_MODER0 << (position * 2));
/* Configure the default Alternate Function in current IO */
GPIOx->AFR[position >> 3] &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ;
/* Configure the default value for IO Speed */
GPIOx->OSPEEDR &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2));
/* Configure the default value IO Output Type */
GPIOx->OTYPER &= ~(GPIO_OTYPER_OT_0 << position) ;
/* Deactivate the Pull-up oand Pull-down resistor for the current IO */
GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPDR0 << (position * 2));
/*------------------------- EXTI Mode Configuration --------------------*/
/* Configure the External Interrupt or event for the current IO */
tmp = ((uint32_t)0x0F) << (4 * (position & 0x03));
SYSCFG->EXTICR[position >> 2] &= ~tmp;
/* Clear EXTI line configuration */
EXTI->IMR &= ~((uint32_t)iocurrent);
EXTI->EMR &= ~((uint32_t)iocurrent);
/* Clear Rising Falling edge configuration */
EXTI->RTSR &= ~((uint32_t)iocurrent);
EXTI->FTSR &= ~((uint32_t)iocurrent);
}
}
}
/**
* @}
*/
/** @defgroup GPIO_Exported_Functions_Group2 Input and Output operation functions
* @brief GPIO Read and Write
*
@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
@endverbatim
* @{
*/
/**
* @brief Reads the specified input port pin.
* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F3 family
* @param GPIO_Pin: specifies the port bit to read.
* This parameter can be GPIO_PIN_x where x can be (0..15).
* @retval The input port pin value.
*/
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
GPIO_PinState bitstatus;
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
{
bitstatus = GPIO_PIN_SET;
}
else
{
bitstatus = GPIO_PIN_RESET;
}
return bitstatus;
}
/**
* @brief Sets or clears the selected data port bit.
*
* @note This function uses GPIOx_BSRR register to allow atomic read/modify
* accesses. In this way, there is no risk of an IRQ occurring between
* the read and the modify access.
*
* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F3 family
* @param GPIO_Pin: specifies the port bit to be written.
* This parameter can be one of GPIO_PIN_x where x can be (0..15).
* @param PinState: specifies the value to be written to the selected bit.
* This parameter can be one of the GPIO_PinState enum values:
* @arg GPIO_PIN_RESET: to clear the port pin
* @arg GPIO_PIN_SET: to set the port pin
* @retval None
*/
void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
{
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
assert_param(IS_GPIO_PIN_ACTION(PinState));
if (PinState != GPIO_PIN_RESET)
{
GPIOx->BSRRL = GPIO_Pin;
}
else
{
GPIOx->BSRRH = GPIO_Pin ;
}
}
/**
* @brief Toggles the specified GPIO pin
* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F3 family
* @param GPIO_Pin: specifies the pins to be toggled.
* @retval None
*/
void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
GPIOx->ODR ^= GPIO_Pin;
}
/**
* @brief Locks GPIO Pins configuration registers.
* @note The locked registers are GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR,
* GPIOx_PUPDR, GPIOx_AFRL and GPIOx_AFRH.
* @note The configuration of the locked GPIO pins can no longer be modified
* until the next reset.
* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F3 family
* @param GPIO_Pin: specifies the port bit to be locked.
* This parameter can be any combination of GPIO_Pin_x where x can be (0..15).
* @retval None
*/
HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
__IO uint32_t tmp = GPIO_LCKR_LCKK;
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
/* Apply lock key write sequence */
tmp |= GPIO_Pin;
/* Set LCKx bit(s): LCKK='1' + LCK[15-0] */
GPIOx->LCKR = tmp;
/* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */
GPIOx->LCKR = GPIO_Pin;
/* Set LCKx bit(s): LCKK='1' + LCK[15-0] */
GPIOx->LCKR = tmp;
/* Read LCKK bit*/
tmp = GPIOx->LCKR;
if((GPIOx->LCKR & GPIO_LCKR_LCKK) != RESET)
{
return HAL_OK;
}
else
{
return HAL_ERROR;
}
}
/**
* @brief This function handles EXTI interrupt request.
* @param GPIO_Pin: Specifies the pins connected EXTI line
* @retval None
*/
void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin)
{
/* EXTI line interrupt detected */
if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET)
{
__HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
HAL_GPIO_EXTI_Callback(GPIO_Pin);
}
}
/**
* @brief EXTI line detection callbacks.
* @param GPIO_Pin: Specifies the pins connected EXTI line
* @retval None
*/
__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_GPIO_EXTI_Callback could be implemented in the user file
*/
}
/**
* @}
*/
/**
* @}
*/
#endif /* HAL_GPIO_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| apache-2.0 |
jmanday/Master | TFM/library/boost_1_63_0/libs/thread/test/sync/mutual_exclusion/locks/unique_lock/locking/try_lock_until_pass.cpp | 57 | 2308 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Copyright (C) 2011 Vicente J. Botet Escriba
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// <boost/thread/locks.hpp>
// template <class Mutex> class unique_lock;
// template <class Clock, class Duration>
// bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
#include <boost/thread/lock_types.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/detail/lightweight_test.hpp>
#if defined BOOST_THREAD_USES_CHRONO
bool try_lock_until_called = false;
struct mutex
{
template <class Clock, class Duration>
bool try_lock_until(const boost::chrono::time_point<Clock, Duration>& abs_time)
{
typedef boost::chrono::milliseconds ms;
BOOST_TEST(Clock::now() - abs_time < ms(5));
try_lock_until_called = !try_lock_until_called;
return try_lock_until_called;
}
void unlock()
{
}
};
mutex m;
int main()
{
typedef boost::chrono::steady_clock Clock;
boost::unique_lock<mutex> lk(m, boost::defer_lock);
BOOST_TEST(lk.try_lock_until(Clock::now()) == true);
BOOST_TEST(try_lock_until_called == true);
BOOST_TEST(lk.owns_lock() == true);
try
{
lk.try_lock_until(Clock::now());
BOOST_TEST(false);
}
catch (boost::system::system_error& e)
{
BOOST_TEST(e.code().value() == boost::system::errc::resource_deadlock_would_occur);
}
lk.unlock();
BOOST_TEST(lk.try_lock_until(Clock::now()) == false);
BOOST_TEST(try_lock_until_called == false);
BOOST_TEST(lk.owns_lock() == false);
lk.release();
try
{
lk.try_lock_until(Clock::now());
BOOST_TEST(false);
}
catch (boost::system::system_error& e)
{
BOOST_TEST(e.code().value() == boost::system::errc::operation_not_permitted);
}
return boost::report_errors();
}
#else
#error "Test not applicable: BOOST_THREAD_USES_CHRONO not defined for this platform as not supported"
#endif
| apache-2.0 |
151706061/DCMTK-ITK | Modules/ThirdParty/VNL/src/vxl/v3p/netlib/lapack/double/dlarfb.f | 59 | 17611 | SUBROUTINE DLARFB( SIDE, TRANS, DIRECT, STOREV, M, N, K, V, LDV,
$ T, LDT, C, LDC, WORK, LDWORK )
*
* -- LAPACK auxiliary routine (version 3.0) --
* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
* Courant Institute, Argonne National Lab, and Rice University
* February 29, 1992
*
* .. Scalar Arguments ..
CHARACTER DIRECT, SIDE, STOREV, TRANS
INTEGER K, LDC, LDT, LDV, LDWORK, M, N
* ..
* .. Array Arguments ..
DOUBLE PRECISION C( LDC, * ), T( LDT, * ), V( LDV, * ),
$ WORK( LDWORK, * )
* ..
*
* Purpose
* =======
*
* DLARFB applies a real block reflector H or its transpose H' to a
* real m by n matrix C, from either the left or the right.
*
* Arguments
* =========
*
* SIDE (input) CHARACTER*1
* = 'L': apply H or H' from the Left
* = 'R': apply H or H' from the Right
*
* TRANS (input) CHARACTER*1
* = 'N': apply H (No transpose)
* = 'T': apply H' (Transpose)
*
* DIRECT (input) CHARACTER*1
* Indicates how H is formed from a product of elementary
* reflectors
* = 'F': H = H(1) H(2) . . . H(k) (Forward)
* = 'B': H = H(k) . . . H(2) H(1) (Backward)
*
* STOREV (input) CHARACTER*1
* Indicates how the vectors which define the elementary
* reflectors are stored:
* = 'C': Columnwise
* = 'R': Rowwise
*
* M (input) INTEGER
* The number of rows of the matrix C.
*
* N (input) INTEGER
* The number of columns of the matrix C.
*
* K (input) INTEGER
* The order of the matrix T (= the number of elementary
* reflectors whose product defines the block reflector).
*
* V (input) DOUBLE PRECISION array, dimension
* (LDV,K) if STOREV = 'C'
* (LDV,M) if STOREV = 'R' and SIDE = 'L'
* (LDV,N) if STOREV = 'R' and SIDE = 'R'
* The matrix V. See further details.
*
* LDV (input) INTEGER
* The leading dimension of the array V.
* If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M);
* if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N);
* if STOREV = 'R', LDV >= K.
*
* T (input) DOUBLE PRECISION array, dimension (LDT,K)
* The triangular k by k matrix T in the representation of the
* block reflector.
*
* LDT (input) INTEGER
* The leading dimension of the array T. LDT >= K.
*
* C (input/output) DOUBLE PRECISION array, dimension (LDC,N)
* On entry, the m by n matrix C.
* On exit, C is overwritten by H*C or H'*C or C*H or C*H'.
*
* LDC (input) INTEGER
* The leading dimension of the array C. LDA >= max(1,M).
*
* WORK (workspace) DOUBLE PRECISION array, dimension (LDWORK,K)
*
* LDWORK (input) INTEGER
* The leading dimension of the array WORK.
* If SIDE = 'L', LDWORK >= max(1,N);
* if SIDE = 'R', LDWORK >= max(1,M).
*
* =====================================================================
*
* .. Parameters ..
DOUBLE PRECISION ONE
PARAMETER ( ONE = 1.0D+0 )
* ..
* .. Local Scalars ..
CHARACTER TRANST
INTEGER I, J
* ..
* .. External Functions ..
LOGICAL LSAME
EXTERNAL LSAME
* ..
* .. External Subroutines ..
EXTERNAL DCOPY, DGEMM, DTRMM
* ..
* .. Executable Statements ..
*
* Quick return if possible
*
IF( M.LE.0 .OR. N.LE.0 )
$ RETURN
*
IF( LSAME( TRANS, 'N' ) ) THEN
TRANST = 'T'
ELSE
TRANST = 'N'
END IF
*
IF( LSAME( STOREV, 'C' ) ) THEN
*
IF( LSAME( DIRECT, 'F' ) ) THEN
*
* Let V = ( V1 ) (first K rows)
* ( V2 )
* where V1 is unit lower triangular.
*
IF( LSAME( SIDE, 'L' ) ) THEN
*
* Form H * C or H' * C where C = ( C1 )
* ( C2 )
*
* W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK)
*
* W := C1'
*
DO 10 J = 1, K
CALL DCOPY( N, C( J, 1 ), LDC, WORK( 1, J ), 1 )
10 CONTINUE
*
* W := W * V1
*
CALL DTRMM( 'Right', 'Lower', 'No transpose', 'Unit', N,
$ K, ONE, V, LDV, WORK, LDWORK )
IF( M.GT.K ) THEN
*
* W := W + C2'*V2
*
CALL DGEMM( 'Transpose', 'No transpose', N, K, M-K,
$ ONE, C( K+1, 1 ), LDC, V( K+1, 1 ), LDV,
$ ONE, WORK, LDWORK )
END IF
*
* W := W * T' or W * T
*
CALL DTRMM( 'Right', 'Upper', TRANST, 'Non-unit', N, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - V * W'
*
IF( M.GT.K ) THEN
*
* C2 := C2 - V2 * W'
*
CALL DGEMM( 'No transpose', 'Transpose', M-K, N, K,
$ -ONE, V( K+1, 1 ), LDV, WORK, LDWORK, ONE,
$ C( K+1, 1 ), LDC )
END IF
*
* W := W * V1'
*
CALL DTRMM( 'Right', 'Lower', 'Transpose', 'Unit', N, K,
$ ONE, V, LDV, WORK, LDWORK )
*
* C1 := C1 - W'
*
DO 30 J = 1, K
DO 20 I = 1, N
C( J, I ) = C( J, I ) - WORK( I, J )
20 CONTINUE
30 CONTINUE
*
ELSE IF( LSAME( SIDE, 'R' ) ) THEN
*
* Form C * H or C * H' where C = ( C1 C2 )
*
* W := C * V = (C1*V1 + C2*V2) (stored in WORK)
*
* W := C1
*
DO 40 J = 1, K
CALL DCOPY( M, C( 1, J ), 1, WORK( 1, J ), 1 )
40 CONTINUE
*
* W := W * V1
*
CALL DTRMM( 'Right', 'Lower', 'No transpose', 'Unit', M,
$ K, ONE, V, LDV, WORK, LDWORK )
IF( N.GT.K ) THEN
*
* W := W + C2 * V2
*
CALL DGEMM( 'No transpose', 'No transpose', M, K, N-K,
$ ONE, C( 1, K+1 ), LDC, V( K+1, 1 ), LDV,
$ ONE, WORK, LDWORK )
END IF
*
* W := W * T or W * T'
*
CALL DTRMM( 'Right', 'Upper', TRANS, 'Non-unit', M, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - W * V'
*
IF( N.GT.K ) THEN
*
* C2 := C2 - W * V2'
*
CALL DGEMM( 'No transpose', 'Transpose', M, N-K, K,
$ -ONE, WORK, LDWORK, V( K+1, 1 ), LDV, ONE,
$ C( 1, K+1 ), LDC )
END IF
*
* W := W * V1'
*
CALL DTRMM( 'Right', 'Lower', 'Transpose', 'Unit', M, K,
$ ONE, V, LDV, WORK, LDWORK )
*
* C1 := C1 - W
*
DO 60 J = 1, K
DO 50 I = 1, M
C( I, J ) = C( I, J ) - WORK( I, J )
50 CONTINUE
60 CONTINUE
END IF
*
ELSE
*
* Let V = ( V1 )
* ( V2 ) (last K rows)
* where V2 is unit upper triangular.
*
IF( LSAME( SIDE, 'L' ) ) THEN
*
* Form H * C or H' * C where C = ( C1 )
* ( C2 )
*
* W := C' * V = (C1'*V1 + C2'*V2) (stored in WORK)
*
* W := C2'
*
DO 70 J = 1, K
CALL DCOPY( N, C( M-K+J, 1 ), LDC, WORK( 1, J ), 1 )
70 CONTINUE
*
* W := W * V2
*
CALL DTRMM( 'Right', 'Upper', 'No transpose', 'Unit', N,
$ K, ONE, V( M-K+1, 1 ), LDV, WORK, LDWORK )
IF( M.GT.K ) THEN
*
* W := W + C1'*V1
*
CALL DGEMM( 'Transpose', 'No transpose', N, K, M-K,
$ ONE, C, LDC, V, LDV, ONE, WORK, LDWORK )
END IF
*
* W := W * T' or W * T
*
CALL DTRMM( 'Right', 'Lower', TRANST, 'Non-unit', N, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - V * W'
*
IF( M.GT.K ) THEN
*
* C1 := C1 - V1 * W'
*
CALL DGEMM( 'No transpose', 'Transpose', M-K, N, K,
$ -ONE, V, LDV, WORK, LDWORK, ONE, C, LDC )
END IF
*
* W := W * V2'
*
CALL DTRMM( 'Right', 'Upper', 'Transpose', 'Unit', N, K,
$ ONE, V( M-K+1, 1 ), LDV, WORK, LDWORK )
*
* C2 := C2 - W'
*
DO 90 J = 1, K
DO 80 I = 1, N
C( M-K+J, I ) = C( M-K+J, I ) - WORK( I, J )
80 CONTINUE
90 CONTINUE
*
ELSE IF( LSAME( SIDE, 'R' ) ) THEN
*
* Form C * H or C * H' where C = ( C1 C2 )
*
* W := C * V = (C1*V1 + C2*V2) (stored in WORK)
*
* W := C2
*
DO 100 J = 1, K
CALL DCOPY( M, C( 1, N-K+J ), 1, WORK( 1, J ), 1 )
100 CONTINUE
*
* W := W * V2
*
CALL DTRMM( 'Right', 'Upper', 'No transpose', 'Unit', M,
$ K, ONE, V( N-K+1, 1 ), LDV, WORK, LDWORK )
IF( N.GT.K ) THEN
*
* W := W + C1 * V1
*
CALL DGEMM( 'No transpose', 'No transpose', M, K, N-K,
$ ONE, C, LDC, V, LDV, ONE, WORK, LDWORK )
END IF
*
* W := W * T or W * T'
*
CALL DTRMM( 'Right', 'Lower', TRANS, 'Non-unit', M, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - W * V'
*
IF( N.GT.K ) THEN
*
* C1 := C1 - W * V1'
*
CALL DGEMM( 'No transpose', 'Transpose', M, N-K, K,
$ -ONE, WORK, LDWORK, V, LDV, ONE, C, LDC )
END IF
*
* W := W * V2'
*
CALL DTRMM( 'Right', 'Upper', 'Transpose', 'Unit', M, K,
$ ONE, V( N-K+1, 1 ), LDV, WORK, LDWORK )
*
* C2 := C2 - W
*
DO 120 J = 1, K
DO 110 I = 1, M
C( I, N-K+J ) = C( I, N-K+J ) - WORK( I, J )
110 CONTINUE
120 CONTINUE
END IF
END IF
*
ELSE IF( LSAME( STOREV, 'R' ) ) THEN
*
IF( LSAME( DIRECT, 'F' ) ) THEN
*
* Let V = ( V1 V2 ) (V1: first K columns)
* where V1 is unit upper triangular.
*
IF( LSAME( SIDE, 'L' ) ) THEN
*
* Form H * C or H' * C where C = ( C1 )
* ( C2 )
*
* W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK)
*
* W := C1'
*
DO 130 J = 1, K
CALL DCOPY( N, C( J, 1 ), LDC, WORK( 1, J ), 1 )
130 CONTINUE
*
* W := W * V1'
*
CALL DTRMM( 'Right', 'Upper', 'Transpose', 'Unit', N, K,
$ ONE, V, LDV, WORK, LDWORK )
IF( M.GT.K ) THEN
*
* W := W + C2'*V2'
*
CALL DGEMM( 'Transpose', 'Transpose', N, K, M-K, ONE,
$ C( K+1, 1 ), LDC, V( 1, K+1 ), LDV, ONE,
$ WORK, LDWORK )
END IF
*
* W := W * T' or W * T
*
CALL DTRMM( 'Right', 'Upper', TRANST, 'Non-unit', N, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - V' * W'
*
IF( M.GT.K ) THEN
*
* C2 := C2 - V2' * W'
*
CALL DGEMM( 'Transpose', 'Transpose', M-K, N, K, -ONE,
$ V( 1, K+1 ), LDV, WORK, LDWORK, ONE,
$ C( K+1, 1 ), LDC )
END IF
*
* W := W * V1
*
CALL DTRMM( 'Right', 'Upper', 'No transpose', 'Unit', N,
$ K, ONE, V, LDV, WORK, LDWORK )
*
* C1 := C1 - W'
*
DO 150 J = 1, K
DO 140 I = 1, N
C( J, I ) = C( J, I ) - WORK( I, J )
140 CONTINUE
150 CONTINUE
*
ELSE IF( LSAME( SIDE, 'R' ) ) THEN
*
* Form C * H or C * H' where C = ( C1 C2 )
*
* W := C * V' = (C1*V1' + C2*V2') (stored in WORK)
*
* W := C1
*
DO 160 J = 1, K
CALL DCOPY( M, C( 1, J ), 1, WORK( 1, J ), 1 )
160 CONTINUE
*
* W := W * V1'
*
CALL DTRMM( 'Right', 'Upper', 'Transpose', 'Unit', M, K,
$ ONE, V, LDV, WORK, LDWORK )
IF( N.GT.K ) THEN
*
* W := W + C2 * V2'
*
CALL DGEMM( 'No transpose', 'Transpose', M, K, N-K,
$ ONE, C( 1, K+1 ), LDC, V( 1, K+1 ), LDV,
$ ONE, WORK, LDWORK )
END IF
*
* W := W * T or W * T'
*
CALL DTRMM( 'Right', 'Upper', TRANS, 'Non-unit', M, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - W * V
*
IF( N.GT.K ) THEN
*
* C2 := C2 - W * V2
*
CALL DGEMM( 'No transpose', 'No transpose', M, N-K, K,
$ -ONE, WORK, LDWORK, V( 1, K+1 ), LDV, ONE,
$ C( 1, K+1 ), LDC )
END IF
*
* W := W * V1
*
CALL DTRMM( 'Right', 'Upper', 'No transpose', 'Unit', M,
$ K, ONE, V, LDV, WORK, LDWORK )
*
* C1 := C1 - W
*
DO 180 J = 1, K
DO 170 I = 1, M
C( I, J ) = C( I, J ) - WORK( I, J )
170 CONTINUE
180 CONTINUE
*
END IF
*
ELSE
*
* Let V = ( V1 V2 ) (V2: last K columns)
* where V2 is unit lower triangular.
*
IF( LSAME( SIDE, 'L' ) ) THEN
*
* Form H * C or H' * C where C = ( C1 )
* ( C2 )
*
* W := C' * V' = (C1'*V1' + C2'*V2') (stored in WORK)
*
* W := C2'
*
DO 190 J = 1, K
CALL DCOPY( N, C( M-K+J, 1 ), LDC, WORK( 1, J ), 1 )
190 CONTINUE
*
* W := W * V2'
*
CALL DTRMM( 'Right', 'Lower', 'Transpose', 'Unit', N, K,
$ ONE, V( 1, M-K+1 ), LDV, WORK, LDWORK )
IF( M.GT.K ) THEN
*
* W := W + C1'*V1'
*
CALL DGEMM( 'Transpose', 'Transpose', N, K, M-K, ONE,
$ C, LDC, V, LDV, ONE, WORK, LDWORK )
END IF
*
* W := W * T' or W * T
*
CALL DTRMM( 'Right', 'Lower', TRANST, 'Non-unit', N, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - V' * W'
*
IF( M.GT.K ) THEN
*
* C1 := C1 - V1' * W'
*
CALL DGEMM( 'Transpose', 'Transpose', M-K, N, K, -ONE,
$ V, LDV, WORK, LDWORK, ONE, C, LDC )
END IF
*
* W := W * V2
*
CALL DTRMM( 'Right', 'Lower', 'No transpose', 'Unit', N,
$ K, ONE, V( 1, M-K+1 ), LDV, WORK, LDWORK )
*
* C2 := C2 - W'
*
DO 210 J = 1, K
DO 200 I = 1, N
C( M-K+J, I ) = C( M-K+J, I ) - WORK( I, J )
200 CONTINUE
210 CONTINUE
*
ELSE IF( LSAME( SIDE, 'R' ) ) THEN
*
* Form C * H or C * H' where C = ( C1 C2 )
*
* W := C * V' = (C1*V1' + C2*V2') (stored in WORK)
*
* W := C2
*
DO 220 J = 1, K
CALL DCOPY( M, C( 1, N-K+J ), 1, WORK( 1, J ), 1 )
220 CONTINUE
*
* W := W * V2'
*
CALL DTRMM( 'Right', 'Lower', 'Transpose', 'Unit', M, K,
$ ONE, V( 1, N-K+1 ), LDV, WORK, LDWORK )
IF( N.GT.K ) THEN
*
* W := W + C1 * V1'
*
CALL DGEMM( 'No transpose', 'Transpose', M, K, N-K,
$ ONE, C, LDC, V, LDV, ONE, WORK, LDWORK )
END IF
*
* W := W * T or W * T'
*
CALL DTRMM( 'Right', 'Lower', TRANS, 'Non-unit', M, K,
$ ONE, T, LDT, WORK, LDWORK )
*
* C := C - W * V
*
IF( N.GT.K ) THEN
*
* C1 := C1 - W * V1
*
CALL DGEMM( 'No transpose', 'No transpose', M, N-K, K,
$ -ONE, WORK, LDWORK, V, LDV, ONE, C, LDC )
END IF
*
* W := W * V2
*
CALL DTRMM( 'Right', 'Lower', 'No transpose', 'Unit', M,
$ K, ONE, V( 1, N-K+1 ), LDV, WORK, LDWORK )
*
* C1 := C1 - W
*
DO 240 J = 1, K
DO 230 I = 1, M
C( I, N-K+J ) = C( I, N-K+J ) - WORK( I, J )
230 CONTINUE
240 CONTINUE
*
END IF
*
END IF
END IF
*
RETURN
*
* End of DLARFB
*
END
| apache-2.0 |
coderReview/NTL-ISS-Food-Intake-Tracker | Backend Services/issfit-api/node_modules/pajk-lwip/src/lib/gif/quantize.c | 60 | 13417 | /*****************************************************************************
quantize.c - quantize a high resolution image into lower one
Based on: "Color Image Quantization for frame buffer Display", by
Paul Heckbert SIGGRAPH 1982 page 297-307.
This doesn't really belong in the core library, was undocumented,
and was removed in 4.2. Then it turned out some client apps were
actually using it, so it was restored in 5.0.
******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include "gif_lib.h"
#include "gif_lib_private.h"
#define ABS(x) ((x) > 0 ? (x) : (-(x)))
#define COLOR_ARRAY_SIZE 32768
#define BITS_PER_PRIM_COLOR 5
#define MAX_PRIM_COLOR 0x1f
static int SortRGBAxis;
typedef struct QuantizedColorType {
GifByteType RGB[3];
GifByteType NewColorIndex;
long Count;
struct QuantizedColorType *Pnext;
} QuantizedColorType;
typedef struct NewColorMapType {
GifByteType RGBMin[3], RGBWidth[3];
unsigned int NumEntries; /* # of QuantizedColorType in linked list below */
unsigned long Count; /* Total number of pixels in all the entries */
QuantizedColorType *QuantizedColors;
} NewColorMapType;
static int SubdivColorMap(NewColorMapType * NewColorSubdiv,
unsigned int ColorMapSize,
unsigned int *NewColorMapSize);
static int SortCmpRtn(const void *Entry1, const void *Entry2);
/******************************************************************************
Quantize high resolution image into lower one. Input image consists of a
2D array for each of the RGB colors with size Width by Height. There is no
Color map for the input. Output is a quantized image with 2D array of
indexes into the output color map.
Note input image can be 24 bits at the most (8 for red/green/blue) and
the output has 256 colors at the most (256 entries in the color map.).
ColorMapSize specifies size of color map up to 256 and will be updated to
real size before returning.
Also non of the parameter are allocated by this routine.
This function returns GIF_OK if successful, GIF_ERROR otherwise.
******************************************************************************/
int
GifQuantizeBuffer(unsigned int Width,
unsigned int Height,
int *ColorMapSize,
GifByteType * RedInput,
GifByteType * GreenInput,
GifByteType * BlueInput,
GifByteType * OutputBuffer,
GifColorType * OutputColorMap) {
unsigned int Index, NumOfEntries;
int i, j, MaxRGBError[3];
unsigned int NewColorMapSize;
long Red, Green, Blue;
NewColorMapType NewColorSubdiv[256];
QuantizedColorType *ColorArrayEntries, *QuantizedColor;
ColorArrayEntries = (QuantizedColorType *)malloc(
sizeof(QuantizedColorType) * COLOR_ARRAY_SIZE);
if (ColorArrayEntries == NULL) {
return GIF_ERROR;
}
for (i = 0; i < COLOR_ARRAY_SIZE; i++) {
ColorArrayEntries[i].RGB[0] = i >> (2 * BITS_PER_PRIM_COLOR);
ColorArrayEntries[i].RGB[1] = (i >> BITS_PER_PRIM_COLOR) &
MAX_PRIM_COLOR;
ColorArrayEntries[i].RGB[2] = i & MAX_PRIM_COLOR;
ColorArrayEntries[i].Count = 0;
}
/* Sample the colors and their distribution: */
for (i = 0; i < (int)(Width * Height); i++) {
Index = ((RedInput[i] >> (8 - BITS_PER_PRIM_COLOR)) <<
(2 * BITS_PER_PRIM_COLOR)) +
((GreenInput[i] >> (8 - BITS_PER_PRIM_COLOR)) <<
BITS_PER_PRIM_COLOR) +
(BlueInput[i] >> (8 - BITS_PER_PRIM_COLOR));
ColorArrayEntries[Index].Count++;
}
/* Put all the colors in the first entry of the color map, and call the
* recursive subdivision process. */
for (i = 0; i < 256; i++) {
NewColorSubdiv[i].QuantizedColors = NULL;
NewColorSubdiv[i].Count = NewColorSubdiv[i].NumEntries = 0;
for (j = 0; j < 3; j++) {
NewColorSubdiv[i].RGBMin[j] = 0;
NewColorSubdiv[i].RGBWidth[j] = 255;
}
}
/* Find the non empty entries in the color table and chain them: */
for (i = 0; i < COLOR_ARRAY_SIZE; i++)
if (ColorArrayEntries[i].Count > 0)
break;
QuantizedColor = NewColorSubdiv[0].QuantizedColors = &ColorArrayEntries[i];
NumOfEntries = 1;
while (++i < COLOR_ARRAY_SIZE)
if (ColorArrayEntries[i].Count > 0) {
QuantizedColor->Pnext = &ColorArrayEntries[i];
QuantizedColor = &ColorArrayEntries[i];
NumOfEntries++;
}
QuantizedColor->Pnext = NULL;
NewColorSubdiv[0].NumEntries = NumOfEntries; /* Different sampled colors */
NewColorSubdiv[0].Count = ((long)Width) * Height; /* Pixels */
NewColorMapSize = 1;
if (SubdivColorMap(NewColorSubdiv, *ColorMapSize, &NewColorMapSize) !=
GIF_OK) {
free((char *)ColorArrayEntries);
return GIF_ERROR;
}
if (NewColorMapSize < *ColorMapSize) {
/* And clear rest of color map: */
for (i = NewColorMapSize; i < *ColorMapSize; i++)
OutputColorMap[i].Red = OutputColorMap[i].Green =
OutputColorMap[i].Blue = 0;
}
/* Average the colors in each entry to be the color to be used in the
* output color map, and plug it into the output color map itself. */
for (i = 0; i < NewColorMapSize; i++) {
if ((j = NewColorSubdiv[i].NumEntries) > 0) {
QuantizedColor = NewColorSubdiv[i].QuantizedColors;
Red = Green = Blue = 0;
while (QuantizedColor) {
QuantizedColor->NewColorIndex = i;
Red += QuantizedColor->RGB[0];
Green += QuantizedColor->RGB[1];
Blue += QuantizedColor->RGB[2];
QuantizedColor = QuantizedColor->Pnext;
}
OutputColorMap[i].Red = (Red << (8 - BITS_PER_PRIM_COLOR)) / j;
OutputColorMap[i].Green = (Green << (8 - BITS_PER_PRIM_COLOR)) / j;
OutputColorMap[i].Blue = (Blue << (8 - BITS_PER_PRIM_COLOR)) / j;
}
}
/* Finally scan the input buffer again and put the mapped index in the
* output buffer. */
MaxRGBError[0] = MaxRGBError[1] = MaxRGBError[2] = 0;
for (i = 0; i < (int)(Width * Height); i++) {
Index = ((RedInput[i] >> (8 - BITS_PER_PRIM_COLOR)) <<
(2 * BITS_PER_PRIM_COLOR)) +
((GreenInput[i] >> (8 - BITS_PER_PRIM_COLOR)) <<
BITS_PER_PRIM_COLOR) +
(BlueInput[i] >> (8 - BITS_PER_PRIM_COLOR));
Index = ColorArrayEntries[Index].NewColorIndex;
OutputBuffer[i] = Index;
if (MaxRGBError[0] < ABS(OutputColorMap[Index].Red - RedInput[i]))
MaxRGBError[0] = ABS(OutputColorMap[Index].Red - RedInput[i]);
if (MaxRGBError[1] < ABS(OutputColorMap[Index].Green - GreenInput[i]))
MaxRGBError[1] = ABS(OutputColorMap[Index].Green - GreenInput[i]);
if (MaxRGBError[2] < ABS(OutputColorMap[Index].Blue - BlueInput[i]))
MaxRGBError[2] = ABS(OutputColorMap[Index].Blue - BlueInput[i]);
}
#ifdef DEBUG
fprintf(stderr,
"Quantization L(0) errors: Red = %d, Green = %d, Blue = %d.\n",
MaxRGBError[0], MaxRGBError[1], MaxRGBError[2]);
#endif /* DEBUG */
free((char *)ColorArrayEntries);
*ColorMapSize = NewColorMapSize;
return GIF_OK;
}
/******************************************************************************
Routine to subdivide the RGB space recursively using median cut in each
axes alternatingly until ColorMapSize different cubes exists.
The biggest cube in one dimension is subdivide unless it has only one entry.
Returns GIF_ERROR if failed, otherwise GIF_OK.
*******************************************************************************/
static int
SubdivColorMap(NewColorMapType * NewColorSubdiv,
unsigned int ColorMapSize,
unsigned int *NewColorMapSize) {
int MaxSize;
unsigned int i, j, Index = 0, NumEntries, MinColor, MaxColor;
long Sum, Count;
QuantizedColorType *QuantizedColor, **SortArray;
while (ColorMapSize > *NewColorMapSize) {
/* Find candidate for subdivision: */
MaxSize = -1;
for (i = 0; i < *NewColorMapSize; i++) {
for (j = 0; j < 3; j++) {
if ((((int)NewColorSubdiv[i].RGBWidth[j]) > MaxSize) &&
(NewColorSubdiv[i].NumEntries > 1)) {
MaxSize = NewColorSubdiv[i].RGBWidth[j];
Index = i;
SortRGBAxis = j;
}
}
}
if (MaxSize == -1)
return GIF_OK;
/* Split the entry Index into two along the axis SortRGBAxis: */
/* Sort all elements in that entry along the given axis and split at
* the median. */
SortArray = (QuantizedColorType **)malloc(
sizeof(QuantizedColorType *) *
NewColorSubdiv[Index].NumEntries);
if (SortArray == NULL)
return GIF_ERROR;
for (j = 0, QuantizedColor = NewColorSubdiv[Index].QuantizedColors;
j < NewColorSubdiv[Index].NumEntries && QuantizedColor != NULL;
j++, QuantizedColor = QuantizedColor->Pnext)
SortArray[j] = QuantizedColor;
/*
* Because qsort isn't stable, this can produce differing
* results for the order of tuples depending on platform
* details of how qsort() is implemented.
*
* We mitigate this problem by sorting on all three axes rather
* than only the one specied by SortRGBAxis; that way the instability
* can only become an issue if there are multiple color indices
* referring to identical RGB tuples. Older versions of this
* sorted on only the one axis.
*/
qsort(SortArray, NewColorSubdiv[Index].NumEntries,
sizeof(QuantizedColorType *), SortCmpRtn);
/* Relink the sorted list into one: */
for (j = 0; j < NewColorSubdiv[Index].NumEntries - 1; j++)
SortArray[j]->Pnext = SortArray[j + 1];
SortArray[NewColorSubdiv[Index].NumEntries - 1]->Pnext = NULL;
NewColorSubdiv[Index].QuantizedColors = QuantizedColor = SortArray[0];
free((char *)SortArray);
/* Now simply add the Counts until we have half of the Count: */
Sum = NewColorSubdiv[Index].Count / 2 - QuantizedColor->Count;
NumEntries = 1;
Count = QuantizedColor->Count;
while (QuantizedColor->Pnext != NULL &&
(Sum -= QuantizedColor->Pnext->Count) >= 0 &&
QuantizedColor->Pnext->Pnext != NULL) {
QuantizedColor = QuantizedColor->Pnext;
NumEntries++;
Count += QuantizedColor->Count;
}
/* Save the values of the last color of the first half, and first
* of the second half so we can update the Bounding Boxes later.
* Also as the colors are quantized and the BBoxes are full 0..255,
* they need to be rescaled.
*/
MaxColor = QuantizedColor->RGB[SortRGBAxis]; /* Max. of first half */
/* coverity[var_deref_op] */
MinColor = QuantizedColor->Pnext->RGB[SortRGBAxis]; /* of second */
MaxColor <<= (8 - BITS_PER_PRIM_COLOR);
MinColor <<= (8 - BITS_PER_PRIM_COLOR);
/* Partition right here: */
NewColorSubdiv[*NewColorMapSize].QuantizedColors =
QuantizedColor->Pnext;
QuantizedColor->Pnext = NULL;
NewColorSubdiv[*NewColorMapSize].Count = Count;
NewColorSubdiv[Index].Count -= Count;
NewColorSubdiv[*NewColorMapSize].NumEntries =
NewColorSubdiv[Index].NumEntries - NumEntries;
NewColorSubdiv[Index].NumEntries = NumEntries;
for (j = 0; j < 3; j++) {
NewColorSubdiv[*NewColorMapSize].RGBMin[j] =
NewColorSubdiv[Index].RGBMin[j];
NewColorSubdiv[*NewColorMapSize].RGBWidth[j] =
NewColorSubdiv[Index].RGBWidth[j];
}
NewColorSubdiv[*NewColorMapSize].RGBWidth[SortRGBAxis] =
NewColorSubdiv[*NewColorMapSize].RGBMin[SortRGBAxis] +
NewColorSubdiv[*NewColorMapSize].RGBWidth[SortRGBAxis] - MinColor;
NewColorSubdiv[*NewColorMapSize].RGBMin[SortRGBAxis] = MinColor;
NewColorSubdiv[Index].RGBWidth[SortRGBAxis] =
MaxColor - NewColorSubdiv[Index].RGBMin[SortRGBAxis];
(*NewColorMapSize)++;
}
return GIF_OK;
}
/****************************************************************************
Routine called by qsort to compare two entries.
*****************************************************************************/
static int
SortCmpRtn(const void *Entry1,
const void *Entry2) {
QuantizedColorType *entry1 = (*((QuantizedColorType **) Entry1));
QuantizedColorType *entry2 = (*((QuantizedColorType **) Entry2));
/* sort on all axes of the color space! */
int hash1 = entry1->RGB[SortRGBAxis] * 256 * 256
+ entry1->RGB[(SortRGBAxis+1) % 3] * 256
+ entry1->RGB[(SortRGBAxis+2) % 3];
int hash2 = entry2->RGB[SortRGBAxis] * 256 * 256
+ entry2->RGB[(SortRGBAxis+1) % 3] * 256
+ entry2->RGB[(SortRGBAxis+2) % 3];
return hash1 - hash2;
}
/* end */
| apache-2.0 |
blackrose28/omaha | third_party/lzma/v4_65/files/CPP/Windows/PropVariantConversions.cpp | 68 | 2840 | // PropVariantConversions.cpp
#include "StdAfx.h"
#include "PropVariantConversions.h"
#include "Windows/Defs.h"
#include "Common/StringConvert.h"
#include "Common/IntToString.h"
static UString ConvertUInt64ToString(UInt64 value)
{
wchar_t buffer[32];
ConvertUInt64ToString(value, buffer);
return buffer;
}
static UString ConvertInt64ToString(Int64 value)
{
wchar_t buffer[32];
ConvertInt64ToString(value, buffer);
return buffer;
}
static char *UIntToStringSpec(char c, UInt32 value, char *s, int numPos)
{
if (c != 0)
*s++ = c;
char temp[16];
int pos = 0;
do
{
temp[pos++] = (char)('0' + value % 10);
value /= 10;
}
while (value != 0);
int i;
for (i = 0; i < numPos - pos; i++)
*s++ = '0';
do
*s++ = temp[--pos];
while (pos > 0);
*s = '\0';
return s;
}
bool ConvertFileTimeToString(const FILETIME &ft, char *s, bool includeTime, bool includeSeconds)
{
s[0] = '\0';
SYSTEMTIME st;
if (!BOOLToBool(FileTimeToSystemTime(&ft, &st)))
return false;
s = UIntToStringSpec(0, st.wYear, s, 4);
s = UIntToStringSpec('-', st.wMonth, s, 2);
s = UIntToStringSpec('-', st.wDay, s, 2);
if (includeTime)
{
s = UIntToStringSpec(' ', st.wHour, s, 2);
s = UIntToStringSpec(':', st.wMinute, s, 2);
if (includeSeconds)
UIntToStringSpec(':', st.wSecond, s, 2);
}
return true;
}
UString ConvertFileTimeToString(const FILETIME &fileTime, bool includeTime, bool includeSeconds)
{
char s[32];
ConvertFileTimeToString(fileTime, s, includeTime, includeSeconds);
return GetUnicodeString(s);
}
UString ConvertPropVariantToString(const PROPVARIANT &prop)
{
switch (prop.vt)
{
case VT_EMPTY: return UString();
case VT_BSTR: return prop.bstrVal;
case VT_UI1: return ConvertUInt64ToString(prop.bVal);
case VT_UI2: return ConvertUInt64ToString(prop.uiVal);
case VT_UI4: return ConvertUInt64ToString(prop.ulVal);
case VT_UI8: return ConvertUInt64ToString(prop.uhVal.QuadPart);
case VT_FILETIME: return ConvertFileTimeToString(prop.filetime, true, true);
// case VT_I1: return ConvertInt64ToString(prop.cVal);
case VT_I2: return ConvertInt64ToString(prop.iVal);
case VT_I4: return ConvertInt64ToString(prop.lVal);
case VT_I8: return ConvertInt64ToString(prop.hVal.QuadPart);
case VT_BOOL: return VARIANT_BOOLToBool(prop.boolVal) ? L"+" : L"-";
default:
#ifndef _WIN32_WCE
throw 150245;
#else
return UString();
#endif
}
}
UInt64 ConvertPropVariantToUInt64(const PROPVARIANT &prop)
{
switch (prop.vt)
{
case VT_UI1: return prop.bVal;
case VT_UI2: return prop.uiVal;
case VT_UI4: return prop.ulVal;
case VT_UI8: return (UInt64)prop.uhVal.QuadPart;
default:
#ifndef _WIN32_WCE
throw 151199;
#else
return 0;
#endif
}
}
| apache-2.0 |
jjjaaajjj/ws-pro-android-games | ch05.Android.Doom/Doom/prboom/SDL-1.2.13/src/stdlib/SDL_string.c | 69 | 34089 | /*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2006 Sam Lantinga
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
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
/* This file contains portable string manipulation functions for SDL */
#include "SDL_stdinc.h"
#define SDL_isupperhex(X) (((X) >= 'A') && ((X) <= 'F'))
#define SDL_islowerhex(X) (((X) >= 'a') && ((X) <= 'f'))
#if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOL)
static size_t SDL_ScanLong(const char *text, int radix, long *valuep)
{
const char *textstart = text;
long value = 0;
SDL_bool negative = SDL_FALSE;
if ( *text == '-' ) {
negative = SDL_TRUE;
++text;
}
if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) {
text += 2;
}
for ( ; ; ) {
int v;
if ( SDL_isdigit((unsigned char) *text) ) {
v = *text - '0';
} else if ( radix == 16 && SDL_isupperhex(*text) ) {
v = 10 + (*text - 'A');
} else if ( radix == 16 && SDL_islowerhex(*text) ) {
v = 10 + (*text - 'a');
} else {
break;
}
value *= radix;
value += v;
++text;
}
if ( valuep ) {
if ( negative && value ) {
*valuep = -value;
} else {
*valuep = value;
}
}
return (text - textstart);
}
#endif
#if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOUL) || !defined(HAVE_STRTOD)
static size_t SDL_ScanUnsignedLong(const char *text, int radix, unsigned long *valuep)
{
const char *textstart = text;
unsigned long value = 0;
if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) {
text += 2;
}
for ( ; ; ) {
int v;
if ( SDL_isdigit((unsigned char) *text) ) {
v = *text - '0';
} else if ( radix == 16 && SDL_isupperhex(*text) ) {
v = 10 + (*text - 'A');
} else if ( radix == 16 && SDL_islowerhex(*text) ) {
v = 10 + (*text - 'a');
} else {
break;
}
value *= radix;
value += v;
++text;
}
if ( valuep ) {
*valuep = value;
}
return (text - textstart);
}
#endif
#ifndef HAVE_SSCANF
static size_t SDL_ScanUintPtrT(const char *text, int radix, uintptr_t *valuep)
{
const char *textstart = text;
uintptr_t value = 0;
if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) {
text += 2;
}
for ( ; ; ) {
int v;
if ( SDL_isdigit((unsigned char) *text) ) {
v = *text - '0';
} else if ( radix == 16 && SDL_isupperhex(*text) ) {
v = 10 + (*text - 'A');
} else if ( radix == 16 && SDL_islowerhex(*text) ) {
v = 10 + (*text - 'a');
} else {
break;
}
value *= radix;
value += v;
++text;
}
if ( valuep ) {
*valuep = value;
}
return (text - textstart);
}
#endif
#ifdef SDL_HAS_64BIT_TYPE
#if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOLL)
static size_t SDL_ScanLongLong(const char *text, int radix, Sint64 *valuep)
{
const char *textstart = text;
Sint64 value = 0;
SDL_bool negative = SDL_FALSE;
if ( *text == '-' ) {
negative = SDL_TRUE;
++text;
}
if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) {
text += 2;
}
for ( ; ; ) {
int v;
if ( SDL_isdigit((unsigned char) *text) ) {
v = *text - '0';
} else if ( radix == 16 && SDL_isupperhex(*text) ) {
v = 10 + (*text - 'A');
} else if ( radix == 16 && SDL_islowerhex(*text) ) {
v = 10 + (*text - 'a');
} else {
break;
}
value *= radix;
value += v;
++text;
}
if ( valuep ) {
if ( negative && value ) {
*valuep = -value;
} else {
*valuep = value;
}
}
return (text - textstart);
}
#endif
#if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOULL)
static size_t SDL_ScanUnsignedLongLong(const char *text, int radix, Uint64 *valuep)
{
const char *textstart = text;
Uint64 value = 0;
if ( radix == 16 && SDL_strncmp(text, "0x", 2) == 0 ) {
text += 2;
}
for ( ; ; ) {
int v;
if ( SDL_isdigit((unsigned char) *text) ) {
v = *text - '0';
} else if ( radix == 16 && SDL_isupperhex(*text) ) {
v = 10 + (*text - 'A');
} else if ( radix == 16 && SDL_islowerhex(*text) ) {
v = 10 + (*text - 'a');
} else {
break;
}
value *= radix;
value += v;
++text;
}
if ( valuep ) {
*valuep = value;
}
return (text - textstart);
}
#endif
#endif /* SDL_HAS_64BIT_TYPE */
#if !defined(HAVE_SSCANF) || !defined(HAVE_STRTOD)
static size_t SDL_ScanFloat(const char *text, double *valuep)
{
const char *textstart = text;
unsigned long lvalue = 0;
double value = 0.0;
SDL_bool negative = SDL_FALSE;
if ( *text == '-' ) {
negative = SDL_TRUE;
++text;
}
text += SDL_ScanUnsignedLong(text, 10, &lvalue);
value += lvalue;
if ( *text == '.' ) {
int mult = 10;
++text;
while ( SDL_isdigit((unsigned char) *text) ) {
lvalue = *text - '0';
value += (double)lvalue / mult;
mult *= 10;
++text;
}
}
if ( valuep ) {
if ( negative && value ) {
*valuep = -value;
} else {
*valuep = value;
}
}
return (text - textstart);
}
#endif
#ifndef SDL_memset
void *SDL_memset(void *dst, int c, size_t len)
{
size_t left = (len % 4);
if ( len >= 4 ) {
Uint32 value = 0;
Uint32 *dstp = (Uint32 *)dst;
int i;
for (i = 0; i < 4; ++i) {
value <<= 8;
value |= c;
}
len /= 4;
while ( len-- ) {
*dstp++ = value;
}
}
if ( left > 0 ) {
Uint8 value = (Uint8)c;
Uint8 *dstp = (Uint8 *)dst;
switch(left) {
case 3:
*dstp++ = value;
case 2:
*dstp++ = value;
case 1:
*dstp++ = value;
}
}
return dst;
}
#endif
#ifndef SDL_memcpy
void *SDL_memcpy(void *dst, const void *src, size_t len)
{
char *srcp = (char *)src;
char *dstp = (char *)dst;
while ( len-- ) {
*dstp++ = *srcp++;
}
return dst;
}
#endif
#ifndef SDL_revcpy
void *SDL_revcpy(void *dst, const void *src, size_t len)
{
char *srcp = (char *)src;
char *dstp = (char *)dst;
srcp += len-1;
dstp += len-1;
while ( len-- ) {
*dstp-- = *srcp--;
}
return dst;
}
#endif
#ifndef SDL_memcmp
int SDL_memcmp(const void *s1, const void *s2, size_t len)
{
char *s1p = (char *)s1;
char *s2p = (char *)s2;
while ( len-- ) {
if ( *s1p != *s2p ) {
return (*s1p - *s2p);
}
++s1p;
++s2p;
}
return 0;
}
#endif
#ifndef HAVE_STRLEN
size_t SDL_strlen(const char *string)
{
size_t len = 0;
while ( *string++ ) {
++len;
}
return len;
}
#endif
#ifndef HAVE_STRLCPY
size_t SDL_strlcpy(char *dst, const char *src, size_t maxlen)
{
size_t srclen = SDL_strlen(src);
if ( maxlen > 0 ) {
size_t len = SDL_min(srclen, maxlen-1);
SDL_memcpy(dst, src, len);
dst[len] = '\0';
}
return srclen;
}
#endif
#ifndef HAVE_STRLCAT
size_t SDL_strlcat(char *dst, const char *src, size_t maxlen)
{
size_t dstlen = SDL_strlen(dst);
size_t srclen = SDL_strlen(src);
if ( dstlen < maxlen ) {
SDL_strlcpy(dst+dstlen, src, maxlen-dstlen);
}
return dstlen+srclen;
}
#endif
#ifndef HAVE_STRDUP
char *SDL_strdup(const char *string)
{
size_t len = SDL_strlen(string)+1;
char *newstr = SDL_malloc(len);
if ( newstr ) {
SDL_strlcpy(newstr, string, len);
}
return newstr;
}
#endif
#ifndef HAVE__STRREV
char *SDL_strrev(char *string)
{
size_t len = SDL_strlen(string);
char *a = &string[0];
char *b = &string[len-1];
len /= 2;
while ( len-- ) {
char c = *a;
*a++ = *b;
*b-- = c;
}
return string;
}
#endif
#ifndef HAVE__STRUPR
char *SDL_strupr(char *string)
{
char *bufp = string;
while ( *bufp ) {
*bufp = SDL_toupper((unsigned char) *bufp);
++bufp;
}
return string;
}
#endif
#ifndef HAVE__STRLWR
char *SDL_strlwr(char *string)
{
char *bufp = string;
while ( *bufp ) {
*bufp = SDL_tolower((unsigned char) *bufp);
++bufp;
}
return string;
}
#endif
#ifndef HAVE_STRCHR
char *SDL_strchr(const char *string, int c)
{
while ( *string ) {
if ( *string == c ) {
return (char *)string;
}
++string;
}
return NULL;
}
#endif
#ifndef HAVE_STRRCHR
char *SDL_strrchr(const char *string, int c)
{
const char *bufp = string + SDL_strlen(string) - 1;
while ( bufp >= string ) {
if ( *bufp == c ) {
return (char *)bufp;
}
--bufp;
}
return NULL;
}
#endif
#ifndef HAVE_STRSTR
char *SDL_strstr(const char *haystack, const char *needle)
{
size_t length = SDL_strlen(needle);
while ( *haystack ) {
if ( SDL_strncmp(haystack, needle, length) == 0 ) {
return (char *)haystack;
}
++haystack;
}
return NULL;
}
#endif
#if !defined(HAVE__LTOA) || !defined(HAVE__I64TOA) || \
!defined(HAVE__ULTOA) || !defined(HAVE__UI64TOA)
static const char ntoa_table[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z'
};
#endif /* ntoa() conversion table */
#ifndef HAVE__LTOA
char *SDL_ltoa(long value, char *string, int radix)
{
char *bufp = string;
if ( value < 0 ) {
*bufp++ = '-';
value = -value;
}
if ( value ) {
while ( value > 0 ) {
*bufp++ = ntoa_table[value % radix];
value /= radix;
}
} else {
*bufp++ = '0';
}
*bufp = '\0';
/* The numbers went into the string backwards. :) */
if ( *string == '-' ) {
SDL_strrev(string+1);
} else {
SDL_strrev(string);
}
return string;
}
#endif
#ifndef HAVE__ULTOA
char *SDL_ultoa(unsigned long value, char *string, int radix)
{
char *bufp = string;
if ( value ) {
while ( value > 0 ) {
*bufp++ = ntoa_table[value % radix];
value /= radix;
}
} else {
*bufp++ = '0';
}
*bufp = '\0';
/* The numbers went into the string backwards. :) */
SDL_strrev(string);
return string;
}
#endif
#ifndef HAVE_STRTOL
long SDL_strtol(const char *string, char **endp, int base)
{
size_t len;
long value;
if ( !base ) {
if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) {
base = 16;
} else {
base = 10;
}
}
len = SDL_ScanLong(string, base, &value);
if ( endp ) {
*endp = (char *)string + len;
}
return value;
}
#endif
#ifndef HAVE_STRTOUL
unsigned long SDL_strtoul(const char *string, char **endp, int base)
{
size_t len;
unsigned long value;
if ( !base ) {
if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) {
base = 16;
} else {
base = 10;
}
}
len = SDL_ScanUnsignedLong(string, base, &value);
if ( endp ) {
*endp = (char *)string + len;
}
return value;
}
#endif
#ifdef SDL_HAS_64BIT_TYPE
#ifndef HAVE__I64TOA
char *SDL_lltoa(Sint64 value, char *string, int radix)
{
char *bufp = string;
if ( value < 0 ) {
*bufp++ = '-';
value = -value;
}
if ( value ) {
while ( value > 0 ) {
*bufp++ = ntoa_table[value % radix];
value /= radix;
}
} else {
*bufp++ = '0';
}
*bufp = '\0';
/* The numbers went into the string backwards. :) */
if ( *string == '-' ) {
SDL_strrev(string+1);
} else {
SDL_strrev(string);
}
return string;
}
#endif
#ifndef HAVE__UI64TOA
char *SDL_ulltoa(Uint64 value, char *string, int radix)
{
char *bufp = string;
if ( value ) {
while ( value > 0 ) {
*bufp++ = ntoa_table[value % radix];
value /= radix;
}
} else {
*bufp++ = '0';
}
*bufp = '\0';
/* The numbers went into the string backwards. :) */
SDL_strrev(string);
return string;
}
#endif
#ifndef HAVE_STRTOLL
Sint64 SDL_strtoll(const char *string, char **endp, int base)
{
size_t len;
Sint64 value;
if ( !base ) {
if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) {
base = 16;
} else {
base = 10;
}
}
len = SDL_ScanLongLong(string, base, &value);
if ( endp ) {
*endp = (char *)string + len;
}
return value;
}
#endif
#ifndef HAVE_STRTOULL
Uint64 SDL_strtoull(const char *string, char **endp, int base)
{
size_t len;
Uint64 value;
if ( !base ) {
if ( (SDL_strlen(string) > 2) && (SDL_strncmp(string, "0x", 2) == 0) ) {
base = 16;
} else {
base = 10;
}
}
len = SDL_ScanUnsignedLongLong(string, base, &value);
if ( endp ) {
*endp = (char *)string + len;
}
return value;
}
#endif
#endif /* SDL_HAS_64BIT_TYPE */
#ifndef HAVE_STRTOD
double SDL_strtod(const char *string, char **endp)
{
size_t len;
double value;
len = SDL_ScanFloat(string, &value);
if ( endp ) {
*endp = (char *)string + len;
}
return value;
}
#endif
#ifndef HAVE_STRCMP
int SDL_strcmp(const char *str1, const char *str2)
{
while (*str1 && *str2) {
if ( *str1 != *str2 )
break;
++str1;
++str2;
}
return (int)((unsigned char)*str1 - (unsigned char)*str2);
}
#endif
#ifndef HAVE_STRNCMP
int SDL_strncmp(const char *str1, const char *str2, size_t maxlen)
{
while ( *str1 && *str2 && maxlen ) {
if ( *str1 != *str2 )
break;
++str1;
++str2;
--maxlen;
}
if ( ! maxlen ) {
return 0;
}
return (int)((unsigned char)*str1 - (unsigned char)*str2);
}
#endif
#if !defined(HAVE_STRCASECMP) && !defined(HAVE__STRICMP)
int SDL_strcasecmp(const char *str1, const char *str2)
{
char a = 0;
char b = 0;
while ( *str1 && *str2 ) {
a = SDL_tolower((unsigned char) *str1);
b = SDL_tolower((unsigned char) *str2);
if ( a != b )
break;
++str1;
++str2;
}
return (int)((unsigned char)a - (unsigned char)b);
}
#endif
#if !defined(HAVE_STRNCASECMP) && !defined(HAVE__STRNICMP)
int SDL_strncasecmp(const char *str1, const char *str2, size_t maxlen)
{
char a = 0;
char b = 0;
while ( *str1 && *str2 && maxlen ) {
a = SDL_tolower((unsigned char) *str1);
b = SDL_tolower((unsigned char) *str2);
if ( a != b )
break;
++str1;
++str2;
--maxlen;
}
return (int)((unsigned char)a - (unsigned char)b);
}
#endif
#ifndef HAVE_SSCANF
int SDL_sscanf(const char *text, const char *fmt, ...)
{
va_list ap;
int retval = 0;
va_start(ap, fmt);
while ( *fmt ) {
if ( *fmt == ' ' ) {
while ( SDL_isspace((unsigned char) *text) ) {
++text;
}
++fmt;
continue;
}
if ( *fmt == '%' ) {
SDL_bool done = SDL_FALSE;
long count = 0;
int radix = 10;
enum {
DO_SHORT,
DO_INT,
DO_LONG,
DO_LONGLONG
} inttype = DO_INT;
SDL_bool suppress = SDL_FALSE;
++fmt;
if ( *fmt == '%' ) {
if ( *text == '%' ) {
++text;
++fmt;
continue;
}
break;
}
if ( *fmt == '*' ) {
suppress = SDL_TRUE;
++fmt;
}
fmt += SDL_ScanLong(fmt, 10, &count);
if ( *fmt == 'c' ) {
if ( ! count ) {
count = 1;
}
if ( suppress ) {
while ( count-- ) {
++text;
}
} else {
char *valuep = va_arg(ap, char*);
while ( count-- ) {
*valuep++ = *text++;
}
++retval;
}
continue;
}
while ( SDL_isspace((unsigned char) *text) ) {
++text;
}
/* FIXME: implement more of the format specifiers */
while (!done) {
switch(*fmt) {
case '*':
suppress = SDL_TRUE;
break;
case 'h':
if ( inttype > DO_SHORT ) {
++inttype;
}
break;
case 'l':
if ( inttype < DO_LONGLONG ) {
++inttype;
}
break;
case 'I':
if ( SDL_strncmp(fmt, "I64", 3) == 0 ) {
fmt += 2;
inttype = DO_LONGLONG;
}
break;
case 'i':
{
int index = 0;
if ( text[index] == '-' ) {
++index;
}
if ( text[index] == '0' ) {
if ( SDL_tolower((unsigned char) text[index+1]) == 'x' ) {
radix = 16;
} else {
radix = 8;
}
}
}
/* Fall through to %d handling */
case 'd':
#ifdef SDL_HAS_64BIT_TYPE
if ( inttype == DO_LONGLONG ) {
Sint64 value;
text += SDL_ScanLongLong(text, radix, &value);
if ( ! suppress ) {
Sint64 *valuep = va_arg(ap, Sint64*);
*valuep = value;
++retval;
}
}
else
#endif /* SDL_HAS_64BIT_TYPE */
{
long value;
text += SDL_ScanLong(text, radix, &value);
if ( ! suppress ) {
switch (inttype) {
case DO_SHORT:
{ short* valuep = va_arg(ap, short*);
*valuep = (short)value;
}
break;
case DO_INT:
{ int* valuep = va_arg(ap, int*);
*valuep = (int)value;
}
break;
case DO_LONG:
{ long* valuep = va_arg(ap, long*);
*valuep = value;
}
break;
case DO_LONGLONG:
/* Handled above */
break;
}
++retval;
}
}
done = SDL_TRUE;
break;
case 'o':
if ( radix == 10 ) {
radix = 8;
}
/* Fall through to unsigned handling */
case 'x':
case 'X':
if ( radix == 10 ) {
radix = 16;
}
/* Fall through to unsigned handling */
case 'u':
#ifdef SDL_HAS_64BIT_TYPE
if ( inttype == DO_LONGLONG ) {
Uint64 value;
text += SDL_ScanUnsignedLongLong(text, radix, &value);
if ( ! suppress ) {
Uint64 *valuep = va_arg(ap, Uint64*);
*valuep = value;
++retval;
}
}
else
#endif /* SDL_HAS_64BIT_TYPE */
{
unsigned long value;
text += SDL_ScanUnsignedLong(text, radix, &value);
if ( ! suppress ) {
switch (inttype) {
case DO_SHORT:
{ short* valuep = va_arg(ap, short*);
*valuep = (short)value;
}
break;
case DO_INT:
{ int* valuep = va_arg(ap, int*);
*valuep = (int)value;
}
break;
case DO_LONG:
{ long* valuep = va_arg(ap, long*);
*valuep = value;
}
break;
case DO_LONGLONG:
/* Handled above */
break;
}
++retval;
}
}
done = SDL_TRUE;
break;
case 'p':
{
uintptr_t value;
text += SDL_ScanUintPtrT(text, 16, &value);
if ( ! suppress ) {
void** valuep = va_arg(ap, void**);
*valuep = (void*)value;
++retval;
}
}
done = SDL_TRUE;
break;
case 'f':
{
double value;
text += SDL_ScanFloat(text, &value);
if ( ! suppress ) {
float* valuep = va_arg(ap, float*);
*valuep = (float)value;
++retval;
}
}
done = SDL_TRUE;
break;
case 's':
if ( suppress ) {
while ( !SDL_isspace((unsigned char) *text) ) {
++text;
if ( count ) {
if ( --count == 0 ) {
break;
}
}
}
} else {
char *valuep = va_arg(ap, char*);
while ( !SDL_isspace((unsigned char) *text) ) {
*valuep++ = *text++;
if ( count ) {
if ( --count == 0 ) {
break;
}
}
}
*valuep = '\0';
++retval;
}
done = SDL_TRUE;
break;
default:
done = SDL_TRUE;
break;
}
++fmt;
}
continue;
}
if ( *text == *fmt ) {
++text;
++fmt;
continue;
}
/* Text didn't match format specifier */
break;
}
va_end(ap);
return retval;
}
#endif
#ifndef HAVE_SNPRINTF
int SDL_snprintf(char *text, size_t maxlen, const char *fmt, ...)
{
va_list ap;
int retval;
va_start(ap, fmt);
retval = SDL_vsnprintf(text, maxlen, fmt, ap);
va_end(ap);
return retval;
}
#endif
#ifndef HAVE_VSNPRINTF
static size_t SDL_PrintLong(char *text, long value, int radix, size_t maxlen)
{
char num[130];
size_t size;
SDL_ltoa(value, num, radix);
size = SDL_strlen(num);
if ( size >= maxlen ) {
size = maxlen-1;
}
SDL_strlcpy(text, num, size+1);
return size;
}
static size_t SDL_PrintUnsignedLong(char *text, unsigned long value, int radix, size_t maxlen)
{
char num[130];
size_t size;
SDL_ultoa(value, num, radix);
size = SDL_strlen(num);
if ( size >= maxlen ) {
size = maxlen-1;
}
SDL_strlcpy(text, num, size+1);
return size;
}
#ifdef SDL_HAS_64BIT_TYPE
static size_t SDL_PrintLongLong(char *text, Sint64 value, int radix, size_t maxlen)
{
char num[130];
size_t size;
SDL_lltoa(value, num, radix);
size = SDL_strlen(num);
if ( size >= maxlen ) {
size = maxlen-1;
}
SDL_strlcpy(text, num, size+1);
return size;
}
static size_t SDL_PrintUnsignedLongLong(char *text, Uint64 value, int radix, size_t maxlen)
{
char num[130];
size_t size;
SDL_ulltoa(value, num, radix);
size = SDL_strlen(num);
if ( size >= maxlen ) {
size = maxlen-1;
}
SDL_strlcpy(text, num, size+1);
return size;
}
#endif /* SDL_HAS_64BIT_TYPE */
static size_t SDL_PrintFloat(char *text, double arg, size_t maxlen)
{
char *textstart = text;
if ( arg ) {
/* This isn't especially accurate, but hey, it's easy. :) */
const double precision = 0.00000001;
size_t len;
unsigned long value;
if ( arg < 0 ) {
*text++ = '-';
--maxlen;
arg = -arg;
}
value = (unsigned long)arg;
len = SDL_PrintUnsignedLong(text, value, 10, maxlen);
text += len;
maxlen -= len;
arg -= value;
if ( arg > precision && maxlen ) {
int mult = 10;
*text++ = '.';
while ( (arg > precision) && maxlen ) {
value = (unsigned long)(arg * mult);
len = SDL_PrintUnsignedLong(text, value, 10, maxlen);
text += len;
maxlen -= len;
arg -= (double)value / mult;
mult *= 10;
}
}
} else {
*text++ = '0';
}
return (text - textstart);
}
static size_t SDL_PrintString(char *text, const char *string, size_t maxlen)
{
char *textstart = text;
while ( *string && maxlen-- ) {
*text++ = *string++;
}
return (text - textstart);
}
int SDL_vsnprintf(char *text, size_t maxlen, const char *fmt, va_list ap)
{
char *textstart = text;
if ( maxlen <= 0 ) {
return 0;
}
--maxlen; /* For the trailing '\0' */
while ( *fmt && maxlen ) {
if ( *fmt == '%' ) {
SDL_bool done = SDL_FALSE;
size_t len = 0;
SDL_bool do_lowercase = SDL_FALSE;
int radix = 10;
enum {
DO_INT,
DO_LONG,
DO_LONGLONG
} inttype = DO_INT;
++fmt;
/* FIXME: implement more of the format specifiers */
while ( *fmt == '.' || (*fmt >= '0' && *fmt <= '9') ) {
++fmt;
}
while (!done) {
switch(*fmt) {
case '%':
*text = '%';
len = 1;
done = SDL_TRUE;
break;
case 'c':
/* char is promoted to int when passed through (...) */
*text = (char)va_arg(ap, int);
len = 1;
done = SDL_TRUE;
break;
case 'h':
/* short is promoted to int when passed through (...) */
break;
case 'l':
if ( inttype < DO_LONGLONG ) {
++inttype;
}
break;
case 'I':
if ( SDL_strncmp(fmt, "I64", 3) == 0 ) {
fmt += 2;
inttype = DO_LONGLONG;
}
break;
case 'i':
case 'd':
switch (inttype) {
case DO_INT:
len = SDL_PrintLong(text, (long)va_arg(ap, int), radix, maxlen);
break;
case DO_LONG:
len = SDL_PrintLong(text, va_arg(ap, long), radix, maxlen);
break;
case DO_LONGLONG:
#ifdef SDL_HAS_64BIT_TYPE
len = SDL_PrintLongLong(text, va_arg(ap, Sint64), radix, maxlen);
#else
len = SDL_PrintLong(text, va_arg(ap, long), radix, maxlen);
#endif
break;
}
done = SDL_TRUE;
break;
case 'p':
case 'x':
do_lowercase = SDL_TRUE;
/* Fall through to 'X' handling */
case 'X':
if ( radix == 10 ) {
radix = 16;
}
if ( *fmt == 'p' ) {
inttype = DO_LONG;
}
/* Fall through to unsigned handling */
case 'o':
if ( radix == 10 ) {
radix = 8;
}
/* Fall through to unsigned handling */
case 'u':
switch (inttype) {
case DO_INT:
len = SDL_PrintUnsignedLong(text, (unsigned long)va_arg(ap, unsigned int), radix, maxlen);
break;
case DO_LONG:
len = SDL_PrintUnsignedLong(text, va_arg(ap, unsigned long), radix, maxlen);
break;
case DO_LONGLONG:
#ifdef SDL_HAS_64BIT_TYPE
len = SDL_PrintUnsignedLongLong(text, va_arg(ap, Uint64), radix, maxlen);
#else
len = SDL_PrintUnsignedLong(text, va_arg(ap, unsigned long), radix, maxlen);
#endif
break;
}
if ( do_lowercase ) {
SDL_strlwr(text);
}
done = SDL_TRUE;
break;
case 'f':
len = SDL_PrintFloat(text, va_arg(ap, double), maxlen);
done = SDL_TRUE;
break;
case 's':
len = SDL_PrintString(text, va_arg(ap, char*), maxlen);
done = SDL_TRUE;
break;
default:
done = SDL_TRUE;
break;
}
++fmt;
}
text += len;
maxlen -= len;
} else {
*text++ = *fmt++;
--maxlen;
}
}
*text = '\0';
return (text - textstart);
}
#endif
| apache-2.0 |
getlantern/lantern-mobile | external/badvpn/lwip/src/core/snmp/msg_in.c | 583 | 43896 | /**
* @file
* SNMP input message processing (RFC1157).
*/
/*
* Copyright (c) 2006 Axon Digital Design B.V., The Netherlands.
* 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.
*
* Author: Christiaan Simons <christiaan.simons@axon.tv>
*/
#include "lwip/opt.h"
#if LWIP_SNMP /* don't build if not configured for use in lwipopts.h */
#include "lwip/snmp.h"
#include "lwip/snmp_asn1.h"
#include "lwip/snmp_msg.h"
#include "lwip/snmp_structs.h"
#include "lwip/ip_addr.h"
#include "lwip/memp.h"
#include "lwip/udp.h"
#include "lwip/stats.h"
#include <string.h>
/* public (non-static) constants */
/** SNMP v1 == 0 */
const s32_t snmp_version = 0;
/** default SNMP community string */
const char snmp_publiccommunity[7] = "public";
/* statically allocated buffers for SNMP_CONCURRENT_REQUESTS */
struct snmp_msg_pstat msg_input_list[SNMP_CONCURRENT_REQUESTS];
/* UDP Protocol Control Block */
struct udp_pcb *snmp1_pcb;
static void snmp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port);
static err_t snmp_pdu_header_check(struct pbuf *p, u16_t ofs, u16_t pdu_len, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat);
static err_t snmp_pdu_dec_varbindlist(struct pbuf *p, u16_t ofs, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat);
/**
* Starts SNMP Agent.
* Allocates UDP pcb and binds it to IP_ADDR_ANY port 161.
*/
void
snmp_init(void)
{
struct snmp_msg_pstat *msg_ps;
u8_t i;
snmp1_pcb = udp_new();
if (snmp1_pcb != NULL)
{
udp_recv(snmp1_pcb, snmp_recv, (void *)SNMP_IN_PORT);
udp_bind(snmp1_pcb, IP_ADDR_ANY, SNMP_IN_PORT);
}
msg_ps = &msg_input_list[0];
for (i=0; i<SNMP_CONCURRENT_REQUESTS; i++)
{
msg_ps->state = SNMP_MSG_EMPTY;
msg_ps->error_index = 0;
msg_ps->error_status = SNMP_ES_NOERROR;
msg_ps++;
}
trap_msg.pcb = snmp1_pcb;
#ifdef SNMP_PRIVATE_MIB_INIT
/* If defined, this must be a function-like define to initialize the
* private MIB after the stack has been initialized.
* The private MIB can also be initialized in tcpip_callback (or after
* the stack is initialized), this define is only for convenience. */
SNMP_PRIVATE_MIB_INIT();
#endif /* SNMP_PRIVATE_MIB_INIT */
/* The coldstart trap will only be output
if our outgoing interface is up & configured */
snmp_coldstart_trap();
}
static void
snmp_error_response(struct snmp_msg_pstat *msg_ps, u8_t error)
{
/* move names back from outvb to invb */
int v;
struct snmp_varbind *vbi = msg_ps->invb.head;
struct snmp_varbind *vbo = msg_ps->outvb.head;
for (v=0; v<msg_ps->vb_idx; v++) {
vbi->ident_len = vbo->ident_len;
vbo->ident_len = 0;
vbi->ident = vbo->ident;
vbo->ident = NULL;
vbi = vbi->next;
vbo = vbo->next;
}
/* free outvb */
snmp_varbind_list_free(&msg_ps->outvb);
/* we send invb back */
msg_ps->outvb = msg_ps->invb;
msg_ps->invb.head = NULL;
msg_ps->invb.tail = NULL;
msg_ps->invb.count = 0;
msg_ps->error_status = error;
/* error index must be 0 for error too big */
msg_ps->error_index = (error != SNMP_ES_TOOBIG) ? (1 + msg_ps->vb_idx) : 0;
snmp_send_response(msg_ps);
snmp_varbind_list_free(&msg_ps->outvb);
msg_ps->state = SNMP_MSG_EMPTY;
}
static void
snmp_ok_response(struct snmp_msg_pstat *msg_ps)
{
err_t err_ret;
err_ret = snmp_send_response(msg_ps);
if (err_ret == ERR_MEM)
{
/* serious memory problem, can't return tooBig */
}
else
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event = %"S32_F"\n",msg_ps->error_status));
}
/* free varbinds (if available) */
snmp_varbind_list_free(&msg_ps->invb);
snmp_varbind_list_free(&msg_ps->outvb);
msg_ps->state = SNMP_MSG_EMPTY;
}
/**
* Service an internal or external event for SNMP GET.
*
* @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1)
* @param msg_ps points to the assosicated message process state
*/
static void
snmp_msg_get_event(u8_t request_id, struct snmp_msg_pstat *msg_ps)
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_get_event: msg_ps->state==%"U16_F"\n",(u16_t)msg_ps->state));
if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF)
{
struct mib_external_node *en;
struct snmp_name_ptr np;
/* get_object_def() answer*/
en = msg_ps->ext_mib_node;
np = msg_ps->ext_name_ptr;
/* translate answer into a known lifeform */
en->get_object_def_a(request_id, np.ident_len, np.ident, &msg_ps->ext_object_def);
if ((msg_ps->ext_object_def.instance != MIB_OBJECT_NONE) &&
(msg_ps->ext_object_def.access & MIB_ACCESS_READ))
{
msg_ps->state = SNMP_MSG_EXTERNAL_GET_VALUE;
en->get_value_q(request_id, &msg_ps->ext_object_def);
}
else
{
en->get_object_def_pc(request_id, np.ident_len, np.ident);
/* search failed, object id points to unknown object (nosuchname) */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
else if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_VALUE)
{
struct mib_external_node *en;
struct snmp_varbind *vb;
/* get_value() answer */
en = msg_ps->ext_mib_node;
/* allocate output varbind */
vb = (struct snmp_varbind *)memp_malloc(MEMP_SNMP_VARBIND);
if (vb != NULL)
{
vb->next = NULL;
vb->prev = NULL;
/* move name from invb to outvb */
vb->ident = msg_ps->vb_ptr->ident;
vb->ident_len = msg_ps->vb_ptr->ident_len;
/* ensure this memory is refereced once only */
msg_ps->vb_ptr->ident = NULL;
msg_ps->vb_ptr->ident_len = 0;
vb->value_type = msg_ps->ext_object_def.asn_type;
LWIP_ASSERT("invalid length", msg_ps->ext_object_def.v_len <= 0xff);
vb->value_len = (u8_t)msg_ps->ext_object_def.v_len;
if (vb->value_len > 0)
{
LWIP_ASSERT("SNMP_MAX_OCTET_STRING_LEN is configured too low", vb->value_len <= SNMP_MAX_VALUE_SIZE);
vb->value = memp_malloc(MEMP_SNMP_VALUE);
if (vb->value != NULL)
{
en->get_value_a(request_id, &msg_ps->ext_object_def, vb->value_len, vb->value);
snmp_varbind_tail_add(&msg_ps->outvb, vb);
/* search again (if vb_idx < msg_ps->invb.count) */
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
else
{
en->get_value_pc(request_id, &msg_ps->ext_object_def);
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: no variable space\n"));
msg_ps->vb_ptr->ident = vb->ident;
msg_ps->vb_ptr->ident_len = vb->ident_len;
memp_free(MEMP_SNMP_VARBIND, vb);
snmp_error_response(msg_ps,SNMP_ES_TOOBIG);
}
}
else
{
/* vb->value_len == 0, empty value (e.g. empty string) */
en->get_value_a(request_id, &msg_ps->ext_object_def, 0, NULL);
vb->value = NULL;
snmp_varbind_tail_add(&msg_ps->outvb, vb);
/* search again (if vb_idx < msg_ps->invb.count) */
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
}
else
{
en->get_value_pc(request_id, &msg_ps->ext_object_def);
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: no outvb space\n"));
snmp_error_response(msg_ps,SNMP_ES_TOOBIG);
}
}
while ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) &&
(msg_ps->vb_idx < msg_ps->invb.count))
{
struct mib_node *mn;
struct snmp_name_ptr np;
if (msg_ps->vb_idx == 0)
{
msg_ps->vb_ptr = msg_ps->invb.head;
}
else
{
msg_ps->vb_ptr = msg_ps->vb_ptr->next;
}
/** test object identifier for .iso.org.dod.internet prefix */
if (snmp_iso_prefix_tst(msg_ps->vb_ptr->ident_len, msg_ps->vb_ptr->ident))
{
mn = snmp_search_tree((struct mib_node*)&internet, msg_ps->vb_ptr->ident_len - 4,
msg_ps->vb_ptr->ident + 4, &np);
if (mn != NULL)
{
if (mn->node_type == MIB_NODE_EX)
{
/* external object */
struct mib_external_node *en = (struct mib_external_node*)mn;
msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF;
/* save en && args in msg_ps!! */
msg_ps->ext_mib_node = en;
msg_ps->ext_name_ptr = np;
en->get_object_def_q(en->addr_inf, request_id, np.ident_len, np.ident);
}
else
{
/* internal object */
struct obj_def object_def;
msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF;
mn->get_object_def(np.ident_len, np.ident, &object_def);
if ((object_def.instance != MIB_OBJECT_NONE) &&
(object_def.access & MIB_ACCESS_READ))
{
mn = mn;
}
else
{
/* search failed, object id points to unknown object (nosuchname) */
mn = NULL;
}
if (mn != NULL)
{
struct snmp_varbind *vb;
msg_ps->state = SNMP_MSG_INTERNAL_GET_VALUE;
/* allocate output varbind */
vb = (struct snmp_varbind *)memp_malloc(MEMP_SNMP_VARBIND);
if (vb != NULL)
{
vb->next = NULL;
vb->prev = NULL;
/* move name from invb to outvb */
vb->ident = msg_ps->vb_ptr->ident;
vb->ident_len = msg_ps->vb_ptr->ident_len;
/* ensure this memory is refereced once only */
msg_ps->vb_ptr->ident = NULL;
msg_ps->vb_ptr->ident_len = 0;
vb->value_type = object_def.asn_type;
LWIP_ASSERT("invalid length", object_def.v_len <= 0xff);
vb->value_len = (u8_t)object_def.v_len;
if (vb->value_len > 0)
{
LWIP_ASSERT("SNMP_MAX_OCTET_STRING_LEN is configured too low",
vb->value_len <= SNMP_MAX_VALUE_SIZE);
vb->value = memp_malloc(MEMP_SNMP_VALUE);
if (vb->value != NULL)
{
mn->get_value(&object_def, vb->value_len, vb->value);
snmp_varbind_tail_add(&msg_ps->outvb, vb);
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
else
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: couldn't allocate variable space\n"));
msg_ps->vb_ptr->ident = vb->ident;
msg_ps->vb_ptr->ident_len = vb->ident_len;
vb->ident = NULL;
vb->ident_len = 0;
memp_free(MEMP_SNMP_VARBIND, vb);
snmp_error_response(msg_ps,SNMP_ES_TOOBIG);
}
}
else
{
/* vb->value_len == 0, empty value (e.g. empty string) */
vb->value = NULL;
snmp_varbind_tail_add(&msg_ps->outvb, vb);
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
}
else
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_event: couldn't allocate outvb space\n"));
snmp_error_response(msg_ps,SNMP_ES_TOOBIG);
}
}
}
}
}
else
{
mn = NULL;
}
if (mn == NULL)
{
/* mn == NULL, noSuchName */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
if ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) &&
(msg_ps->vb_idx == msg_ps->invb.count))
{
snmp_ok_response(msg_ps);
}
}
/**
* Service an internal or external event for SNMP GETNEXT.
*
* @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1)
* @param msg_ps points to the assosicated message process state
*/
static void
snmp_msg_getnext_event(u8_t request_id, struct snmp_msg_pstat *msg_ps)
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_getnext_event: msg_ps->state==%"U16_F"\n",(u16_t)msg_ps->state));
if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF)
{
struct mib_external_node *en;
/* get_object_def() answer*/
en = msg_ps->ext_mib_node;
/* translate answer into a known lifeform */
en->get_object_def_a(request_id, 1, &msg_ps->ext_oid.id[msg_ps->ext_oid.len - 1], &msg_ps->ext_object_def);
if (msg_ps->ext_object_def.instance != MIB_OBJECT_NONE)
{
msg_ps->state = SNMP_MSG_EXTERNAL_GET_VALUE;
en->get_value_q(request_id, &msg_ps->ext_object_def);
}
else
{
en->get_object_def_pc(request_id, 1, &msg_ps->ext_oid.id[msg_ps->ext_oid.len - 1]);
/* search failed, object id points to unknown object (nosuchname) */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
else if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_VALUE)
{
struct mib_external_node *en;
struct snmp_varbind *vb;
/* get_value() answer */
en = msg_ps->ext_mib_node;
LWIP_ASSERT("invalid length", msg_ps->ext_object_def.v_len <= 0xff);
vb = snmp_varbind_alloc(&msg_ps->ext_oid,
msg_ps->ext_object_def.asn_type,
(u8_t)msg_ps->ext_object_def.v_len);
if (vb != NULL)
{
en->get_value_a(request_id, &msg_ps->ext_object_def, vb->value_len, vb->value);
snmp_varbind_tail_add(&msg_ps->outvb, vb);
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
else
{
en->get_value_pc(request_id, &msg_ps->ext_object_def);
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_getnext_event: couldn't allocate outvb space\n"));
snmp_error_response(msg_ps,SNMP_ES_TOOBIG);
}
}
while ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) &&
(msg_ps->vb_idx < msg_ps->invb.count))
{
struct mib_node *mn;
struct snmp_obj_id oid;
if (msg_ps->vb_idx == 0)
{
msg_ps->vb_ptr = msg_ps->invb.head;
}
else
{
msg_ps->vb_ptr = msg_ps->vb_ptr->next;
}
if (snmp_iso_prefix_expand(msg_ps->vb_ptr->ident_len, msg_ps->vb_ptr->ident, &oid))
{
if (msg_ps->vb_ptr->ident_len > 3)
{
/* can offset ident_len and ident */
mn = snmp_expand_tree((struct mib_node*)&internet,
msg_ps->vb_ptr->ident_len - 4,
msg_ps->vb_ptr->ident + 4, &oid);
}
else
{
/* can't offset ident_len -4, ident + 4 */
mn = snmp_expand_tree((struct mib_node*)&internet, 0, NULL, &oid);
}
}
else
{
mn = NULL;
}
if (mn != NULL)
{
if (mn->node_type == MIB_NODE_EX)
{
/* external object */
struct mib_external_node *en = (struct mib_external_node*)mn;
msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF;
/* save en && args in msg_ps!! */
msg_ps->ext_mib_node = en;
msg_ps->ext_oid = oid;
en->get_object_def_q(en->addr_inf, request_id, 1, &oid.id[oid.len - 1]);
}
else
{
/* internal object */
struct obj_def object_def;
struct snmp_varbind *vb;
msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF;
mn->get_object_def(1, &oid.id[oid.len - 1], &object_def);
LWIP_ASSERT("invalid length", object_def.v_len <= 0xff);
vb = snmp_varbind_alloc(&oid, object_def.asn_type, (u8_t)object_def.v_len);
if (vb != NULL)
{
msg_ps->state = SNMP_MSG_INTERNAL_GET_VALUE;
mn->get_value(&object_def, object_def.v_len, vb->value);
snmp_varbind_tail_add(&msg_ps->outvb, vb);
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
else
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_recv couldn't allocate outvb space\n"));
snmp_error_response(msg_ps,SNMP_ES_TOOBIG);
}
}
}
if (mn == NULL)
{
/* mn == NULL, noSuchName */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
if ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) &&
(msg_ps->vb_idx == msg_ps->invb.count))
{
snmp_ok_response(msg_ps);
}
}
/**
* Service an internal or external event for SNMP SET.
*
* @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1)
* @param msg_ps points to the assosicated message process state
*/
static void
snmp_msg_set_event(u8_t request_id, struct snmp_msg_pstat *msg_ps)
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_msg_set_event: msg_ps->state==%"U16_F"\n",(u16_t)msg_ps->state));
if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF)
{
struct mib_external_node *en;
struct snmp_name_ptr np;
/* get_object_def() answer*/
en = msg_ps->ext_mib_node;
np = msg_ps->ext_name_ptr;
/* translate answer into a known lifeform */
en->get_object_def_a(request_id, np.ident_len, np.ident, &msg_ps->ext_object_def);
if (msg_ps->ext_object_def.instance != MIB_OBJECT_NONE)
{
msg_ps->state = SNMP_MSG_EXTERNAL_SET_TEST;
en->set_test_q(request_id, &msg_ps->ext_object_def);
}
else
{
en->get_object_def_pc(request_id, np.ident_len, np.ident);
/* search failed, object id points to unknown object (nosuchname) */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
else if (msg_ps->state == SNMP_MSG_EXTERNAL_SET_TEST)
{
struct mib_external_node *en;
/* set_test() answer*/
en = msg_ps->ext_mib_node;
if (msg_ps->ext_object_def.access & MIB_ACCESS_WRITE)
{
if ((msg_ps->ext_object_def.asn_type == msg_ps->vb_ptr->value_type) &&
(en->set_test_a(request_id,&msg_ps->ext_object_def,
msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value) != 0))
{
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
else
{
en->set_test_pc(request_id,&msg_ps->ext_object_def);
/* bad value */
snmp_error_response(msg_ps,SNMP_ES_BADVALUE);
}
}
else
{
en->set_test_pc(request_id,&msg_ps->ext_object_def);
/* object not available for set */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
else if (msg_ps->state == SNMP_MSG_EXTERNAL_GET_OBJDEF_S)
{
struct mib_external_node *en;
struct snmp_name_ptr np;
/* get_object_def() answer*/
en = msg_ps->ext_mib_node;
np = msg_ps->ext_name_ptr;
/* translate answer into a known lifeform */
en->get_object_def_a(request_id, np.ident_len, np.ident, &msg_ps->ext_object_def);
if (msg_ps->ext_object_def.instance != MIB_OBJECT_NONE)
{
msg_ps->state = SNMP_MSG_EXTERNAL_SET_VALUE;
en->set_value_q(request_id, &msg_ps->ext_object_def,
msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value);
}
else
{
en->get_object_def_pc(request_id, np.ident_len, np.ident);
/* set_value failed, object has disappeared for some odd reason?? */
snmp_error_response(msg_ps,SNMP_ES_GENERROR);
}
}
else if (msg_ps->state == SNMP_MSG_EXTERNAL_SET_VALUE)
{
struct mib_external_node *en;
/** set_value_a() */
en = msg_ps->ext_mib_node;
en->set_value_a(request_id, &msg_ps->ext_object_def,
msg_ps->vb_ptr->value_len, msg_ps->vb_ptr->value);
/** @todo use set_value_pc() if toobig */
msg_ps->state = SNMP_MSG_INTERNAL_SET_VALUE;
msg_ps->vb_idx += 1;
}
/* test all values before setting */
while ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) &&
(msg_ps->vb_idx < msg_ps->invb.count))
{
struct mib_node *mn;
struct snmp_name_ptr np;
if (msg_ps->vb_idx == 0)
{
msg_ps->vb_ptr = msg_ps->invb.head;
}
else
{
msg_ps->vb_ptr = msg_ps->vb_ptr->next;
}
/** test object identifier for .iso.org.dod.internet prefix */
if (snmp_iso_prefix_tst(msg_ps->vb_ptr->ident_len, msg_ps->vb_ptr->ident))
{
mn = snmp_search_tree((struct mib_node*)&internet, msg_ps->vb_ptr->ident_len - 4,
msg_ps->vb_ptr->ident + 4, &np);
if (mn != NULL)
{
if (mn->node_type == MIB_NODE_EX)
{
/* external object */
struct mib_external_node *en = (struct mib_external_node*)mn;
msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF;
/* save en && args in msg_ps!! */
msg_ps->ext_mib_node = en;
msg_ps->ext_name_ptr = np;
en->get_object_def_q(en->addr_inf, request_id, np.ident_len, np.ident);
}
else
{
/* internal object */
struct obj_def object_def;
msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF;
mn->get_object_def(np.ident_len, np.ident, &object_def);
if (object_def.instance != MIB_OBJECT_NONE)
{
mn = mn;
}
else
{
/* search failed, object id points to unknown object (nosuchname) */
mn = NULL;
}
if (mn != NULL)
{
msg_ps->state = SNMP_MSG_INTERNAL_SET_TEST;
if (object_def.access & MIB_ACCESS_WRITE)
{
if ((object_def.asn_type == msg_ps->vb_ptr->value_type) &&
(mn->set_test(&object_def,msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value) != 0))
{
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
msg_ps->vb_idx += 1;
}
else
{
/* bad value */
snmp_error_response(msg_ps,SNMP_ES_BADVALUE);
}
}
else
{
/* object not available for set */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
}
}
}
else
{
mn = NULL;
}
if (mn == NULL)
{
/* mn == NULL, noSuchName */
snmp_error_response(msg_ps,SNMP_ES_NOSUCHNAME);
}
}
if ((msg_ps->state == SNMP_MSG_SEARCH_OBJ) &&
(msg_ps->vb_idx == msg_ps->invb.count))
{
msg_ps->vb_idx = 0;
msg_ps->state = SNMP_MSG_INTERNAL_SET_VALUE;
}
/* set all values "atomically" (be as "atomic" as possible) */
while ((msg_ps->state == SNMP_MSG_INTERNAL_SET_VALUE) &&
(msg_ps->vb_idx < msg_ps->invb.count))
{
struct mib_node *mn;
struct snmp_name_ptr np;
if (msg_ps->vb_idx == 0)
{
msg_ps->vb_ptr = msg_ps->invb.head;
}
else
{
msg_ps->vb_ptr = msg_ps->vb_ptr->next;
}
/* skip iso prefix test, was done previously while settesting() */
mn = snmp_search_tree((struct mib_node*)&internet, msg_ps->vb_ptr->ident_len - 4,
msg_ps->vb_ptr->ident + 4, &np);
/* check if object is still available
(e.g. external hot-plug thingy present?) */
if (mn != NULL)
{
if (mn->node_type == MIB_NODE_EX)
{
/* external object */
struct mib_external_node *en = (struct mib_external_node*)mn;
msg_ps->state = SNMP_MSG_EXTERNAL_GET_OBJDEF_S;
/* save en && args in msg_ps!! */
msg_ps->ext_mib_node = en;
msg_ps->ext_name_ptr = np;
en->get_object_def_q(en->addr_inf, request_id, np.ident_len, np.ident);
}
else
{
/* internal object */
struct obj_def object_def;
msg_ps->state = SNMP_MSG_INTERNAL_GET_OBJDEF_S;
mn->get_object_def(np.ident_len, np.ident, &object_def);
msg_ps->state = SNMP_MSG_INTERNAL_SET_VALUE;
mn->set_value(&object_def,msg_ps->vb_ptr->value_len,msg_ps->vb_ptr->value);
msg_ps->vb_idx += 1;
}
}
}
if ((msg_ps->state == SNMP_MSG_INTERNAL_SET_VALUE) &&
(msg_ps->vb_idx == msg_ps->invb.count))
{
/* simply echo the input if we can set it
@todo do we need to return the actual value?
e.g. if value is silently modified or behaves sticky? */
msg_ps->outvb = msg_ps->invb;
msg_ps->invb.head = NULL;
msg_ps->invb.tail = NULL;
msg_ps->invb.count = 0;
snmp_ok_response(msg_ps);
}
}
/**
* Handle one internal or external event.
* Called for one async event. (recv external/private answer)
*
* @param request_id identifies requests from 0 to (SNMP_CONCURRENT_REQUESTS-1)
*/
void
snmp_msg_event(u8_t request_id)
{
struct snmp_msg_pstat *msg_ps;
if (request_id < SNMP_CONCURRENT_REQUESTS)
{
msg_ps = &msg_input_list[request_id];
if (msg_ps->rt == SNMP_ASN1_PDU_GET_NEXT_REQ)
{
snmp_msg_getnext_event(request_id, msg_ps);
}
else if (msg_ps->rt == SNMP_ASN1_PDU_GET_REQ)
{
snmp_msg_get_event(request_id, msg_ps);
}
else if(msg_ps->rt == SNMP_ASN1_PDU_SET_REQ)
{
snmp_msg_set_event(request_id, msg_ps);
}
}
}
/* lwIP UDP receive callback function */
static void
snmp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
{
struct snmp_msg_pstat *msg_ps;
u8_t req_idx;
err_t err_ret;
u16_t payload_len = p->tot_len;
u16_t payload_ofs = 0;
u16_t varbind_ofs = 0;
/* suppress unused argument warning */
LWIP_UNUSED_ARG(arg);
/* traverse input message process list, look for SNMP_MSG_EMPTY */
msg_ps = &msg_input_list[0];
req_idx = 0;
while ((req_idx < SNMP_CONCURRENT_REQUESTS) && (msg_ps->state != SNMP_MSG_EMPTY))
{
req_idx++;
msg_ps++;
}
if (req_idx == SNMP_CONCURRENT_REQUESTS)
{
/* exceeding number of concurrent requests */
pbuf_free(p);
return;
}
/* accepting request */
snmp_inc_snmpinpkts();
/* record used 'protocol control block' */
msg_ps->pcb = pcb;
/* source address (network order) */
msg_ps->sip = *addr;
/* source port (host order (lwIP oddity)) */
msg_ps->sp = port;
/* check total length, version, community, pdu type */
err_ret = snmp_pdu_header_check(p, payload_ofs, payload_len, &varbind_ofs, msg_ps);
/* Only accept requests and requests without error (be robust) */
/* Reject response and trap headers or error requests as input! */
if ((err_ret != ERR_OK) ||
((msg_ps->rt != SNMP_ASN1_PDU_GET_REQ) &&
(msg_ps->rt != SNMP_ASN1_PDU_GET_NEXT_REQ) &&
(msg_ps->rt != SNMP_ASN1_PDU_SET_REQ)) ||
((msg_ps->error_status != SNMP_ES_NOERROR) ||
(msg_ps->error_index != 0)) )
{
/* header check failed drop request silently, do not return error! */
pbuf_free(p);
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_pdu_header_check() failed\n"));
return;
}
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_recv ok, community %s\n", msg_ps->community));
/* Builds a list of variable bindings. Copy the varbinds from the pbuf
chain to glue them when these are divided over two or more pbuf's. */
err_ret = snmp_pdu_dec_varbindlist(p, varbind_ofs, &varbind_ofs, msg_ps);
/* we've decoded the incoming message, release input msg now */
pbuf_free(p);
if ((err_ret != ERR_OK) || (msg_ps->invb.count == 0))
{
/* varbind-list decode failed, or varbind list empty.
drop request silently, do not return error!
(errors are only returned for a specific varbind failure) */
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_pdu_dec_varbindlist() failed\n"));
return;
}
msg_ps->error_status = SNMP_ES_NOERROR;
msg_ps->error_index = 0;
/* find object for each variable binding */
msg_ps->state = SNMP_MSG_SEARCH_OBJ;
/* first variable binding from list to inspect */
msg_ps->vb_idx = 0;
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_recv varbind cnt=%"U16_F"\n",(u16_t)msg_ps->invb.count));
/* handle input event and as much objects as possible in one go */
snmp_msg_event(req_idx);
}
/**
* Checks and decodes incoming SNMP message header, logs header errors.
*
* @param p points to pbuf chain of SNMP message (UDP payload)
* @param ofs points to first octet of SNMP message
* @param pdu_len the length of the UDP payload
* @param ofs_ret returns the ofset of the variable bindings
* @param m_stat points to the current message request state return
* @return
* - ERR_OK SNMP header is sane and accepted
* - ERR_ARG SNMP header is either malformed or rejected
*/
static err_t
snmp_pdu_header_check(struct pbuf *p, u16_t ofs, u16_t pdu_len, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat)
{
err_t derr;
u16_t len, ofs_base;
u8_t len_octets;
u8_t type;
s32_t version;
ofs_base = ofs;
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) ||
(pdu_len != (1 + len_octets + len)) ||
(type != (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)))
{
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
ofs += (1 + len_octets);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)))
{
/* can't decode or no integer (version) */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &version);
if (derr != ERR_OK)
{
/* can't decode */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
if (version != 0)
{
/* not version 1 */
snmp_inc_snmpinbadversions();
return ERR_ARG;
}
ofs += (1 + len_octets + len);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR)))
{
/* can't decode or no octet string (community) */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
derr = snmp_asn1_dec_raw(p, ofs + 1 + len_octets, len, SNMP_COMMUNITY_STR_LEN, m_stat->community);
if (derr != ERR_OK)
{
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
/* add zero terminator */
len = ((len < (SNMP_COMMUNITY_STR_LEN))?(len):(SNMP_COMMUNITY_STR_LEN));
m_stat->community[len] = 0;
m_stat->com_strlen = (u8_t)len;
if (strncmp(snmp_publiccommunity, (const char*)m_stat->community, SNMP_COMMUNITY_STR_LEN) != 0)
{
/** @todo: move this if we need to check more names */
snmp_inc_snmpinbadcommunitynames();
snmp_authfail_trap();
return ERR_ARG;
}
ofs += (1 + len_octets + len);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if (derr != ERR_OK)
{
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
switch(type)
{
case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_REQ):
/* GetRequest PDU */
snmp_inc_snmpingetrequests();
derr = ERR_OK;
break;
case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_NEXT_REQ):
/* GetNextRequest PDU */
snmp_inc_snmpingetnexts();
derr = ERR_OK;
break;
case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_GET_RESP):
/* GetResponse PDU */
snmp_inc_snmpingetresponses();
derr = ERR_ARG;
break;
case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_SET_REQ):
/* SetRequest PDU */
snmp_inc_snmpinsetrequests();
derr = ERR_OK;
break;
case (SNMP_ASN1_CONTXT | SNMP_ASN1_CONSTR | SNMP_ASN1_PDU_TRAP):
/* Trap PDU */
snmp_inc_snmpintraps();
derr = ERR_ARG;
break;
default:
snmp_inc_snmpinasnparseerrs();
derr = ERR_ARG;
break;
}
if (derr != ERR_OK)
{
/* unsupported input PDU for this agent (no parse error) */
return ERR_ARG;
}
m_stat->rt = type & 0x1F;
ofs += (1 + len_octets);
if (len != (pdu_len - (ofs - ofs_base)))
{
/* decoded PDU length does not equal actual payload length */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)))
{
/* can't decode or no integer (request ID) */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &m_stat->rid);
if (derr != ERR_OK)
{
/* can't decode */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
ofs += (1 + len_octets + len);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)))
{
/* can't decode or no integer (error-status) */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
/* must be noError (0) for incoming requests.
log errors for mib-2 completeness and for debug purposes */
derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &m_stat->error_status);
if (derr != ERR_OK)
{
/* can't decode */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
switch (m_stat->error_status)
{
case SNMP_ES_TOOBIG:
snmp_inc_snmpintoobigs();
break;
case SNMP_ES_NOSUCHNAME:
snmp_inc_snmpinnosuchnames();
break;
case SNMP_ES_BADVALUE:
snmp_inc_snmpinbadvalues();
break;
case SNMP_ES_READONLY:
snmp_inc_snmpinreadonlys();
break;
case SNMP_ES_GENERROR:
snmp_inc_snmpingenerrs();
break;
}
ofs += (1 + len_octets + len);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG)))
{
/* can't decode or no integer (error-index) */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
/* must be 0 for incoming requests.
decode anyway to catch bad integers (and dirty tricks) */
derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, &m_stat->error_index);
if (derr != ERR_OK)
{
/* can't decode */
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
ofs += (1 + len_octets + len);
*ofs_ret = ofs;
return ERR_OK;
}
static err_t
snmp_pdu_dec_varbindlist(struct pbuf *p, u16_t ofs, u16_t *ofs_ret, struct snmp_msg_pstat *m_stat)
{
err_t derr;
u16_t len, vb_len;
u8_t len_octets;
u8_t type;
/* variable binding list */
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &vb_len);
if ((derr != ERR_OK) ||
(type != (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)))
{
snmp_inc_snmpinasnparseerrs();
return ERR_ARG;
}
ofs += (1 + len_octets);
/* start with empty list */
m_stat->invb.count = 0;
m_stat->invb.head = NULL;
m_stat->invb.tail = NULL;
while (vb_len > 0)
{
struct snmp_obj_id oid, oid_value;
struct snmp_varbind *vb;
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) ||
(type != (SNMP_ASN1_UNIV | SNMP_ASN1_CONSTR | SNMP_ASN1_SEQ)) ||
(len == 0) || (len > vb_len))
{
snmp_inc_snmpinasnparseerrs();
/* free varbinds (if available) */
snmp_varbind_list_free(&m_stat->invb);
return ERR_ARG;
}
ofs += (1 + len_octets);
vb_len -= (1 + len_octets);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if ((derr != ERR_OK) || (type != (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID)))
{
/* can't decode object name length */
snmp_inc_snmpinasnparseerrs();
/* free varbinds (if available) */
snmp_varbind_list_free(&m_stat->invb);
return ERR_ARG;
}
derr = snmp_asn1_dec_oid(p, ofs + 1 + len_octets, len, &oid);
if (derr != ERR_OK)
{
/* can't decode object name */
snmp_inc_snmpinasnparseerrs();
/* free varbinds (if available) */
snmp_varbind_list_free(&m_stat->invb);
return ERR_ARG;
}
ofs += (1 + len_octets + len);
vb_len -= (1 + len_octets + len);
snmp_asn1_dec_type(p, ofs, &type);
derr = snmp_asn1_dec_length(p, ofs+1, &len_octets, &len);
if (derr != ERR_OK)
{
/* can't decode object value length */
snmp_inc_snmpinasnparseerrs();
/* free varbinds (if available) */
snmp_varbind_list_free(&m_stat->invb);
return ERR_ARG;
}
switch (type)
{
case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG):
vb = snmp_varbind_alloc(&oid, type, sizeof(s32_t));
if (vb != NULL)
{
s32_t *vptr = (s32_t*)vb->value;
derr = snmp_asn1_dec_s32t(p, ofs + 1 + len_octets, len, vptr);
snmp_varbind_tail_add(&m_stat->invb, vb);
}
else
{
derr = ERR_ARG;
}
break;
case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER):
case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE):
case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS):
vb = snmp_varbind_alloc(&oid, type, sizeof(u32_t));
if (vb != NULL)
{
u32_t *vptr = (u32_t*)vb->value;
derr = snmp_asn1_dec_u32t(p, ofs + 1 + len_octets, len, vptr);
snmp_varbind_tail_add(&m_stat->invb, vb);
}
else
{
derr = ERR_ARG;
}
break;
case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR):
case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_OPAQUE):
LWIP_ASSERT("invalid length", len <= 0xff);
vb = snmp_varbind_alloc(&oid, type, (u8_t)len);
if (vb != NULL)
{
derr = snmp_asn1_dec_raw(p, ofs + 1 + len_octets, len, vb->value_len, (u8_t*)vb->value);
snmp_varbind_tail_add(&m_stat->invb, vb);
}
else
{
derr = ERR_ARG;
}
break;
case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_NUL):
vb = snmp_varbind_alloc(&oid, type, 0);
if (vb != NULL)
{
snmp_varbind_tail_add(&m_stat->invb, vb);
derr = ERR_OK;
}
else
{
derr = ERR_ARG;
}
break;
case (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID):
derr = snmp_asn1_dec_oid(p, ofs + 1 + len_octets, len, &oid_value);
if (derr == ERR_OK)
{
vb = snmp_varbind_alloc(&oid, type, oid_value.len * sizeof(s32_t));
if (vb != NULL)
{
u8_t i = oid_value.len;
s32_t *vptr = (s32_t*)vb->value;
while(i > 0)
{
i--;
vptr[i] = oid_value.id[i];
}
snmp_varbind_tail_add(&m_stat->invb, vb);
derr = ERR_OK;
}
else
{
derr = ERR_ARG;
}
}
break;
case (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR):
if (len == 4)
{
/* must be exactly 4 octets! */
vb = snmp_varbind_alloc(&oid, type, 4);
if (vb != NULL)
{
derr = snmp_asn1_dec_raw(p, ofs + 1 + len_octets, len, vb->value_len, (u8_t*)vb->value);
snmp_varbind_tail_add(&m_stat->invb, vb);
}
else
{
derr = ERR_ARG;
}
}
else
{
derr = ERR_ARG;
}
break;
default:
derr = ERR_ARG;
break;
}
if (derr != ERR_OK)
{
snmp_inc_snmpinasnparseerrs();
/* free varbinds (if available) */
snmp_varbind_list_free(&m_stat->invb);
return ERR_ARG;
}
ofs += (1 + len_octets + len);
vb_len -= (1 + len_octets + len);
}
if (m_stat->rt == SNMP_ASN1_PDU_SET_REQ)
{
snmp_add_snmpintotalsetvars(m_stat->invb.count);
}
else
{
snmp_add_snmpintotalreqvars(m_stat->invb.count);
}
*ofs_ret = ofs;
return ERR_OK;
}
struct snmp_varbind*
snmp_varbind_alloc(struct snmp_obj_id *oid, u8_t type, u8_t len)
{
struct snmp_varbind *vb;
vb = (struct snmp_varbind *)memp_malloc(MEMP_SNMP_VARBIND);
if (vb != NULL)
{
u8_t i;
vb->next = NULL;
vb->prev = NULL;
i = oid->len;
vb->ident_len = i;
if (i > 0)
{
LWIP_ASSERT("SNMP_MAX_TREE_DEPTH is configured too low", i <= SNMP_MAX_TREE_DEPTH);
/* allocate array of s32_t for our object identifier */
vb->ident = (s32_t*)memp_malloc(MEMP_SNMP_VALUE);
if (vb->ident == NULL)
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_varbind_alloc: couldn't allocate ident value space\n"));
memp_free(MEMP_SNMP_VARBIND, vb);
return NULL;
}
while(i > 0)
{
i--;
vb->ident[i] = oid->id[i];
}
}
else
{
/* i == 0, pass zero length object identifier */
vb->ident = NULL;
}
vb->value_type = type;
vb->value_len = len;
if (len > 0)
{
LWIP_ASSERT("SNMP_MAX_OCTET_STRING_LEN is configured too low", vb->value_len <= SNMP_MAX_VALUE_SIZE);
/* allocate raw bytes for our object value */
vb->value = memp_malloc(MEMP_SNMP_VALUE);
if (vb->value == NULL)
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_varbind_alloc: couldn't allocate value space\n"));
if (vb->ident != NULL)
{
memp_free(MEMP_SNMP_VALUE, vb->ident);
}
memp_free(MEMP_SNMP_VARBIND, vb);
return NULL;
}
}
else
{
/* ASN1_NUL type, or zero length ASN1_OC_STR */
vb->value = NULL;
}
}
else
{
LWIP_DEBUGF(SNMP_MSG_DEBUG, ("snmp_varbind_alloc: couldn't allocate varbind space\n"));
}
return vb;
}
void
snmp_varbind_free(struct snmp_varbind *vb)
{
if (vb->value != NULL )
{
memp_free(MEMP_SNMP_VALUE, vb->value);
}
if (vb->ident != NULL )
{
memp_free(MEMP_SNMP_VALUE, vb->ident);
}
memp_free(MEMP_SNMP_VARBIND, vb);
}
void
snmp_varbind_list_free(struct snmp_varbind_root *root)
{
struct snmp_varbind *vb, *prev;
vb = root->tail;
while ( vb != NULL )
{
prev = vb->prev;
snmp_varbind_free(vb);
vb = prev;
}
root->count = 0;
root->head = NULL;
root->tail = NULL;
}
void
snmp_varbind_tail_add(struct snmp_varbind_root *root, struct snmp_varbind *vb)
{
if (root->count == 0)
{
/* add first varbind to list */
root->head = vb;
root->tail = vb;
}
else
{
/* add nth varbind to list tail */
root->tail->next = vb;
vb->prev = root->tail;
root->tail = vb;
}
root->count += 1;
}
struct snmp_varbind*
snmp_varbind_tail_remove(struct snmp_varbind_root *root)
{
struct snmp_varbind* vb;
if (root->count > 0)
{
/* remove tail varbind */
vb = root->tail;
root->tail = vb->prev;
vb->prev->next = NULL;
root->count -= 1;
}
else
{
/* nothing to remove */
vb = NULL;
}
return vb;
}
#endif /* LWIP_SNMP */
| apache-2.0 |
jferreir/mbed | libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F031K6/TOOLCHAIN_ARM_MICRO/sys.cpp | 3920 | 2466 | /* mbed Microcontroller Library - stackheap
* Setup a fixed single stack/heap memory model,
* between the top of the RW/ZI region and the stackpointer
*******************************************************************************
* Copyright (c) 2014, STMicroelectronics
* 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 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.
*******************************************************************************
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <rt_misc.h>
#include <stdint.h>
extern char Image$$RW_IRAM1$$ZI$$Limit[];
extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) {
uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit;
uint32_t sp_limit = __current_sp();
zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned
struct __initial_stackheap r;
r.heap_base = zi_limit;
r.heap_limit = sp_limit;
return r;
}
#ifdef __cplusplus
}
#endif
| apache-2.0 |
BackupGGCode/python-for-android | python3-alpha/python3-src/Doc/includes/noddy.c | 84 | 1689 | #include <Python.h>
typedef struct {
PyObject_HEAD
/* Type-specific fields go here. */
} noddy_NoddyObject;
static PyTypeObject noddy_NoddyType = {
PyVarObject_HEAD_INIT(NULL, 0)
"noddy.Noddy", /* tp_name */
sizeof(noddy_NoddyObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Noddy objects", /* tp_doc */
};
static PyModuleDef noddymodule = {
PyModuleDef_HEAD_INIT,
"noddy",
"Example module that creates an extension type.",
-1,
NULL, NULL, NULL, NULL, NULL
};
PyMODINIT_FUNC
PyInit_noddy(void)
{
PyObject* m;
noddy_NoddyType.tp_new = PyType_GenericNew;
if (PyType_Ready(&noddy_NoddyType) < 0)
return NULL;
m = PyModule_Create(&noddymodule);
if (m == NULL)
return NULL;
Py_INCREF(&noddy_NoddyType);
PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
return m;
}
| apache-2.0 |
netzimme/mbed-os | targets/TARGET_Freescale/TARGET_MCUXpresso_MCUS/TARGET_K82F/drivers/fsl_flexio_spi_edma.c | 85 | 14393 | /*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of Freescale Semiconductor, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fsl_flexio_spi_edma.h"
/*******************************************************************************
* Definitons
******************************************************************************/
/*<! Structure definition for spi_edma_private_handle_t. The structure is private. */
typedef struct _flexio_spi_master_edma_private_handle
{
FLEXIO_SPI_Type *base;
flexio_spi_master_edma_handle_t *handle;
} flexio_spi_master_edma_private_handle_t;
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief EDMA callback function for FLEXIO SPI send transfer.
*
* @param handle EDMA handle pointer.
* @param param Callback function parameter.
*/
static void FLEXIO_SPI_TxEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds);
/*!
* @brief EDMA callback function for FLEXIO SPI receive transfer.
*
* @param handle EDMA handle pointer.
* @param param Callback function parameter.
*/
static void FLEXIO_SPI_RxEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds);
/*!
* @brief EDMA config for FLEXIO SPI transfer.
*
* @param base pointer to FLEXIO_SPI_Type structure.
* @param handle pointer to flexio_spi_master_edma_handle_t structure to store the transfer state.
* @param xfer Pointer to flexio spi transfer structure.
*/
static void FLEXIO_SPI_EDMAConfig(FLEXIO_SPI_Type *base,
flexio_spi_master_edma_handle_t *handle,
flexio_spi_transfer_t *xfer);
/*******************************************************************************
* Variables
******************************************************************************/
/* Dummy data used to send */
static const uint16_t s_dummyData = FLEXIO_SPI_DUMMYDATA;
/*< @brief user configurable flexio spi handle count. */
#define FLEXIO_SPI_HANDLE_COUNT 2
/*<! Private handle only used for internally. */
static flexio_spi_master_edma_private_handle_t s_edmaPrivateHandle[FLEXIO_SPI_HANDLE_COUNT];
/*******************************************************************************
* Code
******************************************************************************/
static void FLEXIO_SPI_TxEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds)
{
tcds = tcds;
flexio_spi_master_edma_private_handle_t *spiPrivateHandle = (flexio_spi_master_edma_private_handle_t *)param;
/* Disable Tx DMA */
if (transferDone)
{
FLEXIO_SPI_EnableDMA(spiPrivateHandle->base, kFLEXIO_SPI_TxDmaEnable, false);
/* change the state */
spiPrivateHandle->handle->txInProgress = false;
/* All finished, call the callback */
if ((spiPrivateHandle->handle->txInProgress == false) && (spiPrivateHandle->handle->rxInProgress == false))
{
if (spiPrivateHandle->handle->callback)
{
(spiPrivateHandle->handle->callback)(spiPrivateHandle->base, spiPrivateHandle->handle, kStatus_Success,
spiPrivateHandle->handle->userData);
}
}
}
}
static void FLEXIO_SPI_RxEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds)
{
tcds = tcds;
flexio_spi_master_edma_private_handle_t *spiPrivateHandle = (flexio_spi_master_edma_private_handle_t *)param;
if (transferDone)
{
/* Disable Rx dma */
FLEXIO_SPI_EnableDMA(spiPrivateHandle->base, kFLEXIO_SPI_RxDmaEnable, false);
/* change the state */
spiPrivateHandle->handle->rxInProgress = false;
/* All finished, call the callback */
if ((spiPrivateHandle->handle->txInProgress == false) && (spiPrivateHandle->handle->rxInProgress == false))
{
if (spiPrivateHandle->handle->callback)
{
(spiPrivateHandle->handle->callback)(spiPrivateHandle->base, spiPrivateHandle->handle, kStatus_Success,
spiPrivateHandle->handle->userData);
}
}
}
}
static void FLEXIO_SPI_EDMAConfig(FLEXIO_SPI_Type *base,
flexio_spi_master_edma_handle_t *handle,
flexio_spi_transfer_t *xfer)
{
edma_transfer_config_t xferConfig;
flexio_spi_shift_direction_t direction;
uint8_t bytesPerFrame;
/* Configure the values in handle. */
switch (xfer->flags)
{
case kFLEXIO_SPI_8bitMsb:
bytesPerFrame = 1;
direction = kFLEXIO_SPI_MsbFirst;
break;
case kFLEXIO_SPI_8bitLsb:
bytesPerFrame = 1;
direction = kFLEXIO_SPI_LsbFirst;
break;
case kFLEXIO_SPI_16bitMsb:
bytesPerFrame = 2;
direction = kFLEXIO_SPI_MsbFirst;
break;
case kFLEXIO_SPI_16bitLsb:
bytesPerFrame = 2;
direction = kFLEXIO_SPI_LsbFirst;
break;
default:
bytesPerFrame = 1U;
direction = kFLEXIO_SPI_MsbFirst;
assert(true);
break;
}
/* Save total transfer size. */
handle->transferSize = xfer->dataSize;
/* Configure tx transfer EDMA. */
xferConfig.destAddr = FLEXIO_SPI_GetTxDataRegisterAddress(base, direction);
xferConfig.destOffset = 0;
if (bytesPerFrame == 1U)
{
xferConfig.srcTransferSize = kEDMA_TransferSize1Bytes;
xferConfig.destTransferSize = kEDMA_TransferSize1Bytes;
xferConfig.minorLoopBytes = 1;
}
else
{
if (direction == kFLEXIO_SPI_MsbFirst)
{
xferConfig.destAddr -= 1U;
}
xferConfig.srcTransferSize = kEDMA_TransferSize2Bytes;
xferConfig.destTransferSize = kEDMA_TransferSize2Bytes;
xferConfig.minorLoopBytes = 2;
}
/* Configure DMA channel. */
if (xfer->txData)
{
xferConfig.srcOffset = bytesPerFrame;
xferConfig.srcAddr = (uint32_t)(xfer->txData);
}
else
{
/* Disable the source increasement and source set to dummyData. */
xferConfig.srcOffset = 0;
xferConfig.srcAddr = (uint32_t)(&s_dummyData);
}
xferConfig.majorLoopCounts = (xfer->dataSize / xferConfig.minorLoopBytes);
/* Store the initially configured eDMA minor byte transfer count into the FLEXIO SPI handle */
handle->nbytes = xferConfig.minorLoopBytes;
if (handle->txHandle)
{
EDMA_SubmitTransfer(handle->txHandle, &xferConfig);
}
/* Configure tx transfer EDMA. */
if (xfer->rxData)
{
xferConfig.srcAddr = FLEXIO_SPI_GetRxDataRegisterAddress(base, direction);
if (bytesPerFrame == 2U)
{
if (direction == kFLEXIO_SPI_LsbFirst)
{
xferConfig.srcAddr -= 1U;
}
}
xferConfig.srcOffset = 0;
xferConfig.destAddr = (uint32_t)(xfer->rxData);
xferConfig.destOffset = bytesPerFrame;
EDMA_SubmitTransfer(handle->rxHandle, &xferConfig);
handle->rxInProgress = true;
FLEXIO_SPI_EnableDMA(base, kFLEXIO_SPI_RxDmaEnable, true);
EDMA_StartTransfer(handle->rxHandle);
}
/* Always start Tx transfer. */
if (handle->txHandle)
{
handle->txInProgress = true;
FLEXIO_SPI_EnableDMA(base, kFLEXIO_SPI_TxDmaEnable, true);
EDMA_StartTransfer(handle->txHandle);
}
}
status_t FLEXIO_SPI_MasterTransferCreateHandleEDMA(FLEXIO_SPI_Type *base,
flexio_spi_master_edma_handle_t *handle,
flexio_spi_master_edma_transfer_callback_t callback,
void *userData,
edma_handle_t *txHandle,
edma_handle_t *rxHandle)
{
assert(handle);
uint8_t index = 0;
/* Find the an empty handle pointer to store the handle. */
for (index = 0; index < FLEXIO_SPI_HANDLE_COUNT; index++)
{
if (s_edmaPrivateHandle[index].base == NULL)
{
s_edmaPrivateHandle[index].base = base;
s_edmaPrivateHandle[index].handle = handle;
break;
}
}
if (index == FLEXIO_SPI_HANDLE_COUNT)
{
return kStatus_OutOfRange;
}
/* Set spi base to handle. */
handle->txHandle = txHandle;
handle->rxHandle = rxHandle;
/* Register callback and userData. */
handle->callback = callback;
handle->userData = userData;
/* Set SPI state to idle. */
handle->txInProgress = false;
handle->rxInProgress = false;
/* Install callback for Tx/Rx dma channel. */
if (handle->txHandle)
{
EDMA_SetCallback(handle->txHandle, FLEXIO_SPI_TxEDMACallback, &s_edmaPrivateHandle[index]);
}
if (handle->rxHandle)
{
EDMA_SetCallback(handle->rxHandle, FLEXIO_SPI_RxEDMACallback, &s_edmaPrivateHandle[index]);
}
return kStatus_Success;
}
status_t FLEXIO_SPI_MasterTransferEDMA(FLEXIO_SPI_Type *base,
flexio_spi_master_edma_handle_t *handle,
flexio_spi_transfer_t *xfer)
{
assert(handle);
assert(xfer);
uint32_t dataMode = 0;
uint16_t timerCmp = base->flexioBase->TIMCMP[base->timerIndex[0]];
timerCmp &= 0x00FFU;
/* Check if the device is busy. */
if ((handle->txInProgress) || (handle->rxInProgress))
{
return kStatus_FLEXIO_SPI_Busy;
}
/* Check if input parameter invalid. */
if (((xfer->txData == NULL) && (xfer->rxData == NULL)) || (xfer->dataSize == 0U))
{
return kStatus_InvalidArgument;
}
/* configure data mode. */
if ((xfer->flags == kFLEXIO_SPI_8bitMsb) || (xfer->flags == kFLEXIO_SPI_8bitLsb))
{
dataMode = (8 * 2 - 1U) << 8U;
}
else if ((xfer->flags == kFLEXIO_SPI_16bitMsb) || (xfer->flags == kFLEXIO_SPI_16bitLsb))
{
dataMode = (16 * 2 - 1U) << 8U;
}
else
{
dataMode = 8 * 2 - 1U;
}
dataMode |= timerCmp;
base->flexioBase->TIMCMP[base->timerIndex[0]] = dataMode;
FLEXIO_SPI_EDMAConfig(base, handle, xfer);
return kStatus_Success;
}
status_t FLEXIO_SPI_MasterTransferGetCountEDMA(FLEXIO_SPI_Type *base,
flexio_spi_master_edma_handle_t *handle,
size_t *count)
{
assert(handle);
if (!count)
{
return kStatus_InvalidArgument;
}
if (handle->rxInProgress)
{
*count = (handle->transferSize -
(uint32_t)handle->nbytes *
EDMA_GetRemainingMajorLoopCount(handle->rxHandle->base, handle->rxHandle->channel));
}
else
{
*count = (handle->transferSize -
(uint32_t)handle->nbytes *
EDMA_GetRemainingMajorLoopCount(handle->txHandle->base, handle->txHandle->channel));
}
return kStatus_Success;
}
void FLEXIO_SPI_MasterTransferAbortEDMA(FLEXIO_SPI_Type *base, flexio_spi_master_edma_handle_t *handle)
{
assert(handle);
/* Disable dma. */
EDMA_StopTransfer(handle->txHandle);
EDMA_StopTransfer(handle->rxHandle);
/* Disable DMA enable bit. */
FLEXIO_SPI_EnableDMA(base, kFLEXIO_SPI_DmaAllEnable, false);
/* Set the handle state. */
handle->txInProgress = false;
handle->rxInProgress = false;
}
status_t FLEXIO_SPI_SlaveTransferEDMA(FLEXIO_SPI_Type *base,
flexio_spi_slave_edma_handle_t *handle,
flexio_spi_transfer_t *xfer)
{
assert(handle);
assert(xfer);
uint32_t dataMode = 0;
/* Check if the device is busy. */
if ((handle->txInProgress) || (handle->rxInProgress))
{
return kStatus_FLEXIO_SPI_Busy;
}
/* Check if input parameter invalid. */
if (((xfer->txData == NULL) && (xfer->rxData == NULL)) || (xfer->dataSize == 0U))
{
return kStatus_InvalidArgument;
}
/* configure data mode. */
if ((xfer->flags == kFLEXIO_SPI_8bitMsb) || (xfer->flags == kFLEXIO_SPI_8bitLsb))
{
dataMode = 8 * 2 - 1U;
}
else if ((xfer->flags == kFLEXIO_SPI_16bitMsb) || (xfer->flags == kFLEXIO_SPI_16bitLsb))
{
dataMode = 16 * 2 - 1U;
}
else
{
dataMode = 8 * 2 - 1U;
}
base->flexioBase->TIMCMP[base->timerIndex[0]] = dataMode;
FLEXIO_SPI_EDMAConfig(base, handle, xfer);
return kStatus_Success;
}
| apache-2.0 |
m0ppers/arangodb | 3rdParty/boost/1.61.0/tools/build/src/engine/boehm_gc/pthread_support.c | 88 | 45156 | /*
* Copyright (c) 1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1996 by Silicon Graphics. All rights reserved.
* Copyright (c) 1998 by Fergus Henderson. All rights reserved.
* Copyright (c) 2000-2005 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
/*
* Support code originally for LinuxThreads, the clone()-based kernel
* thread package for Linux which is included in libc6.
*
* This code no doubt makes some assumptions beyond what is
* guaranteed by the pthread standard, though it now does
* very little of that. It now also supports NPTL, and many
* other Posix thread implementations. We are trying to merge
* all flavors of pthread dupport code into this file.
*/
/* DG/UX ix86 support <takis@xfree86.org> */
/*
* Linux_threads.c now also includes some code to support HPUX and
* OSF1 (Compaq Tru64 Unix, really). The OSF1 support is based on Eric Benson's
* patch.
*
* Eric also suggested an alternate basis for a lock implementation in
* his code:
* + #elif defined(OSF1)
* + unsigned long GC_allocate_lock = 0;
* + msemaphore GC_allocate_semaphore;
* + # define GC_TRY_LOCK() \
* + ((msem_lock(&GC_allocate_semaphore, MSEM_IF_NOWAIT) == 0) \
* + ? (GC_allocate_lock = 1) \
* + : 0)
* + # define GC_LOCK_TAKEN GC_allocate_lock
*/
/*#define DEBUG_THREADS 1*/
# include "private/pthread_support.h"
# if defined(GC_PTHREADS) && !defined(GC_WIN32_THREADS)
# if defined(GC_DGUX386_THREADS) && !defined(_POSIX4A_DRAFT10_SOURCE)
# define _POSIX4A_DRAFT10_SOURCE 1
# endif
# if defined(GC_DGUX386_THREADS) && !defined(_USING_POSIX4A_DRAFT10)
# define _USING_POSIX4A_DRAFT10 1
# endif
# include <stdlib.h>
# include <pthread.h>
# include <sched.h>
# include <time.h>
# include <errno.h>
# include <unistd.h>
# include <sys/mman.h>
# include <sys/time.h>
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <signal.h>
# include "gc_inline.h"
#if defined(GC_DARWIN_THREADS)
# include "private/darwin_semaphore.h"
#else
# include <semaphore.h>
#endif /* !GC_DARWIN_THREADS */
#if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS)
# include <sys/sysctl.h>
#endif /* GC_DARWIN_THREADS */
#if defined(GC_NETBSD_THREADS)
# include <sys/param.h>
# include <sys/sysctl.h>
#endif /* GC_NETBSD_THREADS */
/* Allocator lock definitions. */
#if !defined(USE_SPIN_LOCK)
pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER;
#endif
unsigned long GC_lock_holder = NO_THREAD;
/* Used only for assertions, and to prevent */
/* recursive reentry in the system call wrapper. */
#if defined(GC_DGUX386_THREADS)
# include <sys/dg_sys_info.h>
# include <sys/_int_psem.h>
/* sem_t is an uint in DG/UX */
typedef unsigned int sem_t;
#endif /* GC_DGUX386_THREADS */
#ifndef __GNUC__
# define __inline__
#endif
/* Undefine macros used to redirect pthread primitives. */
# undef pthread_create
# if !defined(GC_DARWIN_THREADS)
# undef pthread_sigmask
# endif
# undef pthread_join
# undef pthread_detach
# if defined(GC_OSF1_THREADS) && defined(_PTHREAD_USE_MANGLED_NAMES_) \
&& !defined(_PTHREAD_USE_PTDNAM_)
/* Restore the original mangled names on Tru64 UNIX. */
# define pthread_create __pthread_create
# define pthread_join __pthread_join
# define pthread_detach __pthread_detach
# endif
#ifdef GC_USE_LD_WRAP
# define WRAP_FUNC(f) __wrap_##f
# define REAL_FUNC(f) __real_##f
#else
# ifdef GC_USE_DLOPEN_WRAP
# include <dlfcn.h>
# define WRAP_FUNC(f) f
# define REAL_FUNC(f) GC_real_##f
/* We define both GC_f and plain f to be the wrapped function. */
/* In that way plain calls work, as do calls from files that */
/* included gc.h, wich redefined f to GC_f. */
/* FIXME: Needs work for DARWIN and True64 (OSF1) */
typedef int (* GC_pthread_create_t)(pthread_t *, const pthread_attr_t *,
void * (*)(void *), void *);
static GC_pthread_create_t GC_real_pthread_create;
typedef int (* GC_pthread_sigmask_t)(int, const sigset_t *, sigset_t *);
static GC_pthread_sigmask_t GC_real_pthread_sigmask;
typedef int (* GC_pthread_join_t)(pthread_t, void **);
static GC_pthread_join_t GC_real_pthread_join;
typedef int (* GC_pthread_detach_t)(pthread_t);
static GC_pthread_detach_t GC_real_pthread_detach;
# else
# define WRAP_FUNC(f) GC_##f
# if !defined(GC_DGUX386_THREADS)
# define REAL_FUNC(f) f
# else /* GC_DGUX386_THREADS */
# define REAL_FUNC(f) __d10_##f
# endif /* GC_DGUX386_THREADS */
# endif
#endif
#if defined(GC_USE_DL_WRAP) || defined(GC_USE_DLOPEN_WRAP)
/* Define GC_ functions as aliases for the plain ones, which will */
/* be intercepted. This allows files which include gc.h, and hence */
/* generate referemces to the GC_ symbols, to see the right symbols. */
int GC_pthread_create(pthread_t * t, const pthread_attr_t * a,
void * (* fn)(void *), void * arg) {
return pthread_create(t, a, fn, arg);
}
int GC_pthread_sigmask(int how, const sigset_t *mask, sigset_t *old) {
return pthread_sigmask(how, mask, old);
}
int GC_pthread_join(pthread_t t, void **res) {
return pthread_join(t, res);
}
int GC_pthread_detach(pthread_t t) {
return pthread_detach(t);
}
#endif /* Linker-based interception. */
#ifdef GC_USE_DLOPEN_WRAP
static GC_bool GC_syms_initialized = FALSE;
void GC_init_real_syms(void)
{
void *dl_handle;
# define LIBPTHREAD_NAME "libpthread.so.0"
# define LIBPTHREAD_NAME_LEN 16 /* incl. trailing 0 */
size_t len = LIBPTHREAD_NAME_LEN - 1;
char namebuf[LIBPTHREAD_NAME_LEN];
static char *libpthread_name = LIBPTHREAD_NAME;
if (GC_syms_initialized) return;
# ifdef RTLD_NEXT
dl_handle = RTLD_NEXT;
# else
dl_handle = dlopen(libpthread_name, RTLD_LAZY);
if (NULL == dl_handle) {
while (isdigit(libpthread_name[len-1])) --len;
if (libpthread_name[len-1] == '.') --len;
memcpy(namebuf, libpthread_name, len);
namebuf[len] = '\0';
dl_handle = dlopen(namebuf, RTLD_LAZY);
}
if (NULL == dl_handle) ABORT("Couldn't open libpthread\n");
# endif
GC_real_pthread_create = (GC_pthread_create_t)
dlsym(dl_handle, "pthread_create");
GC_real_pthread_sigmask = (GC_pthread_sigmask_t)
dlsym(dl_handle, "pthread_sigmask");
GC_real_pthread_join = (GC_pthread_join_t)
dlsym(dl_handle, "pthread_join");
GC_real_pthread_detach = (GC_pthread_detach_t)
dlsym(dl_handle, "pthread_detach");
GC_syms_initialized = TRUE;
}
# define INIT_REAL_SYMS() if (!GC_syms_initialized) GC_init_real_syms();
#else
# define INIT_REAL_SYMS()
#endif
void GC_thr_init(void);
static GC_bool parallel_initialized = FALSE;
GC_bool GC_need_to_lock = FALSE;
void GC_init_parallel(void);
long GC_nprocs = 1; /* Number of processors. We may not have */
/* access to all of them, but this is as good */
/* a guess as any ... */
#ifdef THREAD_LOCAL_ALLOC
/* We must explicitly mark ptrfree and gcj free lists, since the free */
/* list links wouldn't otherwise be found. We also set them in the */
/* normal free lists, since that involves touching less memory than if */
/* we scanned them normally. */
void GC_mark_thread_local_free_lists(void)
{
int i;
GC_thread p;
for (i = 0; i < THREAD_TABLE_SZ; ++i) {
for (p = GC_threads[i]; 0 != p; p = p -> next) {
GC_mark_thread_local_fls_for(&(p->tlfs));
}
}
}
#if defined(GC_ASSERTIONS)
/* Check that all thread-local free-lists are completely marked. */
/* also check that thread-specific-data structures are marked. */
void GC_check_tls(void) {
int i;
GC_thread p;
for (i = 0; i < THREAD_TABLE_SZ; ++i) {
for (p = GC_threads[i]; 0 != p; p = p -> next) {
GC_check_tls_for(&(p->tlfs));
}
}
# if defined(USE_CUSTOM_SPECIFIC)
if (GC_thread_key != 0)
GC_check_tsd_marks(GC_thread_key);
# endif
}
#endif /* GC_ASSERTIONS */
#endif /* Thread_local_alloc */
#ifdef PARALLEL_MARK
# ifndef MAX_MARKERS
# define MAX_MARKERS 16
# endif
static ptr_t marker_sp[MAX_MARKERS] = {0};
#ifdef IA64
static ptr_t marker_bsp[MAX_MARKERS] = {0};
#endif
void * GC_mark_thread(void * id)
{
word my_mark_no = 0;
marker_sp[(word)id] = GC_approx_sp();
# ifdef IA64
marker_bsp[(word)id] = GC_save_regs_in_stack();
# endif
for (;; ++my_mark_no) {
/* GC_mark_no is passed only to allow GC_help_marker to terminate */
/* promptly. This is important if it were called from the signal */
/* handler or from the GC lock acquisition code. Under Linux, it's */
/* not safe to call it from a signal handler, since it uses mutexes */
/* and condition variables. Since it is called only here, the */
/* argument is unnecessary. */
if (my_mark_no < GC_mark_no || my_mark_no > GC_mark_no + 2) {
/* resynchronize if we get far off, e.g. because GC_mark_no */
/* wrapped. */
my_mark_no = GC_mark_no;
}
# ifdef DEBUG_THREADS
GC_printf("Starting mark helper for mark number %lu\n", my_mark_no);
# endif
GC_help_marker(my_mark_no);
}
}
extern long GC_markers; /* Number of mark threads we would */
/* like to have. Includes the */
/* initiating thread. */
pthread_t GC_mark_threads[MAX_MARKERS];
#define PTHREAD_CREATE REAL_FUNC(pthread_create)
static void start_mark_threads(void)
{
unsigned i;
pthread_attr_t attr;
if (GC_markers > MAX_MARKERS) {
WARN("Limiting number of mark threads\n", 0);
GC_markers = MAX_MARKERS;
}
if (0 != pthread_attr_init(&attr)) ABORT("pthread_attr_init failed");
if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
ABORT("pthread_attr_setdetachstate failed");
# if defined(HPUX) || defined(GC_DGUX386_THREADS)
/* Default stack size is usually too small: fix it. */
/* Otherwise marker threads or GC may run out of */
/* space. */
# define MIN_STACK_SIZE (8*HBLKSIZE*sizeof(word))
{
size_t old_size;
int code;
if (pthread_attr_getstacksize(&attr, &old_size) != 0)
ABORT("pthread_attr_getstacksize failed\n");
if (old_size < MIN_STACK_SIZE) {
if (pthread_attr_setstacksize(&attr, MIN_STACK_SIZE) != 0)
ABORT("pthread_attr_setstacksize failed\n");
}
}
# endif /* HPUX || GC_DGUX386_THREADS */
if (GC_print_stats) {
GC_log_printf("Starting %ld marker threads\n", GC_markers - 1);
}
for (i = 0; i < GC_markers - 1; ++i) {
if (0 != PTHREAD_CREATE(GC_mark_threads + i, &attr,
GC_mark_thread, (void *)(word)i)) {
WARN("Marker thread creation failed, errno = %ld.\n", errno);
}
}
}
#endif /* PARALLEL_MARK */
GC_bool GC_thr_initialized = FALSE;
volatile GC_thread GC_threads[THREAD_TABLE_SZ];
void GC_push_thread_structures(void)
{
GC_ASSERT(I_HOLD_LOCK());
GC_push_all((ptr_t)(GC_threads), (ptr_t)(GC_threads)+sizeof(GC_threads));
# if defined(THREAD_LOCAL_ALLOC)
GC_push_all((ptr_t)(&GC_thread_key),
(ptr_t)(&GC_thread_key)+sizeof(&GC_thread_key));
# endif
}
/* It may not be safe to allocate when we register the first thread. */
static struct GC_Thread_Rep first_thread;
/* Add a thread to GC_threads. We assume it wasn't already there. */
/* Caller holds allocation lock. */
GC_thread GC_new_thread(pthread_t id)
{
int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
GC_thread result;
static GC_bool first_thread_used = FALSE;
GC_ASSERT(I_HOLD_LOCK());
if (!first_thread_used) {
result = &first_thread;
first_thread_used = TRUE;
} else {
result = (struct GC_Thread_Rep *)
GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
GC_ASSERT(result -> flags == 0);
}
if (result == 0) return(0);
result -> id = id;
result -> next = GC_threads[hv];
GC_threads[hv] = result;
GC_ASSERT(result -> flags == 0 && result -> thread_blocked == 0);
return(result);
}
/* Delete a thread from GC_threads. We assume it is there. */
/* (The code intentionally traps if it wasn't.) */
void GC_delete_thread(pthread_t id)
{
int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
register GC_thread p = GC_threads[hv];
register GC_thread prev = 0;
GC_ASSERT(I_HOLD_LOCK());
while (!THREAD_EQUAL(p -> id, id)) {
prev = p;
p = p -> next;
}
if (prev == 0) {
GC_threads[hv] = p -> next;
} else {
prev -> next = p -> next;
}
# ifdef GC_DARWIN_THREADS
mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
# endif
GC_INTERNAL_FREE(p);
}
/* If a thread has been joined, but we have not yet */
/* been notified, then there may be more than one thread */
/* in the table with the same pthread id. */
/* This is OK, but we need a way to delete a specific one. */
void GC_delete_gc_thread(GC_thread gc_id)
{
pthread_t id = gc_id -> id;
int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
register GC_thread p = GC_threads[hv];
register GC_thread prev = 0;
GC_ASSERT(I_HOLD_LOCK());
while (p != gc_id) {
prev = p;
p = p -> next;
}
if (prev == 0) {
GC_threads[hv] = p -> next;
} else {
prev -> next = p -> next;
}
# ifdef GC_DARWIN_THREADS
mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
# endif
GC_INTERNAL_FREE(p);
}
/* Return a GC_thread corresponding to a given pthread_t. */
/* Returns 0 if it's not there. */
/* Caller holds allocation lock or otherwise inhibits */
/* updates. */
/* If there is more than one thread with the given id we */
/* return the most recent one. */
GC_thread GC_lookup_thread(pthread_t id)
{
int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
register GC_thread p = GC_threads[hv];
while (p != 0 && !THREAD_EQUAL(p -> id, id)) p = p -> next;
return(p);
}
#ifdef HANDLE_FORK
/* Remove all entries from the GC_threads table, except the */
/* one for the current thread. We need to do this in the child */
/* process after a fork(), since only the current thread */
/* survives in the child. */
void GC_remove_all_threads_but_me(void)
{
pthread_t self = pthread_self();
int hv;
GC_thread p, next, me;
for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
me = 0;
for (p = GC_threads[hv]; 0 != p; p = next) {
next = p -> next;
if (THREAD_EQUAL(p -> id, self)) {
me = p;
p -> next = 0;
} else {
# ifdef THREAD_LOCAL_ALLOC
if (!(p -> flags & FINISHED)) {
GC_destroy_thread_local(&(p->tlfs));
}
# endif /* THREAD_LOCAL_ALLOC */
if (p != &first_thread) GC_INTERNAL_FREE(p);
}
}
GC_threads[hv] = me;
}
}
#endif /* HANDLE_FORK */
#ifdef USE_PROC_FOR_LIBRARIES
GC_bool GC_segment_is_thread_stack(ptr_t lo, ptr_t hi)
{
int i;
GC_thread p;
GC_ASSERT(I_HOLD_LOCK());
# ifdef PARALLEL_MARK
for (i = 0; i < GC_markers; ++i) {
if (marker_sp[i] > lo & marker_sp[i] < hi) return TRUE;
# ifdef IA64
if (marker_bsp[i] > lo & marker_bsp[i] < hi) return TRUE;
# endif
}
# endif
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != 0; p = p -> next) {
if (0 != p -> stack_end) {
# ifdef STACK_GROWS_UP
if (p -> stack_end >= lo && p -> stack_end < hi) return TRUE;
# else /* STACK_GROWS_DOWN */
if (p -> stack_end > lo && p -> stack_end <= hi) return TRUE;
# endif
}
}
}
return FALSE;
}
#endif /* USE_PROC_FOR_LIBRARIES */
#ifdef IA64
/* Find the largest stack_base smaller than bound. May be used */
/* to find the boundary between a register stack and adjacent */
/* immediately preceding memory stack. */
ptr_t GC_greatest_stack_base_below(ptr_t bound)
{
int i;
GC_thread p;
ptr_t result = 0;
GC_ASSERT(I_HOLD_LOCK());
# ifdef PARALLEL_MARK
for (i = 0; i < GC_markers; ++i) {
if (marker_sp[i] > result && marker_sp[i] < bound)
result = marker_sp[i];
}
# endif
for (i = 0; i < THREAD_TABLE_SZ; i++) {
for (p = GC_threads[i]; p != 0; p = p -> next) {
if (p -> stack_end > result && p -> stack_end < bound) {
result = p -> stack_end;
}
}
}
return result;
}
#endif /* IA64 */
#ifdef GC_LINUX_THREADS
/* Return the number of processors, or i<= 0 if it can't be determined. */
int GC_get_nprocs(void)
{
/* Should be "return sysconf(_SC_NPROCESSORS_ONLN);" but that */
/* appears to be buggy in many cases. */
/* We look for lines "cpu<n>" in /proc/stat. */
# define STAT_BUF_SIZE 4096
# define STAT_READ read
/* If read is wrapped, this may need to be redefined to call */
/* the real one. */
char stat_buf[STAT_BUF_SIZE];
int f;
word result = 1;
/* Some old kernels only have a single "cpu nnnn ..." */
/* entry in /proc/stat. We identify those as */
/* uniprocessors. */
size_t i, len = 0;
f = open("/proc/stat", O_RDONLY);
if (f < 0 || (len = STAT_READ(f, stat_buf, STAT_BUF_SIZE)) < 100) {
WARN("Couldn't read /proc/stat\n", 0);
return -1;
}
for (i = 0; i < len - 100; ++i) {
if (stat_buf[i] == '\n' && stat_buf[i+1] == 'c'
&& stat_buf[i+2] == 'p' && stat_buf[i+3] == 'u') {
int cpu_no = atoi(stat_buf + i + 4);
if (cpu_no >= result) result = cpu_no + 1;
}
}
close(f);
return result;
}
#endif /* GC_LINUX_THREADS */
/* We hold the GC lock. Wait until an in-progress GC has finished. */
/* Repeatedly RELEASES GC LOCK in order to wait. */
/* If wait_for_all is true, then we exit with the GC lock held and no */
/* collection in progress; otherwise we just wait for the current GC */
/* to finish. */
extern GC_bool GC_collection_in_progress(void);
void GC_wait_for_gc_completion(GC_bool wait_for_all)
{
GC_ASSERT(I_HOLD_LOCK());
if (GC_incremental && GC_collection_in_progress()) {
int old_gc_no = GC_gc_no;
/* Make sure that no part of our stack is still on the mark stack, */
/* since it's about to be unmapped. */
while (GC_incremental && GC_collection_in_progress()
&& (wait_for_all || old_gc_no == GC_gc_no)) {
ENTER_GC();
GC_in_thread_creation = TRUE;
GC_collect_a_little_inner(1);
GC_in_thread_creation = FALSE;
EXIT_GC();
UNLOCK();
sched_yield();
LOCK();
}
}
}
#ifdef HANDLE_FORK
/* Procedures called before and after a fork. The goal here is to make */
/* it safe to call GC_malloc() in a forked child. It's unclear that is */
/* attainable, since the single UNIX spec seems to imply that one */
/* should only call async-signal-safe functions, and we probably can't */
/* quite guarantee that. But we give it our best shot. (That same */
/* spec also implies that it's not safe to call the system malloc */
/* between fork() and exec(). Thus we're doing no worse than it. */
/* Called before a fork() */
void GC_fork_prepare_proc(void)
{
/* Acquire all relevant locks, so that after releasing the locks */
/* the child will see a consistent state in which monitor */
/* invariants hold. Unfortunately, we can't acquire libc locks */
/* we might need, and there seems to be no guarantee that libc */
/* must install a suitable fork handler. */
/* Wait for an ongoing GC to finish, since we can't finish it in */
/* the (one remaining thread in) the child. */
LOCK();
# if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
GC_wait_for_reclaim();
# endif
GC_wait_for_gc_completion(TRUE);
# if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
GC_acquire_mark_lock();
# endif
}
/* Called in parent after a fork() */
void GC_fork_parent_proc(void)
{
# if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
GC_release_mark_lock();
# endif
UNLOCK();
}
/* Called in child after a fork() */
void GC_fork_child_proc(void)
{
/* Clean up the thread table, so that just our thread is left. */
# if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
GC_release_mark_lock();
# endif
GC_remove_all_threads_but_me();
# ifdef PARALLEL_MARK
/* Turn off parallel marking in the child, since we are probably */
/* just going to exec, and we would have to restart mark threads. */
GC_markers = 1;
GC_parallel = FALSE;
# endif /* PARALLEL_MARK */
UNLOCK();
}
#endif /* HANDLE_FORK */
#if defined(GC_DGUX386_THREADS)
/* Return the number of processors, or i<= 0 if it can't be determined. */
int GC_get_nprocs(void)
{
/* <takis@XFree86.Org> */
int numCpus;
struct dg_sys_info_pm_info pm_sysinfo;
int status =0;
status = dg_sys_info((long int *) &pm_sysinfo,
DG_SYS_INFO_PM_INFO_TYPE, DG_SYS_INFO_PM_CURRENT_VERSION);
if (status < 0)
/* set -1 for error */
numCpus = -1;
else
/* Active CPUs */
numCpus = pm_sysinfo.idle_vp_count;
# ifdef DEBUG_THREADS
GC_printf("Number of active CPUs in this system: %d\n", numCpus);
# endif
return(numCpus);
}
#endif /* GC_DGUX386_THREADS */
#if defined(GC_NETBSD_THREADS)
static int get_ncpu(void)
{
int mib[] = {CTL_HW,HW_NCPU};
int res;
size_t len = sizeof(res);
sysctl(mib, sizeof(mib)/sizeof(int), &res, &len, NULL, 0);
return res;
}
#endif /* GC_NETBSD_THREADS */
# if defined(GC_LINUX_THREADS) && defined(INCLUDE_LINUX_THREAD_DESCR)
__thread int dummy_thread_local;
# endif
/* We hold the allocation lock. */
void GC_thr_init(void)
{
# ifndef GC_DARWIN_THREADS
int dummy;
# endif
GC_thread t;
if (GC_thr_initialized) return;
GC_thr_initialized = TRUE;
# ifdef HANDLE_FORK
/* Prepare for a possible fork. */
pthread_atfork(GC_fork_prepare_proc, GC_fork_parent_proc,
GC_fork_child_proc);
# endif /* HANDLE_FORK */
# if defined(INCLUDE_LINUX_THREAD_DESCR)
/* Explicitly register the region including the address */
/* of a thread local variable. This should included thread */
/* locals for the main thread, except for those allocated */
/* in response to dlopen calls. */
{
ptr_t thread_local_addr = (ptr_t)(&dummy_thread_local);
ptr_t main_thread_start, main_thread_end;
if (!GC_enclosing_mapping(thread_local_addr, &main_thread_start,
&main_thread_end)) {
ABORT("Failed to find mapping for main thread thread locals");
}
GC_add_roots_inner(main_thread_start, main_thread_end, FALSE);
}
# endif
/* Add the initial thread, so we can stop it. */
t = GC_new_thread(pthread_self());
# ifdef GC_DARWIN_THREADS
t -> stop_info.mach_thread = mach_thread_self();
# else
t -> stop_info.stack_ptr = (ptr_t)(&dummy);
# endif
t -> flags = DETACHED | MAIN_THREAD;
GC_stop_init();
/* Set GC_nprocs. */
{
char * nprocs_string = GETENV("GC_NPROCS");
GC_nprocs = -1;
if (nprocs_string != NULL) GC_nprocs = atoi(nprocs_string);
}
if (GC_nprocs <= 0) {
# if defined(GC_HPUX_THREADS)
GC_nprocs = pthread_num_processors_np();
# endif
# if defined(GC_OSF1_THREADS) || defined(GC_AIX_THREADS) \
|| defined(GC_SOLARIS_THREADS)
GC_nprocs = sysconf(_SC_NPROCESSORS_ONLN);
if (GC_nprocs <= 0) GC_nprocs = 1;
# endif
# if defined(GC_IRIX_THREADS)
GC_nprocs = sysconf(_SC_NPROC_ONLN);
if (GC_nprocs <= 0) GC_nprocs = 1;
# endif
# if defined(GC_NETBSD_THREADS)
GC_nprocs = get_ncpu();
# endif
# if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS)
int ncpus = 1;
size_t len = sizeof(ncpus);
sysctl((int[2]) {CTL_HW, HW_NCPU}, 2, &ncpus, &len, NULL, 0);
GC_nprocs = ncpus;
# endif
# if defined(GC_LINUX_THREADS) || defined(GC_DGUX386_THREADS)
GC_nprocs = GC_get_nprocs();
# endif
# if defined(GC_GNU_THREADS)
if (GC_nprocs <= 0) GC_nprocs = 1;
# endif
}
if (GC_nprocs <= 0) {
WARN("GC_get_nprocs() returned %ld\n", GC_nprocs);
GC_nprocs = 2;
# ifdef PARALLEL_MARK
GC_markers = 1;
# endif
} else {
# ifdef PARALLEL_MARK
{
char * markers_string = GETENV("GC_MARKERS");
if (markers_string != NULL) {
GC_markers = atoi(markers_string);
} else {
GC_markers = GC_nprocs;
}
}
# endif
}
# ifdef PARALLEL_MARK
if (GC_print_stats) {
GC_log_printf("Number of processors = %ld, "
"number of marker threads = %ld\n", GC_nprocs, GC_markers);
}
if (GC_markers == 1) {
GC_parallel = FALSE;
if (GC_print_stats) {
GC_log_printf(
"Single marker thread, turning off parallel marking\n");
}
} else {
GC_parallel = TRUE;
/* Disable true incremental collection, but generational is OK. */
GC_time_limit = GC_TIME_UNLIMITED;
}
/* If we are using a parallel marker, actually start helper threads. */
if (GC_parallel) start_mark_threads();
# endif
}
/* Perform all initializations, including those that */
/* may require allocation. */
/* Called without allocation lock. */
/* Must be called before a second thread is created. */
/* Did we say it's called without the allocation lock? */
void GC_init_parallel(void)
{
if (parallel_initialized) return;
parallel_initialized = TRUE;
/* GC_init() calls us back, so set flag first. */
if (!GC_is_initialized) GC_init();
/* Initialize thread local free lists if used. */
# if defined(THREAD_LOCAL_ALLOC)
LOCK();
GC_init_thread_local(&(GC_lookup_thread(pthread_self())->tlfs));
UNLOCK();
# endif
}
#if !defined(GC_DARWIN_THREADS)
int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set, sigset_t *oset)
{
sigset_t fudged_set;
INIT_REAL_SYMS();
if (set != NULL && (how == SIG_BLOCK || how == SIG_SETMASK)) {
fudged_set = *set;
sigdelset(&fudged_set, SIG_SUSPEND);
set = &fudged_set;
}
return(REAL_FUNC(pthread_sigmask)(how, set, oset));
}
#endif /* !GC_DARWIN_THREADS */
/* Wrapper for functions that are likely to block for an appreciable */
/* length of time. */
struct blocking_data {
void (*fn)(void *);
void *arg;
};
static void GC_do_blocking_inner(ptr_t data, void * context) {
struct blocking_data * d = (struct blocking_data *) data;
GC_thread me;
LOCK();
me = GC_lookup_thread(pthread_self());
GC_ASSERT(!(me -> thread_blocked));
# ifdef SPARC
me -> stop_info.stack_ptr = GC_save_regs_in_stack();
# elif !defined(GC_DARWIN_THREADS)
me -> stop_info.stack_ptr = GC_approx_sp();
# endif
# ifdef IA64
me -> backing_store_ptr = GC_save_regs_in_stack();
# endif
me -> thread_blocked = TRUE;
/* Save context here if we want to support precise stack marking */
UNLOCK();
(d -> fn)(d -> arg);
LOCK(); /* This will block if the world is stopped. */
me -> thread_blocked = FALSE;
UNLOCK();
}
void GC_do_blocking(void (*fn)(void *), void *arg) {
struct blocking_data my_data;
my_data.fn = fn;
my_data.arg = arg;
GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
}
struct start_info {
void *(*start_routine)(void *);
void *arg;
word flags;
sem_t registered; /* 1 ==> in our thread table, but */
/* parent hasn't yet noticed. */
};
int GC_unregister_my_thread(void)
{
GC_thread me;
LOCK();
/* Wait for any GC that may be marking from our stack to */
/* complete before we remove this thread. */
GC_wait_for_gc_completion(FALSE);
me = GC_lookup_thread(pthread_self());
# if defined(THREAD_LOCAL_ALLOC)
GC_destroy_thread_local(&(me->tlfs));
# endif
if (me -> flags & DETACHED) {
GC_delete_thread(pthread_self());
} else {
me -> flags |= FINISHED;
}
# if defined(THREAD_LOCAL_ALLOC)
GC_remove_specific(GC_thread_key);
# endif
UNLOCK();
return GC_SUCCESS;
}
/* Called at thread exit. */
/* Never called for main thread. That's OK, since it */
/* results in at most a tiny one-time leak. And */
/* linuxthreads doesn't reclaim the main threads */
/* resources or id anyway. */
void GC_thread_exit_proc(void *arg)
{
GC_unregister_my_thread();
}
int WRAP_FUNC(pthread_join)(pthread_t thread, void **retval)
{
int result;
GC_thread thread_gc_id;
INIT_REAL_SYMS();
LOCK();
thread_gc_id = GC_lookup_thread(thread);
/* This is guaranteed to be the intended one, since the thread id */
/* cant have been recycled by pthreads. */
UNLOCK();
result = REAL_FUNC(pthread_join)(thread, retval);
# if defined (GC_FREEBSD_THREADS)
/* On FreeBSD, the wrapped pthread_join() sometimes returns (what
appears to be) a spurious EINTR which caused the test and real code
to gratuitously fail. Having looked at system pthread library source
code, I see how this return code may be generated. In one path of
code, pthread_join() just returns the errno setting of the thread
being joined. This does not match the POSIX specification or the
local man pages thus I have taken the liberty to catch this one
spurious return value properly conditionalized on GC_FREEBSD_THREADS. */
if (result == EINTR) result = 0;
# endif
if (result == 0) {
LOCK();
/* Here the pthread thread id may have been recycled. */
GC_delete_gc_thread(thread_gc_id);
UNLOCK();
}
return result;
}
int
WRAP_FUNC(pthread_detach)(pthread_t thread)
{
int result;
GC_thread thread_gc_id;
INIT_REAL_SYMS();
LOCK();
thread_gc_id = GC_lookup_thread(thread);
UNLOCK();
result = REAL_FUNC(pthread_detach)(thread);
if (result == 0) {
LOCK();
thread_gc_id -> flags |= DETACHED;
/* Here the pthread thread id may have been recycled. */
if (thread_gc_id -> flags & FINISHED) {
GC_delete_gc_thread(thread_gc_id);
}
UNLOCK();
}
return result;
}
GC_bool GC_in_thread_creation = FALSE; /* Protected by allocation lock. */
GC_thread GC_register_my_thread_inner(struct GC_stack_base *sb,
pthread_t my_pthread)
{
GC_thread me;
GC_in_thread_creation = TRUE; /* OK to collect from unknown thread. */
me = GC_new_thread(my_pthread);
GC_in_thread_creation = FALSE;
# ifdef GC_DARWIN_THREADS
me -> stop_info.mach_thread = mach_thread_self();
# else
me -> stop_info.stack_ptr = sb -> mem_base;
# endif
me -> stack_end = sb -> mem_base;
# ifdef IA64
me -> backing_store_end = sb -> reg_base;
# endif /* IA64 */
return me;
}
int GC_register_my_thread(struct GC_stack_base *sb)
{
pthread_t my_pthread = pthread_self();
GC_thread me;
LOCK();
me = GC_lookup_thread(my_pthread);
if (0 == me) {
me = GC_register_my_thread_inner(sb, my_pthread);
me -> flags |= DETACHED;
/* Treat as detached, since we do not need to worry about */
/* pointer results. */
UNLOCK();
return GC_SUCCESS;
} else {
UNLOCK();
return GC_DUPLICATE;
}
}
void * GC_inner_start_routine(struct GC_stack_base *sb, void * arg)
{
struct start_info * si = arg;
void * result;
GC_thread me;
pthread_t my_pthread;
void *(*start)(void *);
void *start_arg;
my_pthread = pthread_self();
# ifdef DEBUG_THREADS
GC_printf("Starting thread 0x%x\n", (unsigned)my_pthread);
GC_printf("pid = %ld\n", (long) getpid());
GC_printf("sp = 0x%lx\n", (long) &arg);
# endif
LOCK();
me = GC_register_my_thread_inner(sb, my_pthread);
me -> flags = si -> flags;
UNLOCK();
start = si -> start_routine;
# ifdef DEBUG_THREADS
GC_printf("start_routine = %p\n", (void *)start);
# endif
start_arg = si -> arg;
sem_post(&(si -> registered)); /* Last action on si. */
/* OK to deallocate. */
pthread_cleanup_push(GC_thread_exit_proc, 0);
# if defined(THREAD_LOCAL_ALLOC)
LOCK();
GC_init_thread_local(&(me->tlfs));
UNLOCK();
# endif
result = (*start)(start_arg);
# if DEBUG_THREADS
GC_printf("Finishing thread 0x%x\n", (unsigned)pthread_self());
# endif
me -> status = result;
pthread_cleanup_pop(1);
/* Cleanup acquires lock, ensuring that we can't exit */
/* while a collection that thinks we're alive is trying to stop */
/* us. */
return(result);
}
void * GC_start_routine(void * arg)
{
# ifdef INCLUDE_LINUX_THREAD_DESCR
struct GC_stack_base sb;
# ifdef REDIRECT_MALLOC
/* GC_get_stack_base may call pthread_getattr_np, which can */
/* unfortunately call realloc, which may allocate from an */
/* unregistered thread. This is unpleasant, since it might */
/* force heap growth. */
GC_disable();
# endif
if (GC_get_stack_base(&sb) != GC_SUCCESS)
ABORT("Failed to get thread stack base.");
# ifdef REDIRECT_MALLOC
GC_enable();
# endif
return GC_inner_start_routine(&sb, arg);
# else
return GC_call_with_stack_base(GC_inner_start_routine, arg);
# endif
}
int
WRAP_FUNC(pthread_create)(pthread_t *new_thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg)
{
int result;
int detachstate;
word my_flags = 0;
struct start_info * si;
/* This is otherwise saved only in an area mmapped by the thread */
/* library, which isn't visible to the collector. */
/* We resist the temptation to muck with the stack size here, */
/* even if the default is unreasonably small. That's the client's */
/* responsibility. */
INIT_REAL_SYMS();
LOCK();
si = (struct start_info *)GC_INTERNAL_MALLOC(sizeof(struct start_info),
NORMAL);
UNLOCK();
if (!parallel_initialized) GC_init_parallel();
if (0 == si) return(ENOMEM);
sem_init(&(si -> registered), 0, 0);
si -> start_routine = start_routine;
si -> arg = arg;
LOCK();
if (!GC_thr_initialized) GC_thr_init();
# ifdef GC_ASSERTIONS
{
size_t stack_size = 0;
if (NULL != attr) {
pthread_attr_getstacksize(attr, &stack_size);
}
if (0 == stack_size) {
pthread_attr_t my_attr;
pthread_attr_init(&my_attr);
pthread_attr_getstacksize(&my_attr, &stack_size);
}
/* On Solaris 10, with default attr initialization, */
/* stack_size remains 0. Fudge it. */
if (0 == stack_size) {
# ifndef SOLARIS
WARN("Failed to get stack size for assertion checking\n", 0);
# endif
stack_size = 1000000;
}
# ifdef PARALLEL_MARK
GC_ASSERT(stack_size >= (8*HBLKSIZE*sizeof(word)));
# else
/* FreeBSD-5.3/Alpha: default pthread stack is 64K, */
/* HBLKSIZE=8192, sizeof(word)=8 */
GC_ASSERT(stack_size >= 65536);
# endif
/* Our threads may need to do some work for the GC. */
/* Ridiculously small threads won't work, and they */
/* probably wouldn't work anyway. */
}
# endif
if (NULL == attr) {
detachstate = PTHREAD_CREATE_JOINABLE;
} else {
pthread_attr_getdetachstate(attr, &detachstate);
}
if (PTHREAD_CREATE_DETACHED == detachstate) my_flags |= DETACHED;
si -> flags = my_flags;
UNLOCK();
# ifdef DEBUG_THREADS
GC_printf("About to start new thread from thread 0x%x\n",
(unsigned)pthread_self());
# endif
GC_need_to_lock = TRUE;
result = REAL_FUNC(pthread_create)(new_thread, attr, GC_start_routine, si);
# ifdef DEBUG_THREADS
GC_printf("Started thread 0x%x\n", (unsigned)(*new_thread));
# endif
/* Wait until child has been added to the thread table. */
/* This also ensures that we hold onto si until the child is done */
/* with it. Thus it doesn't matter whether it is otherwise */
/* visible to the collector. */
if (0 == result) {
while (0 != sem_wait(&(si -> registered))) {
if (EINTR != errno) ABORT("sem_wait failed");
}
}
sem_destroy(&(si -> registered));
LOCK();
GC_INTERNAL_FREE(si);
UNLOCK();
return(result);
}
/* Spend a few cycles in a way that can't introduce contention with */
/* othre threads. */
void GC_pause(void)
{
int i;
# if !defined(__GNUC__) || defined(__INTEL_COMPILER)
volatile word dummy = 0;
# endif
for (i = 0; i < 10; ++i) {
# if defined(__GNUC__) && !defined(__INTEL_COMPILER)
__asm__ __volatile__ (" " : : : "memory");
# else
/* Something that's unlikely to be optimized away. */
GC_noop(++dummy);
# endif
}
}
#define SPIN_MAX 128 /* Maximum number of calls to GC_pause before */
/* give up. */
volatile GC_bool GC_collecting = 0;
/* A hint that we're in the collector and */
/* holding the allocation lock for an */
/* extended period. */
#if !defined(USE_SPIN_LOCK) || defined(PARALLEL_MARK)
/* If we don't want to use the below spinlock implementation, either */
/* because we don't have a GC_test_and_set implementation, or because */
/* we don't want to risk sleeping, we can still try spinning on */
/* pthread_mutex_trylock for a while. This appears to be very */
/* beneficial in many cases. */
/* I suspect that under high contention this is nearly always better */
/* than the spin lock. But it's a bit slower on a uniprocessor. */
/* Hence we still default to the spin lock. */
/* This is also used to acquire the mark lock for the parallel */
/* marker. */
/* Here we use a strict exponential backoff scheme. I don't know */
/* whether that's better or worse than the above. We eventually */
/* yield by calling pthread_mutex_lock(); it never makes sense to */
/* explicitly sleep. */
#define LOCK_STATS
#ifdef LOCK_STATS
unsigned long GC_spin_count = 0;
unsigned long GC_block_count = 0;
unsigned long GC_unlocked_count = 0;
#endif
void GC_generic_lock(pthread_mutex_t * lock)
{
#ifndef NO_PTHREAD_TRYLOCK
unsigned pause_length = 1;
unsigned i;
if (0 == pthread_mutex_trylock(lock)) {
# ifdef LOCK_STATS
++GC_unlocked_count;
# endif
return;
}
for (; pause_length <= SPIN_MAX; pause_length <<= 1) {
for (i = 0; i < pause_length; ++i) {
GC_pause();
}
switch(pthread_mutex_trylock(lock)) {
case 0:
# ifdef LOCK_STATS
++GC_spin_count;
# endif
return;
case EBUSY:
break;
default:
ABORT("Unexpected error from pthread_mutex_trylock");
}
}
#endif /* !NO_PTHREAD_TRYLOCK */
# ifdef LOCK_STATS
++GC_block_count;
# endif
pthread_mutex_lock(lock);
}
#endif /* !USE_SPIN_LOCK || PARALLEL_MARK */
#if defined(USE_SPIN_LOCK)
/* Reasonably fast spin locks. Basically the same implementation */
/* as STL alloc.h. This isn't really the right way to do this. */
/* but until the POSIX scheduling mess gets straightened out ... */
volatile AO_TS_t GC_allocate_lock = 0;
void GC_lock(void)
{
# define low_spin_max 30 /* spin cycles if we suspect uniprocessor */
# define high_spin_max SPIN_MAX /* spin cycles for multiprocessor */
static unsigned spin_max = low_spin_max;
unsigned my_spin_max;
static unsigned last_spins = 0;
unsigned my_last_spins;
int i;
if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
return;
}
my_spin_max = spin_max;
my_last_spins = last_spins;
for (i = 0; i < my_spin_max; i++) {
if (GC_collecting || GC_nprocs == 1) goto yield;
if (i < my_last_spins/2) {
GC_pause();
continue;
}
if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
/*
* got it!
* Spinning worked. Thus we're probably not being scheduled
* against the other process with which we were contending.
* Thus it makes sense to spin longer the next time.
*/
last_spins = i;
spin_max = high_spin_max;
return;
}
}
/* We are probably being scheduled against the other process. Sleep. */
spin_max = low_spin_max;
yield:
for (i = 0;; ++i) {
if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
return;
}
# define SLEEP_THRESHOLD 12
/* Under Linux very short sleeps tend to wait until */
/* the current time quantum expires. On old Linux */
/* kernels nanosleep(<= 2ms) just spins under Linux. */
/* (Under 2.4, this happens only for real-time */
/* processes.) We want to minimize both behaviors */
/* here. */
if (i < SLEEP_THRESHOLD) {
sched_yield();
} else {
struct timespec ts;
if (i > 24) i = 24;
/* Don't wait for more than about 15msecs, even */
/* under extreme contention. */
ts.tv_sec = 0;
ts.tv_nsec = 1 << i;
nanosleep(&ts, 0);
}
}
}
#else /* !USE_SPINLOCK */
void GC_lock(void)
{
#ifndef NO_PTHREAD_TRYLOCK
if (1 == GC_nprocs || GC_collecting) {
pthread_mutex_lock(&GC_allocate_ml);
} else {
GC_generic_lock(&GC_allocate_ml);
}
#else /* !NO_PTHREAD_TRYLOCK */
pthread_mutex_lock(&GC_allocate_ml);
#endif /* !NO_PTHREAD_TRYLOCK */
}
#endif /* !USE_SPINLOCK */
#if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
#ifdef GC_ASSERTIONS
unsigned long GC_mark_lock_holder = NO_THREAD;
#endif
#if 0
/* Ugly workaround for a linux threads bug in the final versions */
/* of glibc2.1. Pthread_mutex_trylock sets the mutex owner */
/* field even when it fails to acquire the mutex. This causes */
/* pthread_cond_wait to die. Remove for glibc2.2. */
/* According to the man page, we should use */
/* PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, but that isn't actually */
/* defined. */
static pthread_mutex_t mark_mutex =
{0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, {0, 0}};
#else
static pthread_mutex_t mark_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
static pthread_cond_t builder_cv = PTHREAD_COND_INITIALIZER;
void GC_acquire_mark_lock(void)
{
/*
if (pthread_mutex_lock(&mark_mutex) != 0) {
ABORT("pthread_mutex_lock failed");
}
*/
GC_generic_lock(&mark_mutex);
# ifdef GC_ASSERTIONS
GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self());
# endif
}
void GC_release_mark_lock(void)
{
GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
# ifdef GC_ASSERTIONS
GC_mark_lock_holder = NO_THREAD;
# endif
if (pthread_mutex_unlock(&mark_mutex) != 0) {
ABORT("pthread_mutex_unlock failed");
}
}
/* Collector must wait for a freelist builders for 2 reasons: */
/* 1) Mark bits may still be getting examined without lock. */
/* 2) Partial free lists referenced only by locals may not be scanned */
/* correctly, e.g. if they contain "pointer-free" objects, since the */
/* free-list link may be ignored. */
void GC_wait_builder(void)
{
GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
# ifdef GC_ASSERTIONS
GC_mark_lock_holder = NO_THREAD;
# endif
if (pthread_cond_wait(&builder_cv, &mark_mutex) != 0) {
ABORT("pthread_cond_wait failed");
}
GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
# ifdef GC_ASSERTIONS
GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self());
# endif
}
void GC_wait_for_reclaim(void)
{
GC_acquire_mark_lock();
while (GC_fl_builder_count > 0) {
GC_wait_builder();
}
GC_release_mark_lock();
}
void GC_notify_all_builder(void)
{
GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
if (pthread_cond_broadcast(&builder_cv) != 0) {
ABORT("pthread_cond_broadcast failed");
}
}
#endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
#ifdef PARALLEL_MARK
static pthread_cond_t mark_cv = PTHREAD_COND_INITIALIZER;
void GC_wait_marker(void)
{
GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
# ifdef GC_ASSERTIONS
GC_mark_lock_holder = NO_THREAD;
# endif
if (pthread_cond_wait(&mark_cv, &mark_mutex) != 0) {
ABORT("pthread_cond_wait failed");
}
GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
# ifdef GC_ASSERTIONS
GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self());
# endif
}
void GC_notify_all_marker(void)
{
if (pthread_cond_broadcast(&mark_cv) != 0) {
ABORT("pthread_cond_broadcast failed");
}
}
#endif /* PARALLEL_MARK */
# endif /* GC_LINUX_THREADS and friends */
| apache-2.0 |
BeATz-UnKNoWN/python-for-android | python-build/openssl/crypto/x509/x509_lu.c | 93 | 14573 | /* crypto/x509/x509_lu.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/lhash.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method)
{
X509_LOOKUP *ret;
ret=(X509_LOOKUP *)OPENSSL_malloc(sizeof(X509_LOOKUP));
if (ret == NULL) return NULL;
ret->init=0;
ret->skip=0;
ret->method=method;
ret->method_data=NULL;
ret->store_ctx=NULL;
if ((method->new_item != NULL) && !method->new_item(ret))
{
OPENSSL_free(ret);
return NULL;
}
return ret;
}
void X509_LOOKUP_free(X509_LOOKUP *ctx)
{
if (ctx == NULL) return;
if ( (ctx->method != NULL) &&
(ctx->method->free != NULL))
ctx->method->free(ctx);
OPENSSL_free(ctx);
}
int X509_LOOKUP_init(X509_LOOKUP *ctx)
{
if (ctx->method == NULL) return 0;
if (ctx->method->init != NULL)
return ctx->method->init(ctx);
else
return 1;
}
int X509_LOOKUP_shutdown(X509_LOOKUP *ctx)
{
if (ctx->method == NULL) return 0;
if (ctx->method->shutdown != NULL)
return ctx->method->shutdown(ctx);
else
return 1;
}
int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
char **ret)
{
if (ctx->method == NULL) return -1;
if (ctx->method->ctrl != NULL)
return ctx->method->ctrl(ctx,cmd,argc,argl,ret);
else
return 1;
}
int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, int type, X509_NAME *name,
X509_OBJECT *ret)
{
if ((ctx->method == NULL) || (ctx->method->get_by_subject == NULL))
return X509_LU_FAIL;
if (ctx->skip) return 0;
return ctx->method->get_by_subject(ctx,type,name,ret);
}
int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, int type, X509_NAME *name,
ASN1_INTEGER *serial, X509_OBJECT *ret)
{
if ((ctx->method == NULL) ||
(ctx->method->get_by_issuer_serial == NULL))
return X509_LU_FAIL;
return ctx->method->get_by_issuer_serial(ctx,type,name,serial,ret);
}
int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, int type,
unsigned char *bytes, int len, X509_OBJECT *ret)
{
if ((ctx->method == NULL) || (ctx->method->get_by_fingerprint == NULL))
return X509_LU_FAIL;
return ctx->method->get_by_fingerprint(ctx,type,bytes,len,ret);
}
int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, int type, char *str, int len,
X509_OBJECT *ret)
{
if ((ctx->method == NULL) || (ctx->method->get_by_alias == NULL))
return X509_LU_FAIL;
return ctx->method->get_by_alias(ctx,type,str,len,ret);
}
static int x509_object_cmp(const X509_OBJECT * const *a, const X509_OBJECT * const *b)
{
int ret;
ret=((*a)->type - (*b)->type);
if (ret) return ret;
switch ((*a)->type)
{
case X509_LU_X509:
ret=X509_subject_name_cmp((*a)->data.x509,(*b)->data.x509);
break;
case X509_LU_CRL:
ret=X509_CRL_cmp((*a)->data.crl,(*b)->data.crl);
break;
default:
/* abort(); */
return 0;
}
return ret;
}
X509_STORE *X509_STORE_new(void)
{
X509_STORE *ret;
if ((ret=(X509_STORE *)OPENSSL_malloc(sizeof(X509_STORE))) == NULL)
return NULL;
ret->objs = sk_X509_OBJECT_new(x509_object_cmp);
ret->cache=1;
ret->get_cert_methods=sk_X509_LOOKUP_new_null();
ret->verify=0;
ret->verify_cb=0;
if ((ret->param = X509_VERIFY_PARAM_new()) == NULL)
return NULL;
ret->get_issuer = 0;
ret->check_issued = 0;
ret->check_revocation = 0;
ret->get_crl = 0;
ret->check_crl = 0;
ret->cert_crl = 0;
ret->cleanup = 0;
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509_STORE, ret, &ret->ex_data))
{
sk_X509_OBJECT_free(ret->objs);
OPENSSL_free(ret);
return NULL;
}
ret->references=1;
return ret;
}
static void cleanup(X509_OBJECT *a)
{
if (a->type == X509_LU_X509)
{
X509_free(a->data.x509);
}
else if (a->type == X509_LU_CRL)
{
X509_CRL_free(a->data.crl);
}
else
{
/* abort(); */
}
OPENSSL_free(a);
}
void X509_STORE_free(X509_STORE *vfy)
{
int i;
STACK_OF(X509_LOOKUP) *sk;
X509_LOOKUP *lu;
if (vfy == NULL)
return;
sk=vfy->get_cert_methods;
for (i=0; i<sk_X509_LOOKUP_num(sk); i++)
{
lu=sk_X509_LOOKUP_value(sk,i);
X509_LOOKUP_shutdown(lu);
X509_LOOKUP_free(lu);
}
sk_X509_LOOKUP_free(sk);
sk_X509_OBJECT_pop_free(vfy->objs, cleanup);
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509_STORE, vfy, &vfy->ex_data);
if (vfy->param)
X509_VERIFY_PARAM_free(vfy->param);
OPENSSL_free(vfy);
}
X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m)
{
int i;
STACK_OF(X509_LOOKUP) *sk;
X509_LOOKUP *lu;
sk=v->get_cert_methods;
for (i=0; i<sk_X509_LOOKUP_num(sk); i++)
{
lu=sk_X509_LOOKUP_value(sk,i);
if (m == lu->method)
{
return lu;
}
}
/* a new one */
lu=X509_LOOKUP_new(m);
if (lu == NULL)
return NULL;
else
{
lu->store_ctx=v;
if (sk_X509_LOOKUP_push(v->get_cert_methods,lu))
return lu;
else
{
X509_LOOKUP_free(lu);
return NULL;
}
}
}
int X509_STORE_get_by_subject(X509_STORE_CTX *vs, int type, X509_NAME *name,
X509_OBJECT *ret)
{
X509_STORE *ctx=vs->ctx;
X509_LOOKUP *lu;
X509_OBJECT stmp,*tmp;
int i,j;
CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
tmp=X509_OBJECT_retrieve_by_subject(ctx->objs,type,name);
CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
if (tmp == NULL)
{
for (i=vs->current_method; i<sk_X509_LOOKUP_num(ctx->get_cert_methods); i++)
{
lu=sk_X509_LOOKUP_value(ctx->get_cert_methods,i);
j=X509_LOOKUP_by_subject(lu,type,name,&stmp);
if (j < 0)
{
vs->current_method=j;
return j;
}
else if (j)
{
tmp= &stmp;
break;
}
}
vs->current_method=0;
if (tmp == NULL)
return 0;
}
/* if (ret->data.ptr != NULL)
X509_OBJECT_free_contents(ret); */
ret->type=tmp->type;
ret->data.ptr=tmp->data.ptr;
X509_OBJECT_up_ref_count(ret);
return 1;
}
int X509_STORE_add_cert(X509_STORE *ctx, X509 *x)
{
X509_OBJECT *obj;
int ret=1;
if (x == NULL) return 0;
obj=(X509_OBJECT *)OPENSSL_malloc(sizeof(X509_OBJECT));
if (obj == NULL)
{
X509err(X509_F_X509_STORE_ADD_CERT,ERR_R_MALLOC_FAILURE);
return 0;
}
obj->type=X509_LU_X509;
obj->data.x509=x;
CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
X509_OBJECT_up_ref_count(obj);
if (X509_OBJECT_retrieve_match(ctx->objs, obj))
{
X509_OBJECT_free_contents(obj);
OPENSSL_free(obj);
X509err(X509_F_X509_STORE_ADD_CERT,X509_R_CERT_ALREADY_IN_HASH_TABLE);
ret=0;
}
else sk_X509_OBJECT_push(ctx->objs, obj);
CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
return ret;
}
int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x)
{
X509_OBJECT *obj;
int ret=1;
if (x == NULL) return 0;
obj=(X509_OBJECT *)OPENSSL_malloc(sizeof(X509_OBJECT));
if (obj == NULL)
{
X509err(X509_F_X509_STORE_ADD_CRL,ERR_R_MALLOC_FAILURE);
return 0;
}
obj->type=X509_LU_CRL;
obj->data.crl=x;
CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
X509_OBJECT_up_ref_count(obj);
if (X509_OBJECT_retrieve_match(ctx->objs, obj))
{
X509_OBJECT_free_contents(obj);
OPENSSL_free(obj);
X509err(X509_F_X509_STORE_ADD_CRL,X509_R_CERT_ALREADY_IN_HASH_TABLE);
ret=0;
}
else sk_X509_OBJECT_push(ctx->objs, obj);
CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
return ret;
}
void X509_OBJECT_up_ref_count(X509_OBJECT *a)
{
switch (a->type)
{
case X509_LU_X509:
CRYPTO_add(&a->data.x509->references,1,CRYPTO_LOCK_X509);
break;
case X509_LU_CRL:
CRYPTO_add(&a->data.crl->references,1,CRYPTO_LOCK_X509_CRL);
break;
}
}
void X509_OBJECT_free_contents(X509_OBJECT *a)
{
switch (a->type)
{
case X509_LU_X509:
X509_free(a->data.x509);
break;
case X509_LU_CRL:
X509_CRL_free(a->data.crl);
break;
}
}
int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, int type,
X509_NAME *name)
{
X509_OBJECT stmp;
X509 x509_s;
X509_CINF cinf_s;
X509_CRL crl_s;
X509_CRL_INFO crl_info_s;
stmp.type=type;
switch (type)
{
case X509_LU_X509:
stmp.data.x509= &x509_s;
x509_s.cert_info= &cinf_s;
cinf_s.subject=name;
break;
case X509_LU_CRL:
stmp.data.crl= &crl_s;
crl_s.crl= &crl_info_s;
crl_info_s.issuer=name;
break;
default:
/* abort(); */
return -1;
}
return sk_X509_OBJECT_find(h,&stmp);
}
X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h, int type,
X509_NAME *name)
{
int idx;
idx = X509_OBJECT_idx_by_subject(h, type, name);
if (idx==-1) return NULL;
return sk_X509_OBJECT_value(h, idx);
}
X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h, X509_OBJECT *x)
{
int idx, i;
X509_OBJECT *obj;
idx = sk_X509_OBJECT_find(h, x);
if (idx == -1) return NULL;
if (x->type != X509_LU_X509) return sk_X509_OBJECT_value(h, idx);
for (i = idx; i < sk_X509_OBJECT_num(h); i++)
{
obj = sk_X509_OBJECT_value(h, i);
if (x509_object_cmp((const X509_OBJECT **)&obj, (const X509_OBJECT **)&x))
return NULL;
if ((x->type != X509_LU_X509) || !X509_cmp(obj->data.x509, x->data.x509))
return obj;
}
return NULL;
}
/* Try to get issuer certificate from store. Due to limitations
* of the API this can only retrieve a single certificate matching
* a given subject name. However it will fill the cache with all
* matching certificates, so we can examine the cache for all
* matches.
*
* Return values are:
* 1 lookup successful.
* 0 certificate not found.
* -1 some other error.
*/
int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x)
{
X509_NAME *xn;
X509_OBJECT obj, *pobj;
int i, ok, idx, ret;
xn=X509_get_issuer_name(x);
ok=X509_STORE_get_by_subject(ctx,X509_LU_X509,xn,&obj);
if (ok != X509_LU_X509)
{
if (ok == X509_LU_RETRY)
{
X509_OBJECT_free_contents(&obj);
X509err(X509_F_X509_STORE_CTX_GET1_ISSUER,X509_R_SHOULD_RETRY);
return -1;
}
else if (ok != X509_LU_FAIL)
{
X509_OBJECT_free_contents(&obj);
/* not good :-(, break anyway */
return -1;
}
return 0;
}
/* If certificate matches all OK */
if (ctx->check_issued(ctx, x, obj.data.x509))
{
*issuer = obj.data.x509;
return 1;
}
X509_OBJECT_free_contents(&obj);
/* Else find index of first cert accepted by 'check_issued' */
ret = 0;
CRYPTO_w_lock(CRYPTO_LOCK_X509_STORE);
idx = X509_OBJECT_idx_by_subject(ctx->ctx->objs, X509_LU_X509, xn);
if (idx != -1) /* should be true as we've had at least one match */
{
/* Look through all matching certs for suitable issuer */
for (i = idx; i < sk_X509_OBJECT_num(ctx->ctx->objs); i++)
{
pobj = sk_X509_OBJECT_value(ctx->ctx->objs, i);
/* See if we've run past the matches */
if (pobj->type != X509_LU_X509)
break;
if (X509_NAME_cmp(xn, X509_get_subject_name(pobj->data.x509)))
break;
if (ctx->check_issued(ctx, x, pobj->data.x509))
{
*issuer = pobj->data.x509;
X509_OBJECT_up_ref_count(pobj);
ret = 1;
break;
}
}
}
CRYPTO_w_unlock(CRYPTO_LOCK_X509_STORE);
return ret;
}
int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags)
{
return X509_VERIFY_PARAM_set_flags(ctx->param, flags);
}
int X509_STORE_set_depth(X509_STORE *ctx, int depth)
{
X509_VERIFY_PARAM_set_depth(ctx->param, depth);
return 1;
}
int X509_STORE_set_purpose(X509_STORE *ctx, int purpose)
{
return X509_VERIFY_PARAM_set_purpose(ctx->param, purpose);
}
int X509_STORE_set_trust(X509_STORE *ctx, int trust)
{
return X509_VERIFY_PARAM_set_trust(ctx->param, trust);
}
int X509_STORE_set1_param(X509_STORE *ctx, X509_VERIFY_PARAM *param)
{
return X509_VERIFY_PARAM_set1(ctx->param, param);
}
IMPLEMENT_STACK_OF(X509_LOOKUP)
IMPLEMENT_STACK_OF(X509_OBJECT)
| apache-2.0 |
OmniEvo/omnievo_kernel_moto_shamu | drivers/staging/frontier/tranzport.c | 2144 | 26524 | /*
* Frontier Designs Tranzport driver
*
* Copyright (C) 2007 Michael Taht (m@taht.net)
*
* Based on the usbled driver and ldusb drivers by
*
* Copyright (C) 2004 Greg Kroah-Hartman (greg@kroah.com)
* Copyright (C) 2005 Michael Hund <mhund@ld-didactic.de>
*
* The ldusb driver was, in turn, derived from Lego USB Tower driver
* Copyright (C) 2003 David Glance <advidgsf@sourceforge.net>
* 2001-2004 Juergen Stuber <starblue@users.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, version 2.
*
*/
/*
* This driver uses a ring buffer for time critical reading of
* interrupt in reports and provides read and write methods for
* raw interrupt reports.
*/
/* Note: this currently uses a dumb ringbuffer for reads and writes.
* A more optimal driver would cache and kill off outstanding urbs that are
* now invalid, and ignore ones that already were in the queue but valid
* as we only have 17 commands for the tranzport. In particular this is
* key for getting lights to flash in time as otherwise many commands
* can be buffered up before the light change makes it to the interface.
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/uaccess.h>
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/poll.h>
/* Define these values to match your devices */
#define VENDOR_ID 0x165b
#define PRODUCT_ID 0x8101
#ifdef CONFIG_USB_DYNAMIC_MINORS
#define USB_TRANZPORT_MINOR_BASE 0
#else /* FIXME 177- is the another driver's minor - apply for a minor soon */
#define USB_TRANZPORT_MINOR_BASE 177
#endif
/* table of devices that work with this driver */
static const struct usb_device_id usb_tranzport_table[] = {
{USB_DEVICE(VENDOR_ID, PRODUCT_ID)},
{} /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usb_tranzport_table);
MODULE_VERSION("0.35");
MODULE_AUTHOR("Mike Taht <m@taht.net>");
MODULE_DESCRIPTION("Tranzport USB Driver");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("Frontier Designs Tranzport Control Surface");
#define SUPPRESS_EXTRA_OFFLINE_EVENTS 1
#define COMPRESS_WHEEL_EVENTS 1
#define BUFFERED_READS 1
#define RING_BUFFER_SIZE 1000
#define WRITE_BUFFER_SIZE 34
#define TRANZPORT_USB_TIMEOUT 10
#define TRANZPORT_DEBUG 0
static int debug = TRANZPORT_DEBUG;
/* Use our own dbg macro */
#define dbg_info(dev, format, arg...) do \
{ if (debug) dev_info(dev , format , ## arg); } while (0)
/* Module parameters */
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
/* All interrupt in transfers are collected in a ring buffer to
* avoid racing conditions and get better performance of the driver.
*/
static int ring_buffer_size = RING_BUFFER_SIZE;
module_param(ring_buffer_size, int, S_IRUGO);
MODULE_PARM_DESC(ring_buffer_size, "Read ring buffer size in reports");
/* The write_buffer can one day contain more than one interrupt out transfer.
*/
static int write_buffer_size = WRITE_BUFFER_SIZE;
module_param(write_buffer_size, int, S_IRUGO);
MODULE_PARM_DESC(write_buffer_size, "Write buffer size");
/*
* Increase the interval for debugging purposes.
* or set to 1 to use the standard interval from the endpoint descriptors.
*/
static int min_interrupt_in_interval = TRANZPORT_USB_TIMEOUT;
module_param(min_interrupt_in_interval, int, 0);
MODULE_PARM_DESC(min_interrupt_in_interval,
"Minimum interrupt in interval in ms");
static int min_interrupt_out_interval = TRANZPORT_USB_TIMEOUT;
module_param(min_interrupt_out_interval, int, 0);
MODULE_PARM_DESC(min_interrupt_out_interval,
"Minimum interrupt out interval in ms");
struct tranzport_cmd {
unsigned char cmd[8];
};
/* Structure to hold all of our device specific stuff */
struct usb_tranzport {
struct mutex mtx; /* locks this structure */
struct usb_interface *intf; /* save off the usb interface pointer */
int open_count; /* number of times this port opened */
struct tranzport_cmd (*ring_buffer)[RING_BUFFER_SIZE];
unsigned int ring_head;
unsigned int ring_tail;
wait_queue_head_t read_wait;
wait_queue_head_t write_wait;
unsigned char *interrupt_in_buffer;
struct usb_endpoint_descriptor *interrupt_in_endpoint;
struct urb *interrupt_in_urb;
int interrupt_in_interval;
size_t interrupt_in_endpoint_size;
int interrupt_in_running;
int interrupt_in_done;
char *interrupt_out_buffer;
struct usb_endpoint_descriptor *interrupt_out_endpoint;
struct urb *interrupt_out_urb;
int interrupt_out_interval;
size_t interrupt_out_endpoint_size;
int interrupt_out_busy;
/* Sysfs support */
unsigned char enable; /* 0 if disabled 1 if enabled */
unsigned char offline; /* if the device is out of range or asleep */
unsigned char compress_wheel; /* flag to compress wheel events */
};
/* prevent races between open() and disconnect() */
static DEFINE_MUTEX(disconnect_mutex);
static struct usb_driver usb_tranzport_driver;
/**
* usb_tranzport_abort_transfers
* aborts transfers and frees associated data structures
*/
static void usb_tranzport_abort_transfers(struct usb_tranzport *dev)
{
/* shutdown transfer */
if (dev->interrupt_in_running) {
dev->interrupt_in_running = 0;
if (dev->intf)
usb_kill_urb(dev->interrupt_in_urb);
}
if (dev->interrupt_out_busy)
if (dev->intf)
usb_kill_urb(dev->interrupt_out_urb);
}
#define show_int(value) \
static ssize_t show_##value(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct usb_interface *intf = to_usb_interface(dev); \
struct usb_tranzport *t = usb_get_intfdata(intf); \
return sprintf(buf, "%d\n", t->value); \
} \
static DEVICE_ATTR(value, S_IRUGO, show_##value, NULL);
#define show_set_int(value) \
static ssize_t show_##value(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct usb_interface *intf = to_usb_interface(dev); \
struct usb_tranzport *t = usb_get_intfdata(intf); \
return sprintf(buf, "%d\n", t->value); \
} \
static ssize_t set_##value(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct usb_interface *intf = to_usb_interface(dev); \
struct usb_tranzport *t = usb_get_intfdata(intf); \
unsigned long temp; \
if (kstrtoul(buf, 10, &temp)) \
return -EINVAL; \
t->value = temp; \
return count; \
} \
static DEVICE_ATTR(value, S_IWUSR | S_IRUGO, show_##value, set_##value);
show_int(enable);
show_int(offline);
show_set_int(compress_wheel);
/**
* usb_tranzport_delete
*/
static void usb_tranzport_delete(struct usb_tranzport *dev)
{
usb_tranzport_abort_transfers(dev);
if (dev->intf != NULL) {
device_remove_file(&dev->intf->dev, &dev_attr_enable);
device_remove_file(&dev->intf->dev, &dev_attr_offline);
device_remove_file(&dev->intf->dev, &dev_attr_compress_wheel);
}
/* free data structures */
usb_free_urb(dev->interrupt_in_urb);
usb_free_urb(dev->interrupt_out_urb);
kfree(dev->ring_buffer);
kfree(dev->interrupt_in_buffer);
kfree(dev->interrupt_out_buffer);
kfree(dev);
}
/**
* usb_tranzport_interrupt_in_callback
*/
static void usb_tranzport_interrupt_in_callback(struct urb *urb)
{
struct usb_tranzport *dev = urb->context;
unsigned int next_ring_head;
int retval = -1;
if (urb->status) {
if (urb->status == -ENOENT ||
urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN) {
goto exit;
} else {
dbg_info(&dev->intf->dev,
"%s: nonzero status received: %d\n",
__func__, urb->status);
goto resubmit; /* maybe we can recover */
}
}
if (urb->actual_length != 8) {
dev_warn(&dev->intf->dev,
"Urb length was %d bytes!!"
"Do something intelligent\n",
urb->actual_length);
} else {
dbg_info(&dev->intf->dev,
"%s: received: %02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__, dev->interrupt_in_buffer[0],
dev->interrupt_in_buffer[1],
dev->interrupt_in_buffer[2],
dev->interrupt_in_buffer[3],
dev->interrupt_in_buffer[4],
dev->interrupt_in_buffer[5],
dev->interrupt_in_buffer[6],
dev->interrupt_in_buffer[7]);
#if SUPPRESS_EXTRA_OFFLINE_EVENTS
if (dev->offline == 2 && dev->interrupt_in_buffer[1] == 0xff)
goto resubmit;
if (dev->offline == 1 && dev->interrupt_in_buffer[1] == 0xff) {
dev->offline = 2;
goto resubmit;
}
/* Always pass one offline event up the stack */
if (dev->offline > 0 && dev->interrupt_in_buffer[1] != 0xff)
dev->offline = 0;
if (dev->offline == 0 && dev->interrupt_in_buffer[1] == 0xff)
dev->offline = 1;
#endif /* SUPPRESS_EXTRA_OFFLINE_EVENTS */
dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n",
__func__, dev->ring_head, dev->ring_tail);
next_ring_head = (dev->ring_head + 1) % ring_buffer_size;
if (next_ring_head != dev->ring_tail) {
memcpy(&((*dev->ring_buffer)[dev->ring_head]),
dev->interrupt_in_buffer, urb->actual_length);
dev->ring_head = next_ring_head;
retval = 0;
memset(dev->interrupt_in_buffer, 0, urb->actual_length);
} else {
dev_warn(&dev->intf->dev,
"Ring buffer overflow, %d bytes dropped\n",
urb->actual_length);
memset(dev->interrupt_in_buffer, 0, urb->actual_length);
}
}
resubmit:
/* resubmit if we're still running */
if (dev->interrupt_in_running && dev->intf) {
retval = usb_submit_urb(dev->interrupt_in_urb, GFP_ATOMIC);
if (retval)
dev_err(&dev->intf->dev,
"usb_submit_urb failed (%d)\n", retval);
}
exit:
dev->interrupt_in_done = 1;
wake_up_interruptible(&dev->read_wait);
}
/**
* usb_tranzport_interrupt_out_callback
*/
static void usb_tranzport_interrupt_out_callback(struct urb *urb)
{
struct usb_tranzport *dev = urb->context;
/* sync/async unlink faults aren't errors */
if (urb->status && !(urb->status == -ENOENT ||
urb->status == -ECONNRESET ||
urb->status == -ESHUTDOWN))
dbg_info(&dev->intf->dev,
"%s - nonzero write interrupt status received: %d\n",
__func__, urb->status);
dev->interrupt_out_busy = 0;
wake_up_interruptible(&dev->write_wait);
}
/**
* usb_tranzport_open
*/
static int usb_tranzport_open(struct inode *inode, struct file *file)
{
struct usb_tranzport *dev;
int subminor;
int retval = 0;
struct usb_interface *interface;
nonseekable_open(inode, file);
subminor = iminor(inode);
mutex_lock(&disconnect_mutex);
interface = usb_find_interface(&usb_tranzport_driver, subminor);
if (!interface) {
pr_err("%s - error, can't find device for minor %d\n",
__func__, subminor);
retval = -ENODEV;
goto unlock_disconnect_exit;
}
dev = usb_get_intfdata(interface);
if (!dev) {
retval = -ENODEV;
goto unlock_disconnect_exit;
}
/* lock this device */
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto unlock_disconnect_exit;
}
/* allow opening only once */
if (dev->open_count) {
retval = -EBUSY;
goto unlock_exit;
}
dev->open_count = 1;
/* initialize in direction */
dev->ring_head = 0;
dev->ring_tail = 0;
usb_fill_int_urb(dev->interrupt_in_urb,
interface_to_usbdev(interface),
usb_rcvintpipe(interface_to_usbdev(interface),
dev->interrupt_in_endpoint->
bEndpointAddress),
dev->interrupt_in_buffer,
dev->interrupt_in_endpoint_size,
usb_tranzport_interrupt_in_callback, dev,
dev->interrupt_in_interval);
dev->interrupt_in_running = 1;
dev->interrupt_in_done = 0;
dev->enable = 1;
dev->offline = 0;
dev->compress_wheel = 1;
retval = usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL);
if (retval) {
dev_err(&interface->dev,
"Couldn't submit interrupt_in_urb %d\n", retval);
dev->interrupt_in_running = 0;
dev->open_count = 0;
goto unlock_exit;
}
/* save device in the file's private structure */
file->private_data = dev;
unlock_exit:
mutex_unlock(&dev->mtx);
unlock_disconnect_exit:
mutex_unlock(&disconnect_mutex);
return retval;
}
/**
* usb_tranzport_release
*/
static int usb_tranzport_release(struct inode *inode, struct file *file)
{
struct usb_tranzport *dev;
int retval = 0;
dev = file->private_data;
if (dev == NULL) {
retval = -ENODEV;
goto exit;
}
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto exit;
}
if (dev->open_count != 1) {
retval = -ENODEV;
goto unlock_exit;
}
if (dev->intf == NULL) {
/* the device was unplugged before the file was released */
mutex_unlock(&dev->mtx);
/* unlock here as usb_tranzport_delete frees dev */
usb_tranzport_delete(dev);
retval = -ENODEV;
goto exit;
}
/* wait until write transfer is finished */
if (dev->interrupt_out_busy)
wait_event_interruptible_timeout(dev->write_wait,
!dev->interrupt_out_busy,
2 * HZ);
usb_tranzport_abort_transfers(dev);
dev->open_count = 0;
unlock_exit:
mutex_unlock(&dev->mtx);
exit:
return retval;
}
/**
* usb_tranzport_poll
*/
static unsigned int usb_tranzport_poll(struct file *file, poll_table *wait)
{
struct usb_tranzport *dev;
unsigned int mask = 0;
dev = file->private_data;
poll_wait(file, &dev->read_wait, wait);
poll_wait(file, &dev->write_wait, wait);
if (dev->ring_head != dev->ring_tail)
mask |= POLLIN | POLLRDNORM;
if (!dev->interrupt_out_busy)
mask |= POLLOUT | POLLWRNORM;
return mask;
}
/**
* usb_tranzport_read
*/
static ssize_t usb_tranzport_read(struct file *file, char __user *buffer,
size_t count, loff_t *ppos)
{
struct usb_tranzport *dev;
int retval = 0;
#if BUFFERED_READS
int c = 0;
#endif
#if COMPRESS_WHEEL_EVENTS
signed char oldwheel;
signed char newwheel;
int cancompress = 1;
int next_tail;
#endif
/* do I have such a thing as a null event? */
dev = file->private_data;
/* verify that we actually have some data to read */
if (count == 0)
goto exit;
/* lock this object */
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto exit;
}
/* verify that the device wasn't unplugged */
if (dev->intf == NULL) {
retval = -ENODEV;
pr_err("%s: No device or device unplugged %d\n",
__func__, retval);
goto unlock_exit;
}
while (dev->ring_head == dev->ring_tail) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto unlock_exit;
}
/* tiny race - FIXME: make atomic? */
/* atomic_cmp_exchange(&dev->interrupt_in_done,0,0); */
dev->interrupt_in_done = 0;
retval = wait_event_interruptible(dev->read_wait,
dev->interrupt_in_done);
if (retval < 0)
goto unlock_exit;
}
dbg_info(&dev->intf->dev,
"%s: copying to userspace: "
"%02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__,
(*dev->ring_buffer)[dev->ring_tail].cmd[0],
(*dev->ring_buffer)[dev->ring_tail].cmd[1],
(*dev->ring_buffer)[dev->ring_tail].cmd[2],
(*dev->ring_buffer)[dev->ring_tail].cmd[3],
(*dev->ring_buffer)[dev->ring_tail].cmd[4],
(*dev->ring_buffer)[dev->ring_tail].cmd[5],
(*dev->ring_buffer)[dev->ring_tail].cmd[6],
(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
#if BUFFERED_READS
c = 0;
while ((c < count) && (dev->ring_tail != dev->ring_head)) {
#if COMPRESS_WHEEL_EVENTS
next_tail = (dev->ring_tail+1) % ring_buffer_size;
if (dev->compress_wheel)
cancompress = 1;
while (dev->ring_head != next_tail && cancompress == 1) {
newwheel = (*dev->ring_buffer)[next_tail].cmd[6];
oldwheel = (*dev->ring_buffer)[dev->ring_tail].cmd[6];
/* if both are wheel events, and
no buttons have changes (FIXME, do I have to check?),
and we are the same sign, we can compress +- 7F
*/
dbg_info(&dev->intf->dev,
"%s: trying to compress: "
"%02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__,
(*dev->ring_buffer)[dev->ring_tail].cmd[0],
(*dev->ring_buffer)[dev->ring_tail].cmd[1],
(*dev->ring_buffer)[dev->ring_tail].cmd[2],
(*dev->ring_buffer)[dev->ring_tail].cmd[3],
(*dev->ring_buffer)[dev->ring_tail].cmd[4],
(*dev->ring_buffer)[dev->ring_tail].cmd[5],
(*dev->ring_buffer)[dev->ring_tail].cmd[6],
(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
if (((*dev->ring_buffer)[dev->ring_tail].cmd[6] != 0 &&
(*dev->ring_buffer)[next_tail].cmd[6] != 0) &&
((newwheel > 0 && oldwheel > 0) ||
(newwheel < 0 && oldwheel < 0)) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[2] ==
(*dev->ring_buffer)[next_tail].cmd[2]) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[3] ==
(*dev->ring_buffer)[next_tail].cmd[3]) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[4] ==
(*dev->ring_buffer)[next_tail].cmd[4]) &&
((*dev->ring_buffer)[dev->ring_tail].cmd[5] ==
(*dev->ring_buffer)[next_tail].cmd[5])) {
dbg_info(&dev->intf->dev,
"%s: should compress: "
"%02x%02x%02x%02x%02x%02x%02x%02x\n",
__func__,
(*dev->ring_buffer)[dev->ring_tail].
cmd[0],
(*dev->ring_buffer)[dev->ring_tail].
cmd[1],
(*dev->ring_buffer)[dev->ring_tail].
cmd[2],
(*dev->ring_buffer)[dev->ring_tail].
cmd[3],
(*dev->ring_buffer)[dev->ring_tail].
cmd[4],
(*dev->ring_buffer)[dev->ring_tail].
cmd[5],
(*dev->ring_buffer)[dev->ring_tail].
cmd[6],
(*dev->ring_buffer)[dev->ring_tail].
cmd[7]);
newwheel += oldwheel;
if (oldwheel > 0 && !(newwheel > 0)) {
newwheel = 0x7f;
cancompress = 0;
}
if (oldwheel < 0 && !(newwheel < 0)) {
newwheel = 0x80;
cancompress = 0;
}
(*dev->ring_buffer)[next_tail].cmd[6] =
newwheel;
dev->ring_tail = next_tail;
next_tail =
(dev->ring_tail + 1) % ring_buffer_size;
} else {
cancompress = 0;
}
}
#endif /* COMPRESS_WHEEL_EVENTS */
if (copy_to_user(
&buffer[c],
&(*dev->ring_buffer)[dev->ring_tail], 8)) {
retval = -EFAULT;
goto unlock_exit;
}
dev->ring_tail = (dev->ring_tail + 1) % ring_buffer_size;
c += 8;
dbg_info(&dev->intf->dev,
"%s: head, tail are %x, %x\n",
__func__, dev->ring_head, dev->ring_tail);
}
retval = c;
#else
/* if (copy_to_user(buffer, &(*dev->ring_buffer)[dev->ring_tail], 8)) { */
retval = -EFAULT;
goto unlock_exit;
}
dev->ring_tail = (dev->ring_tail + 1) % ring_buffer_size;
dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n",
__func__, dev->ring_head, dev->ring_tail);
retval = 8;
#endif /* BUFFERED_READS */
unlock_exit:
/* unlock the device */
mutex_unlock(&dev->mtx);
exit:
return retval;
}
/**
* usb_tranzport_write
*/
static ssize_t usb_tranzport_write(struct file *file,
const char __user *buffer, size_t count,
loff_t *ppos)
{
struct usb_tranzport *dev;
size_t bytes_to_write;
int retval = 0;
dev = file->private_data;
/* verify that we actually have some data to write */
if (count == 0)
goto exit;
/* lock this object */
if (mutex_lock_interruptible(&dev->mtx)) {
retval = -ERESTARTSYS;
goto exit;
}
/* verify that the device wasn't unplugged */
if (dev->intf == NULL) {
retval = -ENODEV;
pr_err("%s: No device or device unplugged %d\n",
__func__, retval);
goto unlock_exit;
}
/* wait until previous transfer is finished */
if (dev->interrupt_out_busy) {
if (file->f_flags & O_NONBLOCK) {
retval = -EAGAIN;
goto unlock_exit;
}
retval = wait_event_interruptible(dev->write_wait,
!dev->interrupt_out_busy);
if (retval < 0)
goto unlock_exit;
}
/* write the data into interrupt_out_buffer from userspace */
bytes_to_write = min(count,
write_buffer_size *
dev->interrupt_out_endpoint_size);
if (bytes_to_write < count)
dev_warn(&dev->intf->dev,
"Write buffer overflow, %zd bytes dropped\n",
count - bytes_to_write);
dbg_info(&dev->intf->dev,
"%s: count = %zd, bytes_to_write = %zd\n", __func__,
count, bytes_to_write);
if (copy_from_user(dev->interrupt_out_buffer, buffer, bytes_to_write)) {
retval = -EFAULT;
goto unlock_exit;
}
if (dev->interrupt_out_endpoint == NULL) {
dev_err(&dev->intf->dev, "Endpoint should not be be null!\n");
goto unlock_exit;
}
/* send off the urb */
usb_fill_int_urb(dev->interrupt_out_urb,
interface_to_usbdev(dev->intf),
usb_sndintpipe(interface_to_usbdev(dev->intf),
dev->interrupt_out_endpoint->
bEndpointAddress),
dev->interrupt_out_buffer, bytes_to_write,
usb_tranzport_interrupt_out_callback, dev,
dev->interrupt_out_interval);
dev->interrupt_out_busy = 1;
wmb();
retval = usb_submit_urb(dev->interrupt_out_urb, GFP_KERNEL);
if (retval) {
dev->interrupt_out_busy = 0;
dev_err(&dev->intf->dev,
"Couldn't submit interrupt_out_urb %d\n", retval);
goto unlock_exit;
}
retval = bytes_to_write;
unlock_exit:
/* unlock the device */
mutex_unlock(&dev->mtx);
exit:
return retval;
}
/* file operations needed when we register this driver */
static const struct file_operations usb_tranzport_fops = {
.owner = THIS_MODULE,
.read = usb_tranzport_read,
.write = usb_tranzport_write,
.open = usb_tranzport_open,
.release = usb_tranzport_release,
.poll = usb_tranzport_poll,
.llseek = no_llseek,
};
/*
* usb class driver info in order to get a minor number from the usb core,
* and to have the device registered with the driver core
*/
static struct usb_class_driver usb_tranzport_class = {
.name = "tranzport%d",
.fops = &usb_tranzport_fops,
.minor_base = USB_TRANZPORT_MINOR_BASE,
};
/**
* usb_tranzport_probe
*
* Called by the usb core when a new device is connected that it thinks
* this driver might be interested in.
*/
static int usb_tranzport_probe(struct usb_interface *intf,
const struct usb_device_id *id) {
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_tranzport *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
int i;
int true_size;
int retval = -ENOMEM;
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL)
goto exit;
mutex_init(&dev->mtx);
dev->intf = intf;
init_waitqueue_head(&dev->read_wait);
init_waitqueue_head(&dev->write_wait);
iface_desc = intf->cur_altsetting;
/* set up the endpoint information */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_is_int_in(endpoint))
dev->interrupt_in_endpoint = endpoint;
if (usb_endpoint_is_int_out(endpoint))
dev->interrupt_out_endpoint = endpoint;
}
if (dev->interrupt_in_endpoint == NULL) {
dev_err(&intf->dev, "Interrupt in endpoint not found\n");
goto error;
}
if (dev->interrupt_out_endpoint == NULL)
dev_warn(&intf->dev,
"Interrupt out endpoint not found"
"(using control endpoint instead)\n");
dev->interrupt_in_endpoint_size =
le16_to_cpu(dev->interrupt_in_endpoint->wMaxPacketSize);
if (dev->interrupt_in_endpoint_size != 8)
dev_warn(&intf->dev, "Interrupt in endpoint size is not 8!\n");
if (ring_buffer_size == 0)
ring_buffer_size = RING_BUFFER_SIZE;
true_size = min(ring_buffer_size, RING_BUFFER_SIZE);
/* FIXME - there are more usb_alloc routines for dma correctness.
Needed? */
dev->ring_buffer =
kmalloc((true_size * sizeof(struct tranzport_cmd)) + 8, GFP_KERNEL);
if (!dev->ring_buffer)
goto error;
dev->interrupt_in_buffer =
kmalloc(dev->interrupt_in_endpoint_size, GFP_KERNEL);
if (!dev->interrupt_in_buffer)
goto error;
dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_in_urb) {
dev_err(&intf->dev, "Couldn't allocate interrupt_in_urb\n");
goto error;
}
dev->interrupt_out_endpoint_size =
dev->interrupt_out_endpoint ?
le16_to_cpu(dev->interrupt_out_endpoint->wMaxPacketSize) :
udev->descriptor.bMaxPacketSize0;
if (dev->interrupt_out_endpoint_size != 8)
dev_warn(&intf->dev,
"Interrupt out endpoint size is not 8!)\n");
dev->interrupt_out_buffer =
kmalloc_array(write_buffer_size,
dev->interrupt_out_endpoint_size, GFP_KERNEL);
if (!dev->interrupt_out_buffer)
goto error;
dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_out_urb) {
dev_err(&intf->dev, "Couldn't allocate interrupt_out_urb\n");
goto error;
}
dev->interrupt_in_interval =
min_interrupt_in_interval >
dev->interrupt_in_endpoint->bInterval ? min_interrupt_in_interval
: dev->interrupt_in_endpoint->bInterval;
if (dev->interrupt_out_endpoint) {
dev->interrupt_out_interval =
min_interrupt_out_interval >
dev->interrupt_out_endpoint->bInterval ?
min_interrupt_out_interval :
dev->interrupt_out_endpoint->bInterval;
}
/* we can register the device now, as it is ready */
usb_set_intfdata(intf, dev);
retval = usb_register_dev(intf, &usb_tranzport_class);
if (retval) {
/* something prevented us from registering this driver */
dev_err(&intf->dev,
"Not able to get a minor for this device.\n");
usb_set_intfdata(intf, NULL);
goto error;
}
retval = device_create_file(&intf->dev, &dev_attr_compress_wheel);
if (retval)
goto error;
retval = device_create_file(&intf->dev, &dev_attr_enable);
if (retval)
goto error;
retval = device_create_file(&intf->dev, &dev_attr_offline);
if (retval)
goto error;
/* let the user know what node this device is now attached to */
dev_info(&intf->dev,
"Tranzport Device #%d now attached to major %d minor %d\n",
(intf->minor - USB_TRANZPORT_MINOR_BASE), USB_MAJOR,
intf->minor);
exit:
return retval;
error:
usb_tranzport_delete(dev);
return retval;
}
/**
* usb_tranzport_disconnect
*
* Called by the usb core when the device is removed from the system.
*/
static void usb_tranzport_disconnect(struct usb_interface *intf)
{
struct usb_tranzport *dev;
int minor;
mutex_lock(&disconnect_mutex);
dev = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
mutex_lock(&dev->mtx);
minor = intf->minor;
/* give back our minor */
usb_deregister_dev(intf, &usb_tranzport_class);
/* if the device is not opened, then we clean up right now */
if (!dev->open_count) {
mutex_unlock(&dev->mtx);
usb_tranzport_delete(dev);
} else {
dev->intf = NULL;
mutex_unlock(&dev->mtx);
}
mutex_unlock(&disconnect_mutex);
dev_info(&intf->dev, "Tranzport Surface #%d now disconnected\n",
(minor - USB_TRANZPORT_MINOR_BASE));
}
/* usb specific object needed to register this driver with the usb subsystem */
static struct usb_driver usb_tranzport_driver = {
.name = "tranzport",
.probe = usb_tranzport_probe,
.disconnect = usb_tranzport_disconnect,
.id_table = usb_tranzport_table,
};
module_usb_driver(usb_tranzport_driver);
| apache-2.0 |
liamgh/liamgreenhughes-sl4a-tf101 | python-build/openssl/crypto/evp/m_dss.c | 102 | 3953 | /* crypto/evp/m_dss.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#ifndef OPENSSL_NO_DSA
#include <openssl/dsa.h>
#endif
#ifndef OPENSSL_NO_SHA
static int init(EVP_MD_CTX *ctx)
{ return SHA1_Init(ctx->md_data); }
static int update(EVP_MD_CTX *ctx,const void *data,size_t count)
{ return SHA1_Update(ctx->md_data,data,count); }
static int final(EVP_MD_CTX *ctx,unsigned char *md)
{ return SHA1_Final(md,ctx->md_data); }
static const EVP_MD dsa_md=
{
NID_dsaWithSHA,
NID_dsaWithSHA,
SHA_DIGEST_LENGTH,
EVP_MD_FLAG_FIPS,
init,
update,
final,
NULL,
NULL,
EVP_PKEY_DSA_method,
SHA_CBLOCK,
sizeof(EVP_MD *)+sizeof(SHA_CTX),
};
const EVP_MD *EVP_dss(void)
{
return(&dsa_md);
}
#endif
| apache-2.0 |
Immortalin/python-for-android | python-build/openssl/crypto/dsa/dsa_sign.c | 102 | 4093 | /* crypto/dsa/dsa_sign.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* Original version from Steven Schoch <schoch@sheba.arc.nasa.gov> */
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/bn.h>
#include <openssl/dsa.h>
#include <openssl/rand.h>
#include <openssl/asn1.h>
#ifdef OPENSSL_FIPS
#include <openssl/fips.h>
#endif
DSA_SIG * DSA_do_sign(const unsigned char *dgst, int dlen, DSA *dsa)
{
#ifdef OPENSSL_FIPS
if(FIPS_mode() && !(dsa->flags & DSA_FLAG_NON_FIPS_ALLOW))
{
DSAerr(DSA_F_DSA_DO_SIGN, DSA_R_OPERATION_NOT_ALLOWED_IN_FIPS_MODE);
return NULL;
}
#endif
return dsa->meth->dsa_do_sign(dgst, dlen, dsa);
}
int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in, BIGNUM **kinvp, BIGNUM **rp)
{
#ifdef OPENSSL_FIPS
if(FIPS_mode() && !(dsa->flags & DSA_FLAG_NON_FIPS_ALLOW))
{
DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_OPERATION_NOT_ALLOWED_IN_FIPS_MODE);
return 0;
}
#endif
return dsa->meth->dsa_sign_setup(dsa, ctx_in, kinvp, rp);
}
| apache-2.0 |
MRSDTeamI/bud-e | Navigation/base_controller/rosaria/build/CMakeFiles/2.8.12.2/CompilerIdC/CMakeCCompilerId.c | 619 | 11935 | #ifdef __cplusplus
# error "A C++ compiler has been selected for C."
#endif
/* Version number components: V=Version, R=Revision, P=Patch
Version date components: YYYY=Year, MM=Month, DD=Day */
#if defined(__18CXX)
# define ID_VOID_MAIN
#endif
#if defined(__INTEL_COMPILER) || defined(__ICC)
# define COMPILER_ID "Intel"
/* __INTEL_COMPILER = VRP */
# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100)
# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10)
# if defined(__INTEL_COMPILER_BUILD_DATE)
/* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */
# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE)
# endif
#elif defined(__PATHCC__)
# define COMPILER_ID "PathScale"
# define COMPILER_VERSION_MAJOR DEC(__PATHCC__)
# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__)
# if defined(__PATHCC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__)
# endif
#elif defined(__clang__)
# define COMPILER_ID "Clang"
# define COMPILER_VERSION_MAJOR DEC(__clang_major__)
# define COMPILER_VERSION_MINOR DEC(__clang_minor__)
# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__)
#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__)
# define COMPILER_ID "Embarcadero"
# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF)
# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF)
# define COMPILER_VERSION_PATCH HEX(__CODEGEARC_VERSION__ & 0xFFFF)
#elif defined(__BORLANDC__)
# define COMPILER_ID "Borland"
/* __BORLANDC__ = 0xVRR */
# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8)
# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF)
#elif defined(__WATCOMC__)
# define COMPILER_ID "Watcom"
/* __WATCOMC__ = VVRR */
# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100)
# define COMPILER_VERSION_MINOR DEC(__WATCOMC__ % 100)
#elif defined(__SUNPRO_C)
# define COMPILER_ID "SunPro"
# if __SUNPRO_C >= 0x5100
/* __SUNPRO_C = 0xVRRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF)
# else
/* __SUNPRO_C = 0xVRP */
# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8)
# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF)
# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF)
# endif
#elif defined(__HP_cc)
# define COMPILER_ID "HP"
/* __HP_cc = VVRRPP */
# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000)
# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100)
# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100)
#elif defined(__DECC)
# define COMPILER_ID "Compaq"
/* __DECC_VER = VVRRTPPPP */
# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000)
# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100)
# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000)
#elif defined(__IBMC__)
# if defined(__COMPILER_VER__)
# define COMPILER_ID "zOS"
# else
# if __IBMC__ >= 800
# define COMPILER_ID "XL"
# else
# define COMPILER_ID "VisualAge"
# endif
/* __IBMC__ = VRP */
# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100)
# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10)
# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10)
# endif
#elif defined(__PGI)
# define COMPILER_ID "PGI"
# define COMPILER_VERSION_MAJOR DEC(__PGIC__)
# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__)
# if defined(__PGIC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__)
# endif
#elif defined(_CRAYC)
# define COMPILER_ID "Cray"
# define COMPILER_VERSION_MAJOR DEC(_RELEASE)
# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR)
#elif defined(__TI_COMPILER_VERSION__)
# define COMPILER_ID "TI"
/* __TI_COMPILER_VERSION__ = VVVRRRPPP */
# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000)
# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000)
# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000)
#elif defined(__TINYC__)
# define COMPILER_ID "TinyCC"
#elif defined(__SCO_VERSION__)
# define COMPILER_ID "SCO"
#elif defined(__GNUC__)
# define COMPILER_ID "GNU"
# define COMPILER_VERSION_MAJOR DEC(__GNUC__)
# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__)
# if defined(__GNUC_PATCHLEVEL__)
# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__)
# endif
#elif defined(_MSC_VER)
# define COMPILER_ID "MSVC"
/* _MSC_VER = VVRR */
# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100)
# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100)
# if defined(_MSC_FULL_VER)
# if _MSC_VER >= 1400
/* _MSC_FULL_VER = VVRRPPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000)
# else
/* _MSC_FULL_VER = VVRRPPPP */
# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000)
# endif
# endif
# if defined(_MSC_BUILD)
# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD)
# endif
/* Analog VisualDSP++ >= 4.5.6 */
#elif defined(__VISUALDSPVERSION__)
# define COMPILER_ID "ADSP"
/* __VISUALDSPVERSION__ = 0xVVRRPP00 */
# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24)
# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF)
# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF)
/* Analog VisualDSP++ < 4.5.6 */
#elif defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__)
# define COMPILER_ID "ADSP"
/* IAR Systems compiler for embedded systems.
http://www.iar.com */
#elif defined(__IAR_SYSTEMS_ICC__ ) || defined(__IAR_SYSTEMS_ICC)
# define COMPILER_ID "IAR"
/* sdcc, the small devices C compiler for embedded systems,
http://sdcc.sourceforge.net */
#elif defined(SDCC)
# define COMPILER_ID "SDCC"
/* SDCC = VRP */
# define COMPILER_VERSION_MAJOR DEC(SDCC/100)
# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10)
# define COMPILER_VERSION_PATCH DEC(SDCC % 10)
#elif defined(_SGI_COMPILER_VERSION) || defined(_COMPILER_VERSION)
# define COMPILER_ID "MIPSpro"
# if defined(_SGI_COMPILER_VERSION)
/* _SGI_COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_SGI_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_SGI_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_SGI_COMPILER_VERSION % 10)
# else
/* _COMPILER_VERSION = VRP */
# define COMPILER_VERSION_MAJOR DEC(_COMPILER_VERSION/100)
# define COMPILER_VERSION_MINOR DEC(_COMPILER_VERSION/10 % 10)
# define COMPILER_VERSION_PATCH DEC(_COMPILER_VERSION % 10)
# endif
/* This compiler is either not known or is too old to define an
identification macro. Try to identify the platform and guess that
it is the native compiler. */
#elif defined(__sgi)
# define COMPILER_ID "MIPSpro"
#elif defined(__hpux) || defined(__hpua)
# define COMPILER_ID "HP"
#else /* unknown compiler */
# define COMPILER_ID ""
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]";
/* Identify known platforms by name. */
#if defined(__linux) || defined(__linux__) || defined(linux)
# define PLATFORM_ID "Linux"
#elif defined(__CYGWIN__)
# define PLATFORM_ID "Cygwin"
#elif defined(__MINGW32__)
# define PLATFORM_ID "MinGW"
#elif defined(__APPLE__)
# define PLATFORM_ID "Darwin"
#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
# define PLATFORM_ID "Windows"
#elif defined(__FreeBSD__) || defined(__FreeBSD)
# define PLATFORM_ID "FreeBSD"
#elif defined(__NetBSD__) || defined(__NetBSD)
# define PLATFORM_ID "NetBSD"
#elif defined(__OpenBSD__) || defined(__OPENBSD)
# define PLATFORM_ID "OpenBSD"
#elif defined(__sun) || defined(sun)
# define PLATFORM_ID "SunOS"
#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__)
# define PLATFORM_ID "AIX"
#elif defined(__sgi) || defined(__sgi__) || defined(_SGI)
# define PLATFORM_ID "IRIX"
#elif defined(__hpux) || defined(__hpux__)
# define PLATFORM_ID "HP-UX"
#elif defined(__HAIKU__)
# define PLATFORM_ID "Haiku"
#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS)
# define PLATFORM_ID "BeOS"
#elif defined(__QNX__) || defined(__QNXNTO__)
# define PLATFORM_ID "QNX"
#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__)
# define PLATFORM_ID "Tru64"
#elif defined(__riscos) || defined(__riscos__)
# define PLATFORM_ID "RISCos"
#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__)
# define PLATFORM_ID "SINIX"
#elif defined(__UNIX_SV__)
# define PLATFORM_ID "UNIX_SV"
#elif defined(__bsdos__)
# define PLATFORM_ID "BSDOS"
#elif defined(_MPRAS) || defined(MPRAS)
# define PLATFORM_ID "MP-RAS"
#elif defined(__osf) || defined(__osf__)
# define PLATFORM_ID "OSF1"
#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv)
# define PLATFORM_ID "SCO_SV"
#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX)
# define PLATFORM_ID "ULTRIX"
#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX)
# define PLATFORM_ID "Xenix"
#else /* unknown platform */
# define PLATFORM_ID ""
#endif
/* For windows compilers MSVC and Intel we can determine
the architecture of the compiler being used. This is because
the compilers do not have flags that can change the architecture,
but rather depend on which compiler is being used
*/
#if defined(_WIN32) && defined(_MSC_VER)
# if defined(_M_IA64)
# define ARCHITECTURE_ID "IA64"
# elif defined(_M_X64) || defined(_M_AMD64)
# define ARCHITECTURE_ID "x64"
# elif defined(_M_IX86)
# define ARCHITECTURE_ID "X86"
# elif defined(_M_ARM)
# define ARCHITECTURE_ID "ARM"
# elif defined(_M_MIPS)
# define ARCHITECTURE_ID "MIPS"
# elif defined(_M_SH)
# define ARCHITECTURE_ID "SHx"
# else /* unknown architecture */
# define ARCHITECTURE_ID ""
# endif
#else
# define ARCHITECTURE_ID ""
#endif
/* Convert integer to decimal digit literals. */
#define DEC(n) \
('0' + (((n) / 10000000)%10)), \
('0' + (((n) / 1000000)%10)), \
('0' + (((n) / 100000)%10)), \
('0' + (((n) / 10000)%10)), \
('0' + (((n) / 1000)%10)), \
('0' + (((n) / 100)%10)), \
('0' + (((n) / 10)%10)), \
('0' + ((n) % 10))
/* Convert integer to hex digit literals. */
#define HEX(n) \
('0' + ((n)>>28 & 0xF)), \
('0' + ((n)>>24 & 0xF)), \
('0' + ((n)>>20 & 0xF)), \
('0' + ((n)>>16 & 0xF)), \
('0' + ((n)>>12 & 0xF)), \
('0' + ((n)>>8 & 0xF)), \
('0' + ((n)>>4 & 0xF)), \
('0' + ((n) & 0xF))
/* Construct a string literal encoding the version number components. */
#ifdef COMPILER_VERSION_MAJOR
char const info_version[] = {
'I', 'N', 'F', 'O', ':',
'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[',
COMPILER_VERSION_MAJOR,
# ifdef COMPILER_VERSION_MINOR
'.', COMPILER_VERSION_MINOR,
# ifdef COMPILER_VERSION_PATCH
'.', COMPILER_VERSION_PATCH,
# ifdef COMPILER_VERSION_TWEAK
'.', COMPILER_VERSION_TWEAK,
# endif
# endif
# endif
']','\0'};
#endif
/* Construct the string literal in pieces to prevent the source from
getting matched. Store it in a pointer rather than an array
because some compilers will just produce instructions to fill the
array rather than assigning a pointer to a static array. */
char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]";
char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]";
/*--------------------------------------------------------------------------*/
#ifdef ID_VOID_MAIN
void main() {}
#else
int main(int argc, char* argv[])
{
int require = 0;
require += info_compiler[argc];
require += info_platform[argc];
require += info_arch[argc];
#ifdef COMPILER_VERSION_MAJOR
require += info_version[argc];
#endif
(void)argv;
return require;
}
#endif
| apache-2.0 |
tung7970/mbed-os | hal/targets/cmsis/TARGET_ARM_SSG/TARGET_MPS2_M0/cmsis_nvic.c | 113 | 2470 | /* MPS2 CMSIS Library
*
* Copyright (c) 2006-2016 ARM Limited
* 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.
*******************************************************************************
* CMSIS-style functionality to support dynamic vectors
*******************************************************************************/
#include "cmsis_nvic.h"
#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Location of vectors in RAM
#define NVIC_FLASH_VECTOR_ADDRESS (0x00000000) // Initial vector position in flash
void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) {
// int i;
// Space for dynamic vectors, initialised to allocate in R/W
static volatile uint32_t* vectors = (uint32_t*)NVIC_FLASH_VECTOR_ADDRESS;
// Set the vector
vectors[IRQn + 16] = vector;
}
uint32_t NVIC_GetVector(IRQn_Type IRQn) {
// We can always read vectors at 0x0, as the addresses are remapped
uint32_t *vectors = (uint32_t*)NVIC_FLASH_VECTOR_ADDRESS;
// Return the vector
return vectors[IRQn + 16];
}
| apache-2.0 |
bsmr-java/libgdx | gdx/jni/com.badlogic.gdx.utils.BufferUtils.cpp | 117 | 25802 | #include <com.badlogic.gdx.utils.BufferUtils.h>
//@line:497
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_freeMemory(JNIEnv* env, jclass clazz, jobject obj_buffer) {
char* buffer = (char*)(obj_buffer?env->GetDirectBufferAddress(obj_buffer):0);
//@line:559
free(buffer);
}
JNIEXPORT jobject JNICALL Java_com_badlogic_gdx_utils_BufferUtils_newDisposableByteBuffer(JNIEnv* env, jclass clazz, jint numBytes) {
//@line:563
return env->NewDirectByteBuffer((char*)malloc(numBytes), numBytes);
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_getBufferAddress
(JNIEnv* env, jclass clazz, jobject obj_buffer, unsigned char* buffer) {
//@line:567
return (jlong) buffer;
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_getBufferAddress(JNIEnv* env, jclass clazz, jobject obj_buffer) {
unsigned char* buffer = (unsigned char*)(obj_buffer?env->GetDirectBufferAddress(obj_buffer):0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_getBufferAddress(env, clazz, obj_buffer, buffer);
return JNI_returnValue;
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_clear(JNIEnv* env, jclass clazz, jobject obj_buffer, jint numBytes) {
char* buffer = (char*)(obj_buffer?env->GetDirectBufferAddress(obj_buffer):0);
//@line:572
memset(buffer, 0, numBytes);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3FLjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jfloatArray obj_src, jobject obj_dst, jint numFloats, jint offset) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
float* src = (float*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:576
memcpy(dst, src + offset, numFloats << 2 );
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3BILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jbyteArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
char* src = (char*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:580
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3CILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jcharArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
unsigned short* src = (unsigned short*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:584
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3SILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jshortArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
short* src = (short*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:588
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3IILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jintArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
int* src = (int*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:592
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3JILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jlongArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
long long* src = (long long*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:596
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3FILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jfloatArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
float* src = (float*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:600
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni___3DILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jdoubleArray obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
double* src = (double*)env->GetPrimitiveArrayCritical(obj_src, 0);
//@line:604
memcpy(dst + dstOffset, src + srcOffset, numBytes);
env->ReleasePrimitiveArrayCritical(obj_src, src, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_copyJni__Ljava_nio_Buffer_2ILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jobject obj_src, jint srcOffset, jobject obj_dst, jint dstOffset, jint numBytes) {
unsigned char* src = (unsigned char*)(obj_src?env->GetDirectBufferAddress(obj_src):0);
unsigned char* dst = (unsigned char*)(obj_dst?env->GetDirectBufferAddress(obj_dst):0);
//@line:608
memcpy(dst + dstOffset, src + srcOffset, numBytes);
}
//@line:612
template<size_t n1, size_t n2> void transform(float * const &src, float * const &m, float * const &dst) {}
template<> inline void transform<4, 4>(float * const &src, float * const &m, float * const &dst) {
const float x = src[0], y = src[1], z = src[2], w = src[3];
dst[0] = x * m[ 0] + y * m[ 4] + z * m[ 8] + w * m[12];
dst[1] = x * m[ 1] + y * m[ 5] + z * m[ 9] + w * m[13];
dst[2] = x * m[ 2] + y * m[ 6] + z * m[10] + w * m[14];
dst[3] = x * m[ 3] + y * m[ 7] + z * m[11] + w * m[15];
}
template<> inline void transform<3, 4>(float * const &src, float * const &m, float * const &dst) {
const float x = src[0], y = src[1], z = src[2];
dst[0] = x * m[ 0] + y * m[ 4] + z * m[ 8] + m[12];
dst[1] = x * m[ 1] + y * m[ 5] + z * m[ 9] + m[13];
dst[2] = x * m[ 2] + y * m[ 6] + z * m[10] + m[14];
}
template<> inline void transform<2, 4>(float * const &src, float * const &m, float * const &dst) {
const float x = src[0], y = src[1];
dst[0] = x * m[ 0] + y * m[ 4] + m[12];
dst[1] = x * m[ 1] + y * m[ 5] + m[13];
}
template<> inline void transform<3, 3>(float * const &src, float * const &m, float * const &dst) {
const float x = src[0], y = src[1], z = src[2];
dst[0] = x * m[0] + y * m[3] + z * m[6];
dst[1] = x * m[1] + y * m[4] + z * m[7];
dst[2] = x * m[2] + y * m[5] + z * m[8];
}
template<> inline void transform<2, 3>(float * const &src, float * const &m, float * const &dst) {
const float x = src[0], y = src[1];
dst[0] = x * m[0] + y * m[3] + m[6];
dst[1] = x * m[1] + y * m[4] + m[7];
}
template<size_t n1, size_t n2> void transform(float * const &v, int const &stride, int const &count, float * const &m, int offset) {
for (int i = 0; i < count; i++) {
transform<n1, n2>(&v[offset], m, &v[offset]);
offset += stride;
}
}
template<size_t n1, size_t n2> void transform(float * const &v, int const &stride, unsigned short * const &indices, int const &count, float * const &m, int offset) {
for (int i = 0; i < count; i++) {
transform<n1, n2>(&v[offset], m, &v[offset]);
offset += stride;
}
}
inline bool compare(float * const &lhs, float * const & rhs, const unsigned int &size, const float &epsilon) {
for (unsigned int i = 0; i < size; i++)
if ((*(unsigned int*)&lhs[i] != *(unsigned int*)&rhs[i]) && ((lhs[i] > rhs[i] ? lhs[i] - rhs[i] : rhs[i] - lhs[i]) > epsilon))
return false;
return true;
}
long find(float * const &vertex, const unsigned int &size, float * const &vertices, const unsigned int &count, const float &epsilon) {
for (unsigned int i = 0; i < count; i++)
if (compare(&vertices[i*size], vertex, size, epsilon))
return (long)i;
return -1;
}
inline bool compare(float * const &lhs, float * const & rhs, const unsigned int &size) {
for (unsigned int i = 0; i < size; i++)
if ((*(unsigned int*)&lhs[i] != *(unsigned int*)&rhs[i]) && lhs[i] != rhs[i])
return false;
return true;
}
long find(float * const &vertex, const unsigned int &size, float * const &vertices, const unsigned int &count) {
for (unsigned int i = 0; i < count; i++)
if (compare(&vertices[i*size], vertex, size))
return (long)i;
return -1;
}
inline unsigned int calcHash(float * const &vertex, const unsigned int &size) {
unsigned int result = 0;
for (unsigned int i = 0; i < size; ++i)
result += ((*((unsigned int *)&vertex[i])) & 0xffffff80) >> (i & 0x7);
return result & 0x7fffffff;
}
long find(float * const &vertex, const unsigned int &size, float * const &vertices, unsigned int * const &hashes, const unsigned int &count) {
const unsigned int hash = calcHash(vertex, size);
for (unsigned int i = 0; i < count; i++)
if (hashes[i] == hash && compare(&vertices[i*size], vertex, size))
return (long)i;
return -1;
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV4M4Jni__Ljava_nio_Buffer_2II_3FI(JNIEnv* env, jclass clazz, jobject obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
unsigned char* data = (unsigned char*)(obj_data?env->GetDirectBufferAddress(obj_data):0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:707
transform<4, 4>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV4M4Jni___3FII_3FI(JNIEnv* env, jclass clazz, jfloatArray obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
float* data = (float*)env->GetPrimitiveArrayCritical(obj_data, 0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:711
transform<4, 4>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_data, data, 0);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV3M4Jni__Ljava_nio_Buffer_2II_3FI(JNIEnv* env, jclass clazz, jobject obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
unsigned char* data = (unsigned char*)(obj_data?env->GetDirectBufferAddress(obj_data):0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:715
transform<3, 4>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV3M4Jni___3FII_3FI(JNIEnv* env, jclass clazz, jfloatArray obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
float* data = (float*)env->GetPrimitiveArrayCritical(obj_data, 0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:719
transform<3, 4>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_data, data, 0);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV2M4Jni__Ljava_nio_Buffer_2II_3FI(JNIEnv* env, jclass clazz, jobject obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
unsigned char* data = (unsigned char*)(obj_data?env->GetDirectBufferAddress(obj_data):0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:723
transform<2, 4>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV2M4Jni___3FII_3FI(JNIEnv* env, jclass clazz, jfloatArray obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
float* data = (float*)env->GetPrimitiveArrayCritical(obj_data, 0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:727
transform<2, 4>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_data, data, 0);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV3M3Jni__Ljava_nio_Buffer_2II_3FI(JNIEnv* env, jclass clazz, jobject obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
unsigned char* data = (unsigned char*)(obj_data?env->GetDirectBufferAddress(obj_data):0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:731
transform<3, 3>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV3M3Jni___3FII_3FI(JNIEnv* env, jclass clazz, jfloatArray obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
float* data = (float*)env->GetPrimitiveArrayCritical(obj_data, 0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:735
transform<3, 3>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_data, data, 0);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV2M3Jni__Ljava_nio_Buffer_2II_3FI(JNIEnv* env, jclass clazz, jobject obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
unsigned char* data = (unsigned char*)(obj_data?env->GetDirectBufferAddress(obj_data):0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:739
transform<2, 3>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
JNIEXPORT void JNICALL Java_com_badlogic_gdx_utils_BufferUtils_transformV2M3Jni___3FII_3FI(JNIEnv* env, jclass clazz, jfloatArray obj_data, jint strideInBytes, jint count, jfloatArray obj_matrix, jint offsetInBytes) {
float* data = (float*)env->GetPrimitiveArrayCritical(obj_data, 0);
float* matrix = (float*)env->GetPrimitiveArrayCritical(obj_matrix, 0);
//@line:743
transform<2, 3>((float*)data, strideInBytes / 4, count, (float*)matrix, offsetInBytes / 4);
env->ReleasePrimitiveArrayCritical(obj_data, data, 0);
env->ReleasePrimitiveArrayCritical(obj_matrix, matrix, 0);
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2IILjava_nio_Buffer_2II
(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices, unsigned char* vertex, unsigned char* vertices) {
//@line:747
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2IILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices) {
unsigned char* vertex = (unsigned char*)(obj_vertex?env->GetDirectBufferAddress(obj_vertex):0);
unsigned char* vertices = (unsigned char*)(obj_vertices?env->GetDirectBufferAddress(obj_vertices):0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2IILjava_nio_Buffer_2II(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, vertex, vertices);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FIILjava_nio_Buffer_2II
(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices, unsigned char* vertices, float* vertex) {
//@line:751
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find___3FIILjava_nio_Buffer_2II(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices) {
unsigned char* vertices = (unsigned char*)(obj_vertices?env->GetDirectBufferAddress(obj_vertices):0);
float* vertex = (float*)env->GetPrimitiveArrayCritical(obj_vertex, 0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FIILjava_nio_Buffer_2II(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, vertices, vertex);
env->ReleasePrimitiveArrayCritical(obj_vertex, vertex, 0);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2II_3FII
(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices, unsigned char* vertex, float* vertices) {
//@line:755
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2II_3FII(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices) {
unsigned char* vertex = (unsigned char*)(obj_vertex?env->GetDirectBufferAddress(obj_vertex):0);
float* vertices = (float*)env->GetPrimitiveArrayCritical(obj_vertices, 0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2II_3FII(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, vertex, vertices);
env->ReleasePrimitiveArrayCritical(obj_vertices, vertices, 0);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FII_3FII
(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices, float* vertex, float* vertices) {
//@line:759
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find___3FII_3FII(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices) {
float* vertex = (float*)env->GetPrimitiveArrayCritical(obj_vertex, 0);
float* vertices = (float*)env->GetPrimitiveArrayCritical(obj_vertices, 0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FII_3FII(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, vertex, vertices);
env->ReleasePrimitiveArrayCritical(obj_vertex, vertex, 0);
env->ReleasePrimitiveArrayCritical(obj_vertices, vertices, 0);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2IILjava_nio_Buffer_2IIF
(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon, unsigned char* vertex, unsigned char* vertices) {
//@line:763
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices, epsilon);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2IILjava_nio_Buffer_2IIF(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon) {
unsigned char* vertex = (unsigned char*)(obj_vertex?env->GetDirectBufferAddress(obj_vertex):0);
unsigned char* vertices = (unsigned char*)(obj_vertices?env->GetDirectBufferAddress(obj_vertices):0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2IILjava_nio_Buffer_2IIF(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, epsilon, vertex, vertices);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FIILjava_nio_Buffer_2IIF
(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon, unsigned char* vertices, float* vertex) {
//@line:767
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices, epsilon);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find___3FIILjava_nio_Buffer_2IIF(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jobject obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon) {
unsigned char* vertices = (unsigned char*)(obj_vertices?env->GetDirectBufferAddress(obj_vertices):0);
float* vertex = (float*)env->GetPrimitiveArrayCritical(obj_vertex, 0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FIILjava_nio_Buffer_2IIF(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, epsilon, vertices, vertex);
env->ReleasePrimitiveArrayCritical(obj_vertex, vertex, 0);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2II_3FIIF
(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon, unsigned char* vertex, float* vertices) {
//@line:771
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices, epsilon);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2II_3FIIF(JNIEnv* env, jclass clazz, jobject obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon) {
unsigned char* vertex = (unsigned char*)(obj_vertex?env->GetDirectBufferAddress(obj_vertex):0);
float* vertices = (float*)env->GetPrimitiveArrayCritical(obj_vertices, 0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find__Ljava_nio_Buffer_2II_3FIIF(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, epsilon, vertex, vertices);
env->ReleasePrimitiveArrayCritical(obj_vertices, vertices, 0);
return JNI_returnValue;
}
static inline jlong wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FII_3FIIF
(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon, float* vertex, float* vertices) {
//@line:775
return find((float *)&vertex[vertexOffsetInBytes / 4], (unsigned int)(strideInBytes / 4), (float*)&vertices[verticesOffsetInBytes / 4], (unsigned int)numVertices, epsilon);
}
JNIEXPORT jlong JNICALL Java_com_badlogic_gdx_utils_BufferUtils_find___3FII_3FIIF(JNIEnv* env, jclass clazz, jfloatArray obj_vertex, jint vertexOffsetInBytes, jint strideInBytes, jfloatArray obj_vertices, jint verticesOffsetInBytes, jint numVertices, jfloat epsilon) {
float* vertex = (float*)env->GetPrimitiveArrayCritical(obj_vertex, 0);
float* vertices = (float*)env->GetPrimitiveArrayCritical(obj_vertices, 0);
jlong JNI_returnValue = wrapped_Java_com_badlogic_gdx_utils_BufferUtils_find___3FII_3FIIF(env, clazz, obj_vertex, vertexOffsetInBytes, strideInBytes, obj_vertices, verticesOffsetInBytes, numVertices, epsilon, vertex, vertices);
env->ReleasePrimitiveArrayCritical(obj_vertex, vertex, 0);
env->ReleasePrimitiveArrayCritical(obj_vertices, vertices, 0);
return JNI_returnValue;
}
| apache-2.0 |
hhool/transmission | external/openssl/apps/dhparam.c | 120 | 15661 | /* apps/dhparam.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
/* ====================================================================
* Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <openssl/opensslconf.h> /* for OPENSSL_NO_DH */
#ifndef OPENSSL_NO_DH
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "apps.h"
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/bn.h>
#include <openssl/dh.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_DSA
#include <openssl/dsa.h>
#endif
#undef PROG
#define PROG dhparam_main
#define DEFBITS 512
/* -inform arg - input format - default PEM (DER or PEM)
* -outform arg - output format - default PEM
* -in arg - input file - default stdin
* -out arg - output file - default stdout
* -dsaparam - read or generate DSA parameters, convert to DH
* -check - check the parameters are ok
* -noout
* -text
* -C
*/
static int MS_CALLBACK dh_cb(int p, int n, BN_GENCB *cb);
int MAIN(int, char **);
int MAIN(int argc, char **argv)
{
#ifndef OPENSSL_NO_ENGINE
ENGINE *e = NULL;
#endif
DH *dh=NULL;
int i,badops=0,text=0;
#ifndef OPENSSL_NO_DSA
int dsaparam=0;
#endif
BIO *in=NULL,*out=NULL;
int informat,outformat,check=0,noout=0,C=0,ret=1;
char *infile,*outfile,*prog;
char *inrand=NULL;
#ifndef OPENSSL_NO_ENGINE
char *engine=NULL;
#endif
int num = 0, g = 0;
apps_startup();
if (bio_err == NULL)
if ((bio_err=BIO_new(BIO_s_file())) != NULL)
BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
if (!load_config(bio_err, NULL))
goto end;
infile=NULL;
outfile=NULL;
informat=FORMAT_PEM;
outformat=FORMAT_PEM;
prog=argv[0];
argc--;
argv++;
while (argc >= 1)
{
if (strcmp(*argv,"-inform") == 0)
{
if (--argc < 1) goto bad;
informat=str2fmt(*(++argv));
}
else if (strcmp(*argv,"-outform") == 0)
{
if (--argc < 1) goto bad;
outformat=str2fmt(*(++argv));
}
else if (strcmp(*argv,"-in") == 0)
{
if (--argc < 1) goto bad;
infile= *(++argv);
}
else if (strcmp(*argv,"-out") == 0)
{
if (--argc < 1) goto bad;
outfile= *(++argv);
}
#ifndef OPENSSL_NO_ENGINE
else if (strcmp(*argv,"-engine") == 0)
{
if (--argc < 1) goto bad;
engine= *(++argv);
}
#endif
else if (strcmp(*argv,"-check") == 0)
check=1;
else if (strcmp(*argv,"-text") == 0)
text=1;
#ifndef OPENSSL_NO_DSA
else if (strcmp(*argv,"-dsaparam") == 0)
dsaparam=1;
#endif
else if (strcmp(*argv,"-C") == 0)
C=1;
else if (strcmp(*argv,"-noout") == 0)
noout=1;
else if (strcmp(*argv,"-2") == 0)
g=2;
else if (strcmp(*argv,"-5") == 0)
g=5;
else if (strcmp(*argv,"-rand") == 0)
{
if (--argc < 1) goto bad;
inrand= *(++argv);
}
else if (((sscanf(*argv,"%d",&num) == 0) || (num <= 0)))
goto bad;
argv++;
argc--;
}
if (badops)
{
bad:
BIO_printf(bio_err,"%s [options] [numbits]\n",prog);
BIO_printf(bio_err,"where options are\n");
BIO_printf(bio_err," -inform arg input format - one of DER PEM\n");
BIO_printf(bio_err," -outform arg output format - one of DER PEM\n");
BIO_printf(bio_err," -in arg input file\n");
BIO_printf(bio_err," -out arg output file\n");
#ifndef OPENSSL_NO_DSA
BIO_printf(bio_err," -dsaparam read or generate DSA parameters, convert to DH\n");
#endif
BIO_printf(bio_err," -check check the DH parameters\n");
BIO_printf(bio_err," -text print a text form of the DH parameters\n");
BIO_printf(bio_err," -C Output C code\n");
BIO_printf(bio_err," -2 generate parameters using 2 as the generator value\n");
BIO_printf(bio_err," -5 generate parameters using 5 as the generator value\n");
BIO_printf(bio_err," numbits number of bits in to generate (default 512)\n");
#ifndef OPENSSL_NO_ENGINE
BIO_printf(bio_err," -engine e use engine e, possibly a hardware device.\n");
#endif
BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
BIO_printf(bio_err," - load the file (or the files in the directory) into\n");
BIO_printf(bio_err," the random number generator\n");
BIO_printf(bio_err," -noout no output\n");
goto end;
}
ERR_load_crypto_strings();
#ifndef OPENSSL_NO_ENGINE
e = setup_engine(bio_err, engine, 0);
#endif
if (g && !num)
num = DEFBITS;
#ifndef OPENSSL_NO_DSA
if (dsaparam)
{
if (g)
{
BIO_printf(bio_err, "generator may not be chosen for DSA parameters\n");
goto end;
}
}
else
#endif
{
/* DH parameters */
if (num && !g)
g = 2;
}
if(num) {
BN_GENCB cb;
BN_GENCB_set(&cb, dh_cb, bio_err);
if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL)
{
BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n");
}
if (inrand != NULL)
BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
#ifndef OPENSSL_NO_DSA
if (dsaparam)
{
DSA *dsa = DSA_new();
BIO_printf(bio_err,"Generating DSA parameters, %d bit long prime\n",num);
if(!dsa || !DSA_generate_parameters_ex(dsa, num,
NULL, 0, NULL, NULL, &cb))
{
if(dsa) DSA_free(dsa);
ERR_print_errors(bio_err);
goto end;
}
dh = DSA_dup_DH(dsa);
DSA_free(dsa);
if (dh == NULL)
{
ERR_print_errors(bio_err);
goto end;
}
}
else
#endif
{
dh = DH_new();
BIO_printf(bio_err,"Generating DH parameters, %d bit long safe prime, generator %d\n",num,g);
BIO_printf(bio_err,"This is going to take a long time\n");
if(!dh || !DH_generate_parameters_ex(dh, num, g, &cb))
{
if(dh) DH_free(dh);
ERR_print_errors(bio_err);
goto end;
}
}
app_RAND_write_file(NULL, bio_err);
} else {
in=BIO_new(BIO_s_file());
if (in == NULL)
{
ERR_print_errors(bio_err);
goto end;
}
if (infile == NULL)
BIO_set_fp(in,stdin,BIO_NOCLOSE);
else
{
if (BIO_read_filename(in,infile) <= 0)
{
perror(infile);
goto end;
}
}
if (informat != FORMAT_ASN1 && informat != FORMAT_PEM)
{
BIO_printf(bio_err,"bad input format specified\n");
goto end;
}
#ifndef OPENSSL_NO_DSA
if (dsaparam)
{
DSA *dsa;
if (informat == FORMAT_ASN1)
dsa=d2i_DSAparams_bio(in,NULL);
else /* informat == FORMAT_PEM */
dsa=PEM_read_bio_DSAparams(in,NULL,NULL,NULL);
if (dsa == NULL)
{
BIO_printf(bio_err,"unable to load DSA parameters\n");
ERR_print_errors(bio_err);
goto end;
}
dh = DSA_dup_DH(dsa);
DSA_free(dsa);
if (dh == NULL)
{
ERR_print_errors(bio_err);
goto end;
}
}
else
#endif
{
if (informat == FORMAT_ASN1)
dh=d2i_DHparams_bio(in,NULL);
else /* informat == FORMAT_PEM */
dh=PEM_read_bio_DHparams(in,NULL,NULL,NULL);
if (dh == NULL)
{
BIO_printf(bio_err,"unable to load DH parameters\n");
ERR_print_errors(bio_err);
goto end;
}
}
/* dh != NULL */
}
out=BIO_new(BIO_s_file());
if (out == NULL)
{
ERR_print_errors(bio_err);
goto end;
}
if (outfile == NULL)
{
BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
{
BIO *tmpbio = BIO_new(BIO_f_linebuffer());
out = BIO_push(tmpbio, out);
}
#endif
}
else
{
if (BIO_write_filename(out,outfile) <= 0)
{
perror(outfile);
goto end;
}
}
if (text)
{
DHparams_print(out,dh);
}
if (check)
{
if (!DH_check(dh,&i))
{
ERR_print_errors(bio_err);
goto end;
}
if (i & DH_CHECK_P_NOT_PRIME)
printf("p value is not prime\n");
if (i & DH_CHECK_P_NOT_SAFE_PRIME)
printf("p value is not a safe prime\n");
if (i & DH_UNABLE_TO_CHECK_GENERATOR)
printf("unable to check the generator value\n");
if (i & DH_NOT_SUITABLE_GENERATOR)
printf("the g value is not a generator\n");
if (i == 0)
printf("DH parameters appear to be ok.\n");
}
if (C)
{
unsigned char *data;
int len,l,bits;
len=BN_num_bytes(dh->p);
bits=BN_num_bits(dh->p);
data=(unsigned char *)OPENSSL_malloc(len);
if (data == NULL)
{
perror("OPENSSL_malloc");
goto end;
}
printf("#ifndef HEADER_DH_H\n"
"#include <openssl/dh.h>\n"
"#endif\n");
printf("DH *get_dh%d()\n\t{\n",bits);
l=BN_bn2bin(dh->p,data);
printf("\tstatic unsigned char dh%d_p[]={",bits);
for (i=0; i<l; i++)
{
if ((i%12) == 0) printf("\n\t\t");
printf("0x%02X,",data[i]);
}
printf("\n\t\t};\n");
l=BN_bn2bin(dh->g,data);
printf("\tstatic unsigned char dh%d_g[]={",bits);
for (i=0; i<l; i++)
{
if ((i%12) == 0) printf("\n\t\t");
printf("0x%02X,",data[i]);
}
printf("\n\t\t};\n");
printf("\tDH *dh;\n\n");
printf("\tif ((dh=DH_new()) == NULL) return(NULL);\n");
printf("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n",
bits,bits);
printf("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n",
bits,bits);
printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n");
printf("\t\t{ DH_free(dh); return(NULL); }\n");
if (dh->length)
printf("\tdh->length = %ld;\n", dh->length);
printf("\treturn(dh);\n\t}\n");
OPENSSL_free(data);
}
if (!noout)
{
if (outformat == FORMAT_ASN1)
i=i2d_DHparams_bio(out,dh);
else if (outformat == FORMAT_PEM)
i=PEM_write_bio_DHparams(out,dh);
else {
BIO_printf(bio_err,"bad output format specified for outfile\n");
goto end;
}
if (!i)
{
BIO_printf(bio_err,"unable to write DH parameters\n");
ERR_print_errors(bio_err);
goto end;
}
}
ret=0;
end:
if (in != NULL) BIO_free(in);
if (out != NULL) BIO_free_all(out);
if (dh != NULL) DH_free(dh);
apps_shutdown();
OPENSSL_EXIT(ret);
}
/* dh_cb is identical to dsa_cb in apps/dsaparam.c */
static int MS_CALLBACK dh_cb(int p, int n, BN_GENCB *cb)
{
char c='*';
if (p == 0) c='.';
if (p == 1) c='+';
if (p == 2) c='*';
if (p == 3) c='\n';
BIO_write(cb->arg,&c,1);
(void)BIO_flush(cb->arg);
#ifdef LINT
p=n;
#endif
return 1;
}
#endif
| apache-2.0 |
rdmeneze/controller | FreeRTOS/Demo/Common/ethernet/uIP/uip-1.0/apps/webserver/httpd-cgi.c | 120 | 6180 | /**
* \addtogroup httpd
* @{
*/
/**
* \file
* Web server script interface
* \author
* Adam Dunkels <adam@sics.se>
*
*/
/*
* Copyright (c) 2001-2006, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This file is part of the uIP TCP/IP stack.
*
* $Id: httpd-cgi.c,v 1.2 2006/06/11 21:46:37 adam Exp $
*
*/
#include "uip.h"
#include "psock.h"
#include "httpd.h"
#include "httpd-cgi.h"
#include "httpd-fs.h"
#include <stdio.h>
#include <string.h>
HTTPD_CGI_CALL(file, "file-stats", file_stats);
HTTPD_CGI_CALL(tcp, "tcp-connections", tcp_stats);
HTTPD_CGI_CALL(net, "net-stats", net_stats);
static const struct httpd_cgi_call *calls[] = { &file, &tcp, &net, NULL };
/*---------------------------------------------------------------------------*/
static
PT_THREAD(nullfunction(struct httpd_state *s, char *ptr))
{
PSOCK_BEGIN(&s->sout);
PSOCK_END(&s->sout);
}
/*---------------------------------------------------------------------------*/
httpd_cgifunction
httpd_cgi(char *name)
{
const struct httpd_cgi_call **f;
/* Find the matching name in the table, return the function. */
for(f = calls; *f != NULL; ++f) {
if(strncmp((*f)->name, name, strlen((*f)->name)) == 0) {
return (*f)->function;
}
}
return nullfunction;
}
/*---------------------------------------------------------------------------*/
static unsigned short
generate_file_stats(void *arg)
{
char *f = (char *)arg;
return snprintf((char *)uip_appdata, UIP_APPDATA_SIZE, "%5u", httpd_fs_count(f));
}
/*---------------------------------------------------------------------------*/
static
PT_THREAD(file_stats(struct httpd_state *s, char *ptr))
{
PSOCK_BEGIN(&s->sout);
PSOCK_GENERATOR_SEND(&s->sout, generate_file_stats, strchr(ptr, ' ') + 1);
PSOCK_END(&s->sout);
}
/*---------------------------------------------------------------------------*/
static const char closed[] = /* "CLOSED",*/
{0x43, 0x4c, 0x4f, 0x53, 0x45, 0x44, 0};
static const char syn_rcvd[] = /* "SYN-RCVD",*/
{0x53, 0x59, 0x4e, 0x2d, 0x52, 0x43, 0x56,
0x44, 0};
static const char syn_sent[] = /* "SYN-SENT",*/
{0x53, 0x59, 0x4e, 0x2d, 0x53, 0x45, 0x4e,
0x54, 0};
static const char established[] = /* "ESTABLISHED",*/
{0x45, 0x53, 0x54, 0x41, 0x42, 0x4c, 0x49, 0x53, 0x48,
0x45, 0x44, 0};
static const char fin_wait_1[] = /* "FIN-WAIT-1",*/
{0x46, 0x49, 0x4e, 0x2d, 0x57, 0x41, 0x49,
0x54, 0x2d, 0x31, 0};
static const char fin_wait_2[] = /* "FIN-WAIT-2",*/
{0x46, 0x49, 0x4e, 0x2d, 0x57, 0x41, 0x49,
0x54, 0x2d, 0x32, 0};
static const char closing[] = /* "CLOSING",*/
{0x43, 0x4c, 0x4f, 0x53, 0x49,
0x4e, 0x47, 0};
static const char time_wait[] = /* "TIME-WAIT,"*/
{0x54, 0x49, 0x4d, 0x45, 0x2d, 0x57, 0x41,
0x49, 0x54, 0};
static const char last_ack[] = /* "LAST-ACK"*/
{0x4c, 0x41, 0x53, 0x54, 0x2d, 0x41, 0x43,
0x4b, 0};
static const char *states[] = {
closed,
syn_rcvd,
syn_sent,
established,
fin_wait_1,
fin_wait_2,
closing,
time_wait,
last_ack};
static unsigned short
generate_tcp_stats(void *arg)
{
struct uip_conn *conn;
struct httpd_state *s = (struct httpd_state *)arg;
conn = &uip_conns[s->count];
return snprintf((char *)uip_appdata, UIP_APPDATA_SIZE,
"<tr><td>%d</td><td>%u.%u.%u.%u:%u</td><td>%s</td><td>%u</td><td>%u</td><td>%c %c</td></tr>\r\n",
htons(conn->lport),
htons(conn->ripaddr[0]) >> 8,
htons(conn->ripaddr[0]) & 0xff,
htons(conn->ripaddr[1]) >> 8,
htons(conn->ripaddr[1]) & 0xff,
htons(conn->rport),
states[conn->tcpstateflags & UIP_TS_MASK],
conn->nrtx,
conn->timer,
(uip_outstanding(conn))? '*':' ',
(uip_stopped(conn))? '!':' ');
}
/*---------------------------------------------------------------------------*/
static
PT_THREAD(tcp_stats(struct httpd_state *s, char *ptr))
{
PSOCK_BEGIN(&s->sout);
for(s->count = 0; s->count < UIP_CONNS; ++s->count) {
if((uip_conns[s->count].tcpstateflags & UIP_TS_MASK) != UIP_CLOSED) {
PSOCK_GENERATOR_SEND(&s->sout, generate_tcp_stats, s);
}
}
PSOCK_END(&s->sout);
}
/*---------------------------------------------------------------------------*/
static unsigned short
generate_net_stats(void *arg)
{
struct httpd_state *s = (struct httpd_state *)arg;
return snprintf((char *)uip_appdata, UIP_APPDATA_SIZE,
"%5u\n", ((uip_stats_t *)&uip_stat)[s->count]);
}
static
PT_THREAD(net_stats(struct httpd_state *s, char *ptr))
{
PSOCK_BEGIN(&s->sout);
#if UIP_STATISTICS
for(s->count = 0; s->count < sizeof(uip_stat) / sizeof(uip_stats_t);
++s->count) {
PSOCK_GENERATOR_SEND(&s->sout, generate_net_stats, s);
}
#endif /* UIP_STATISTICS */
PSOCK_END(&s->sout);
}
/*---------------------------------------------------------------------------*/
/** @} */
| apache-2.0 |
rgrover/mbed | hal/targets/hal/TARGET_NXP/TARGET_LPC81X/gpio_irq_api.c | 129 | 4200 | /* mbed Microcontroller Library
* Copyright (c) 2006-2013 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 <stddef.h>
#include "cmsis.h"
#include "gpio_irq_api.h"
#include "mbed_error.h"
#define CHANNEL_NUM 8
#define LPC_GPIO_X LPC_PIN_INT
#define PININT_IRQ PININT0_IRQn
static uint32_t channel_ids[CHANNEL_NUM] = {0};
static gpio_irq_handler irq_handler;
static inline void handle_interrupt_in(uint32_t channel) {
uint32_t ch_bit = (1 << channel);
// Return immediately if:
// * The interrupt was already served
// * There is no user handler
// * It is a level interrupt, not an edge interrupt
if ( ((LPC_GPIO_X->IST & ch_bit) == 0) ||
(channel_ids[channel] == 0 ) ||
(LPC_GPIO_X->ISEL & ch_bit ) ) return;
if ((LPC_GPIO_X->IENR & ch_bit) && (LPC_GPIO_X->RISE & ch_bit)) {
irq_handler(channel_ids[channel], IRQ_RISE);
LPC_GPIO_X->RISE = ch_bit;
}
if ((LPC_GPIO_X->IENF & ch_bit) && (LPC_GPIO_X->FALL & ch_bit)) {
irq_handler(channel_ids[channel], IRQ_FALL);
}
LPC_GPIO_X->IST = ch_bit;
}
void gpio_irq0(void) {handle_interrupt_in(0);}
void gpio_irq1(void) {handle_interrupt_in(1);}
void gpio_irq2(void) {handle_interrupt_in(2);}
void gpio_irq3(void) {handle_interrupt_in(3);}
void gpio_irq4(void) {handle_interrupt_in(4);}
void gpio_irq5(void) {handle_interrupt_in(5);}
void gpio_irq6(void) {handle_interrupt_in(6);}
void gpio_irq7(void) {handle_interrupt_in(7);}
int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) {
if (pin == NC) return -1;
irq_handler = handler;
int found_free_channel = 0;
int i = 0;
for (i=0; i<CHANNEL_NUM; i++) {
if (channel_ids[i] == 0) {
channel_ids[i] = id;
obj->ch = i;
found_free_channel = 1;
break;
}
}
if (!found_free_channel) return -1;
/* Enable AHB clock to the GPIO domain. */
LPC_SYSCON->SYSAHBCLKCTRL |= (1<<6);
LPC_SYSCON->PINTSEL[obj->ch] = pin;
// Interrupt Wake-Up Enable
LPC_SYSCON->STARTERP0 |= 1 << obj->ch;
void (*channels_irq)(void) = NULL;
switch (obj->ch) {
case 0: channels_irq = &gpio_irq0; break;
case 1: channels_irq = &gpio_irq1; break;
case 2: channels_irq = &gpio_irq2; break;
case 3: channels_irq = &gpio_irq3; break;
case 4: channels_irq = &gpio_irq4; break;
case 5: channels_irq = &gpio_irq5; break;
case 6: channels_irq = &gpio_irq6; break;
case 7: channels_irq = &gpio_irq7; break;
}
NVIC_SetVector((IRQn_Type)(PININT_IRQ + obj->ch), (uint32_t)channels_irq);
NVIC_EnableIRQ((IRQn_Type)(PININT_IRQ + obj->ch));
return 0;
}
void gpio_irq_free(gpio_irq_t *obj) {
channel_ids[obj->ch] = 0;
LPC_SYSCON->STARTERP0 &= ~(1 << obj->ch);
}
void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) {
unsigned int ch_bit = (1 << obj->ch);
// Clear interrupt
if (!(LPC_GPIO_X->ISEL & ch_bit))
LPC_GPIO_X->IST = ch_bit;
// Edge trigger
LPC_GPIO_X->ISEL &= ~ch_bit;
if (event == IRQ_RISE) {
if (enable) {
LPC_GPIO_X->IENR |= ch_bit;
} else {
LPC_GPIO_X->IENR &= ~ch_bit;
}
} else {
if (enable) {
LPC_GPIO_X->IENF |= ch_bit;
} else {
LPC_GPIO_X->IENF &= ~ch_bit;
}
}
}
void gpio_irq_enable(gpio_irq_t *obj) {
NVIC_EnableIRQ((IRQn_Type)(PININT_IRQ + obj->ch));
}
void gpio_irq_disable(gpio_irq_t *obj) {
NVIC_DisableIRQ((IRQn_Type)(PININT_IRQ + obj->ch));
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.