code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30
values | license stringclasses 15
values | size int64 3 1.01M |
|---|---|---|---|---|---|
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>killerbee.openear.gps.gps'</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="killerbee-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="killerbee-module.html">Package killerbee</a> ::
<a href="killerbee.openear-module.html">Package openear</a> ::
<a href="killerbee.openear.gps-module.html">Package gps</a> ::
Module gps'
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="killerbee.openear.gps.gps%27-module.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== MODULE DESCRIPTION ==================== -->
<h1 class="epydoc">Module gps'</h1><p class="nomargin-top"><span class="codelink"><a href="killerbee.openear.gps.gps%27-pysrc.html">source code</a></span></p>
<!-- ==================== CLASSES ==================== -->
<a name="section-Classes"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Classes</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Classes"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="killerbee.openear.gps.gps%27.gps-class.html" class="summary-name">gps</a><br />
Client interface to a running gpsd instance.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="killerbee.openear.gps.gps%27.gpsdata-class.html" class="summary-name">gpsdata</a><br />
Position, track, velocity and status information returned by a GPS.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a href="killerbee.openear.gps.gps%27.gpsfix-class.html" class="summary-name">gpsfix</a>
</td>
</tr>
</table>
<!-- ==================== FUNCTIONS ==================== -->
<a name="section-Functions"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Functions</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Functions"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="isnan"></a><span class="summary-sig-name">isnan</span>(<span class="summary-sig-arg">x</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="killerbee.openear.gps.gps%27-pysrc.html#isnan">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== VARIABLES ==================== -->
<a name="section-Variables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Variables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="AIS_SET"></a><span class="summary-name">AIS_SET</span> = <code title="268435456">268435456</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="ALTITUDE_SET"></a><span class="summary-name">ALTITUDE_SET</span> = <code title="16">16</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="ATTITUDE_SET"></a><span class="summary-name">ATTITUDE_SET</span> = <code title="16384">16384</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="AUXDATA_SET"></a><span class="summary-name">AUXDATA_SET</span> = <code title="2147483648">2147483648</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="CLIMBERR_SET"></a><span class="summary-name">CLIMBERR_SET</span> = <code title="2097152">2097152</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="CLIMB_SET"></a><span class="summary-name">CLIMB_SET</span> = <code title="128">128</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="DEVICEID_SET"></a><span class="summary-name">DEVICEID_SET</span> = <code title="16777216">16777216</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="DEVICELIST_SET"></a><span class="summary-name">DEVICELIST_SET</span> = <code title="8388608">8388608</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="DEVICE_SET"></a><span class="summary-name">DEVICE_SET</span> = <code title="4194304">4194304</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="DOP_SET"></a><span class="summary-name">DOP_SET</span> = <code title="1024">1024</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="ERROR_SET"></a><span class="summary-name">ERROR_SET</span> = <code title="33554432">33554432</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="GPSD_PORT"></a><span class="summary-name">GPSD_PORT</span> = <code title="'2947'"><code class="variable-quote">'</code><code class="variable-string">2947</code><code class="variable-quote">'</code></code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="HERR_SET"></a><span class="summary-name">HERR_SET</span> = <code title="4096">4096</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="LATLON_SET"></a><span class="summary-name">LATLON_SET</span> = <code title="8">8</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="MAXCHANNELS"></a><span class="summary-name">MAXCHANNELS</span> = <code title="20">20</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="MODE_2D"></a><span class="summary-name">MODE_2D</span> = <code title="2">2</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="MODE_3D"></a><span class="summary-name">MODE_3D</span> = <code title="3">3</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="MODE_NO_FIX"></a><span class="summary-name">MODE_NO_FIX</span> = <code title="1">1</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="MODE_SET"></a><span class="summary-name">MODE_SET</span> = <code title="512">512</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="NaN"></a><span class="summary-name">NaN</span> = <code title="nan">nan</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="ONLINE_SET"></a><span class="summary-name">ONLINE_SET</span> = <code title="1">1</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="PACKET_SET"></a><span class="summary-name">PACKET_SET</span> = <code title="536870912">536870912</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="POLICY_SET"></a><span class="summary-name">POLICY_SET</span> = <code title="32768">32768</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="RAW_SET"></a><span class="summary-name">RAW_SET</span> = <code title="131072">131072</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="RTCM2_SET"></a><span class="summary-name">RTCM2_SET</span> = <code title="67108864">67108864</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="RTCM3_SET"></a><span class="summary-name">RTCM3_SET</span> = <code title="134217728">134217728</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="SATELLITE_SET"></a><span class="summary-name">SATELLITE_SET</span> = <code title="65536">65536</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="SIGNAL_STRENGTH_UNKNOWN"></a><span class="summary-name">SIGNAL_STRENGTH_UNKNOWN</span> = <code title="nan">nan</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="SPEEDERR_SET"></a><span class="summary-name">SPEEDERR_SET</span> = <code title="524288">524288</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="SPEED_SET"></a><span class="summary-name">SPEED_SET</span> = <code title="32">32</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="STATUS_DGPS_FIX"></a><span class="summary-name">STATUS_DGPS_FIX</span> = <code title="2">2</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="STATUS_FIX"></a><span class="summary-name">STATUS_FIX</span> = <code title="1">1</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="STATUS_NO_FIX"></a><span class="summary-name">STATUS_NO_FIX</span> = <code title="0">0</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="STATUS_SET"></a><span class="summary-name">STATUS_SET</span> = <code title="256">256</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="TIMERR_SET"></a><span class="summary-name">TIMERR_SET</span> = <code title="4">4</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="TIME_SET"></a><span class="summary-name">TIME_SET</span> = <code title="2">2</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="TRACKERR_SET"></a><span class="summary-name">TRACKERR_SET</span> = <code title="1048576">1048576</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="TRACK_SET"></a><span class="summary-name">TRACK_SET</span> = <code title="64">64</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="UNION_SET"></a><span class="summary-name">UNION_SET</span> = <code title="511707136">511707136</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="USED_SET"></a><span class="summary-name">USED_SET</span> = <code title="262144">262144</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="VERR_SET"></a><span class="summary-name">VERR_SET</span> = <code title="8192">8192</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="VERSION_SET"></a><span class="summary-name">VERSION_SET</span> = <code title="2048">2048</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_DEVICE"></a><span class="summary-name">WATCH_DEVICE</span> = <code title="64">64</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_DISABLE"></a><span class="summary-name">WATCH_DISABLE</span> = <code title="0">0</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_ENABLE"></a><span class="summary-name">WATCH_ENABLE</span> = <code title="1">1</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_JSON"></a><span class="summary-name">WATCH_JSON</span> = <code title="2">2</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_NEWSTYLE"></a><span class="summary-name">WATCH_NEWSTYLE</span> = <code title="128">128</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_NMEA"></a><span class="summary-name">WATCH_NMEA</span> = <code title="4">4</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_OLDSTYLE"></a><span class="summary-name">WATCH_OLDSTYLE</span> = <code title="65536">65536</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_RARE"></a><span class="summary-name">WATCH_RARE</span> = <code title="8">8</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_RAW"></a><span class="summary-name">WATCH_RAW</span> = <code title="16">16</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="WATCH_SCALED"></a><span class="summary-name">WATCH_SCALED</span> = <code title="32">32</code>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="__package__"></a><span class="summary-name">__package__</span> = <code title="'killerbee.openear.gps'"><code class="variable-quote">'</code><code class="variable-string">killerbee.openear.gps</code><code class="variable-quote">'</code></code>
</td>
</tr>
</table>
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="killerbee-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Mon Dec 30 17:49:12 2013
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| rfmcpherson/killerbee | doc/killerbee.openear.gps.gps'-module.html | HTML | bsd-3-clause | 22,847 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_COMMAND_BUFFER_SERVICE_SHADER_TRANSLATOR_H_
#define GPU_COMMAND_BUFFER_SERVICE_SHADER_TRANSLATOR_H_
#include <string>
#include "base/basictypes.h"
#include "base/containers/hash_tables.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/observer_list.h"
#include "gpu/gpu_export.h"
#if defined(ANGLE_DX11)
#include "third_party/angle_dx11/include/GLSLANG/ShaderLang.h"
#else
#include "third_party/angle/include/GLSLANG/ShaderLang.h"
#endif
namespace gpu {
namespace gles2 {
// Translates a GLSL ES 2.0 shader to desktop GLSL shader, or just
// validates GLSL ES 2.0 shaders on a true GLSL ES implementation.
class ShaderTranslatorInterface {
public:
enum GlslImplementationType {
kGlsl,
kGlslES
};
enum GlslBuiltInFunctionBehavior {
kGlslBuiltInFunctionOriginal,
kGlslBuiltInFunctionEmulated
};
struct VariableInfo {
VariableInfo()
: type(0),
size(0) {
}
VariableInfo(int _type, int _size, std::string _name)
: type(_type),
size(_size),
name(_name) {
}
bool operator==(
const ShaderTranslatorInterface::VariableInfo& other) const {
return type == other.type &&
size == other.size &&
strcmp(name.c_str(), other.name.c_str()) == 0;
}
int type;
int size;
std::string name; // name in the original shader source.
};
// Mapping between variable name and info.
typedef base::hash_map<std::string, VariableInfo> VariableMap;
// Mapping between hashed name and original name.
typedef base::hash_map<std::string, std::string> NameMap;
// Initializes the translator.
// Must be called once before using the translator object.
virtual bool Init(
ShShaderType shader_type,
ShShaderSpec shader_spec,
const ShBuiltInResources* resources,
GlslImplementationType glsl_implementation_type,
GlslBuiltInFunctionBehavior glsl_built_in_function_behavior) = 0;
// Translates the given shader source.
// Returns true if translation is successful, false otherwise.
virtual bool Translate(const char* shader) = 0;
// The following functions return results from the last translation.
// The results are NULL/empty if the translation was unsuccessful.
// A valid info-log is always returned irrespective of whether translation
// was successful or not.
virtual const char* translated_shader() const = 0;
virtual const char* info_log() const = 0;
virtual const VariableMap& attrib_map() const = 0;
virtual const VariableMap& uniform_map() const = 0;
virtual const NameMap& name_map() const = 0;
// Return a string that is unique for a specfic set of options that would
// possibly effect compilation.
virtual std::string GetStringForOptionsThatWouldEffectCompilation() const = 0;
protected:
virtual ~ShaderTranslatorInterface() {}
};
// Implementation of ShaderTranslatorInterface
class GPU_EXPORT ShaderTranslator
: public base::RefCounted<ShaderTranslator>,
NON_EXPORTED_BASE(public ShaderTranslatorInterface) {
public:
class DestructionObserver {
public:
DestructionObserver();
virtual ~DestructionObserver();
virtual void OnDestruct(ShaderTranslator* translator) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
};
ShaderTranslator();
// Overridden from ShaderTranslatorInterface.
virtual bool Init(
ShShaderType shader_type,
ShShaderSpec shader_spec,
const ShBuiltInResources* resources,
GlslImplementationType glsl_implementation_type,
GlslBuiltInFunctionBehavior glsl_built_in_function_behavior) OVERRIDE;
// Overridden from ShaderTranslatorInterface.
virtual bool Translate(const char* shader) OVERRIDE;
// Overridden from ShaderTranslatorInterface.
virtual const char* translated_shader() const OVERRIDE;
virtual const char* info_log() const OVERRIDE;
// Overridden from ShaderTranslatorInterface.
virtual const VariableMap& attrib_map() const OVERRIDE;
virtual const VariableMap& uniform_map() const OVERRIDE;
virtual const NameMap& name_map() const OVERRIDE;
virtual std::string GetStringForOptionsThatWouldEffectCompilation() const
OVERRIDE;
void AddDestructionObserver(DestructionObserver* observer);
void RemoveDestructionObserver(DestructionObserver* observer);
private:
friend class base::RefCounted<ShaderTranslator>;
virtual ~ShaderTranslator();
void ClearResults();
int GetCompileOptions() const;
ShHandle compiler_;
ShBuiltInResources compiler_options_;
scoped_ptr<char[]> translated_shader_;
scoped_ptr<char[]> info_log_;
VariableMap attrib_map_;
VariableMap uniform_map_;
NameMap name_map_;
bool implementation_is_glsl_es_;
bool needs_built_in_function_emulation_;
ObserverList<DestructionObserver> destruction_observers_;
DISALLOW_COPY_AND_ASSIGN(ShaderTranslator);
};
} // namespace gles2
} // namespace gpu
#endif // GPU_COMMAND_BUFFER_SERVICE_SHADER_TRANSLATOR_H_
| hujiajie/pa-chromium | gpu/command_buffer/service/shader_translator.h | C | bsd-3-clause | 5,188 |
module FunIn3 where
--The application of a function is replaced by the right-hand side of the definition,
--with actual parameters replacing formals.
--In this example, unfold 'addthree'.
--This example aims to test the elimination of extra parentheses when unfolding
--a function defintion.
main :: Int -> Int
main = \x -> case x of
1 -> 1 + main 0
0 ->((1 + 2) + 3)
addthree :: Int -> Int -> Int -> Int
addthree a b c = a + b + c
| mpickering/HaRe | old/testing/unfoldDef/FunIn3_TokOut.hs | Haskell | bsd-3-clause | 469 |
package scala.lms
package internal
import util.GraphUtil
import scala.collection.mutable
import java.util.IdentityHashMap
import scala.collection.JavaConversions._
trait Scheduling {
val IR: Expressions
import IR._
def getUnsortedSchedule(scope: List[Stm])(result: Any): List[Stm] = {
getSchedule(scope)(result, false)
}
// checks if a and b share at least one element. O(N^2), but with no allocation and possible early exit.
def containsAny(a: List[Sym[Any]], b: List[Sym[Any]]): Boolean = {
var aIter = a
while (aIter.nonEmpty) {
val aElem = aIter.head
aIter = aIter.tail
var bIter = b
while (bIter.nonEmpty) {
if (bIter.head eq aElem) return true
bIter = bIter.tail
}
}
false
}
//TBD: not used?
def getStronglySortedSchedule(scope: List[Stm])(result: Any): List[Stm] = {
def deps(st: List[Sym[Any]]): List[Stm] =
scope.filter(d => containsAny(st, d.lhs))
// scope.filter(d => (st intersect d.lhs).nonEmpty)
def allSyms(r: Any) = syms(r) ++ softSyms(r)
val xx = GraphUtil.stronglyConnectedComponents[Stm](deps(allSyms(result)), t => deps(allSyms(t.rhs)))
xx.foreach { x =>
if (x.length > 1) {
printerr("warning: recursive schedule for result " + result + ": " + x)
(new Exception) printStackTrace
}
}
xx.flatten.reverse
}
//performance hotspot!
//should be O(1) wrt 'scope' (nodes in graph), try to keep this as efficient as possible
protected def scheduleDepsWithIndex(syms: List[Sym[Any]], cache: IdentityHashMap[Sym[Any], (Stm,Int)]): List[Stm] = {
//syms.map(cache.get(_)).filter(_ ne null).distinct.sortBy(_._2).map(_._1)
val sortedSet = new java.util.TreeSet[(Stm,Int)](
new java.util.Comparator[(Stm,Int)] { def compare(a:(Stm,Int), b:(Stm,Int)) = if (b._2 < a._2) -1 else if (b._2 == a._2) 0 else 1 }
)
for (sym <- syms) {
val stm = cache.get(sym)
if (stm ne null) sortedSet.add(stm)
}
var res: List[Stm] = Nil
val iter = sortedSet.iterator //return stms in the original order given by 'scope'
while (iter.hasNext) {
res ::= iter.next._1
}
res
}
protected def buildScopeIndex(scope: List[Stm]): IdentityHashMap[Sym[Any], (Stm,Int)] = {
val cache = new IdentityHashMap[Sym[Any], (Stm,Int)]
var idx = 0
for (stm <- scope) {
for (s <- stm.lhs) cache.put(s, (stm,idx)) //remember the original order of the stms
idx += 1
}
cache
}
def getSchedule(scope: List[Stm])(result: Any, sort: Boolean = true): List[Stm] = {
val scopeIndex = buildScopeIndex(scope)
val xx = GraphUtil.stronglyConnectedComponents[Stm](scheduleDepsWithIndex(syms(result), scopeIndex), t => scheduleDepsWithIndex(syms(t.rhs), scopeIndex))
if (sort) xx.foreach { x =>
if (x.length > 1) {
printerr("warning: recursive schedule for result " + result + ": " + x)
(new Exception) printStackTrace
}
}
xx.flatten.reverse
}
def getScheduleM(scope: List[Stm])(result: Any, cold: Boolean, hot: Boolean): List[Stm] = {
def mysyms(st: Any) = {
val db = symsFreq(st).groupBy(_._1).mapValues(_.map(_._2).sum).toList
assert(syms(st).toSet == db.map(_._1).toSet, "different list of syms: "+syms(st)+"!="+db+" for "+st)
if (cold && hot) db.map(_._1)
else if (cold && !hot) db.withFilter(_._2 < 100.0).map(_._1)
else if (!cold && hot) db.withFilter(_._2 > 0.75).map(_._1)
else db.withFilter(p=>p._2 > 0.75 && p._2 < 100.0).map(_._1)
}
val scopeIndex = buildScopeIndex(scope)
GraphUtil.stronglyConnectedComponents[Stm](scheduleDepsWithIndex(mysyms(result), scopeIndex), t => scheduleDepsWithIndex(mysyms(t.rhs), scopeIndex)).flatten.reverse
}
/** begin performance hotspot **/
/*
for each symbol s in sts, find all statements that depend on it.
we need to stop when we reach the statement where s is bound.
it would be tempting to do only one scc call but then we mix
up the locations where different symbols are bound.
*/
def getFatDependentStuff(scope: List[Stm])(sts: List[Sym[Any]]): List[Stm] = {
if (sts.isEmpty) return Nil
/*
precompute:
s => all d in scope such that: d.lhs contains s || syms(d.rhs).contains(s)
st => all d in scope such that: boundSyms(d.rhs) contains st
*/
//type IdentityHashMap[K,V] = HashMap[K,V]
// IdentityHashMap appears faster than scala.collection.mutable.HashMap here (based on perf. testing)
// possible improvement: use an integer hashmap that works directly with sym ids
val lhsCache = new IdentityHashMap[Sym[Any], List[Stm]]()
val symsCache = new IdentityHashMap[Sym[Any], List[Stm]]()
val boundSymsCache = new IdentityHashMap[Sym[Any], List[Stm]]()
//val boundSymsCache = new IdentityHashMap[Sym[Any], Set[Stm]]()
def infix_getOrElse[K,V](map: IdentityHashMap[K, V], s: K, f: => V) = {
var res = map.get(s) //map(s)
if (res == null) res = f
res
}
def putDef(map: IdentityHashMap[Sym[Any], List[Stm]], s: Sym[Any], d: Stm): Unit = {
var res = map.get(s) //map(s)
if (res == null) res = Nil
//map.getOrElse(s, Nil) match {
res match {
case `d`::ds =>
case ds => map.update(s,d::ds) //map.put(s,d::ds)
}
}
def putDefSet(map: IdentityHashMap[Sym[Any], Set[Stm]], s: Sym[Any], d: Stm): Unit = {
var res = map(s) //map.get(s)
if (res == null) {
res = Set[Stm]()
map.update(s,res) //map.put(s,res)
}
res += d
}
for (d <- scope) {
d.lhs.foreach(s => putDef(lhsCache, s, d))
syms(d.rhs).foreach(s => putDef(symsCache, s, d))
boundSyms(d.rhs).foreach(st => putDef(boundSymsCache, st, d))
tunnelSyms(d.rhs).foreach(st => putDef(boundSymsCache, st, d)) // treat tunnel like bound
}
/*
optimization:
traverse syms by ascending id. if sym s1 is used by s2, do not evaluate further
uses of s2 because they are already there.
CAVEAT: TRANSFORMERS !!!
assumption: if s2 uses s1, the scope of s2 is completely included in s1's scope:
val A = loop { s1 => ... val B = sum { s2 => ... val y = s2 + s1; .../* use y */ ... } }
once we reach y the second time (from s2) we can stop, because the uses of
y have been tracked up to A, which includes all of B
*/
val seen = new mutable.HashSet[Sym[Any]]
def getDepStuff(st: Sym[Any]) = {
// could also precalculate uses, but computing all combinations eagerly is also expensive
def uses(s: Sym[Any]): List[Stm] = if (seen(s)) Nil else {
//seen += s
lhsCache.getOrElse(s,Nil) ::: symsCache.getOrElse(s,Nil) filterNot (boundSymsCache.getOrElse(st, Nil) contains _)
}
GraphUtil.stronglyConnectedComponents[Stm](
uses(st),
t => t.lhs flatMap uses
).flatten
}
/*
reference impl:*/
val res = sts.flatMap(getDepStuff).distinct
/*if (sts.contains(Sym(1064))) {
println("dep on x1064:")
res.foreach { r =>
println(" " + r)
}
}*/
res
// CAVEAT: TRANSFORMERS !!! see CloseWorldRestage app in Delite
//sts.sortBy(_.id).flatMap(getDepStuff)
}
/** end performance hotspot **/
}
| astojanov/virtualization-lms-core | src/internal/Scheduling.scala | Scala | bsd-3-clause | 7,393 |
// t0288.cc
// "ambiguous function template instantiation"
// 2005-08-03: This appears to be fixed by the switch to
// the new mtype module.
namespace std
{
template < class _CharT > struct char_traits;
}
typedef int ptrdiff_t;
extern "C"
{
typedef struct __locale_struct
{
}
*__locale_t;
};
typedef struct __pthread_attr_s
{
}
pthread_barrierattr_t;
namespace std
{
typedef ptrdiff_t streamsize;
template < typename _CharT, typename _Traits =
char_traits < _CharT > >class basic_ios;
template < typename _CharT, typename _Traits =
char_traits < _CharT > >class basic_streambuf;
}
extern "C++"
{
namespace std
{
class exception
{
};
}
}
namespace std
{
template < typename _CharT, typename _Traits > class basic_streambuf
{
public:typedef _CharT char_type;
typedef _Traits traits_type;
typedef basic_streambuf < char_type, traits_type > __streambuf_type;
friend streamsize __copy_streambufs <> (basic_ios < char_type,
traits_type > &__ios,
__streambuf_type * __sbin,
__streambuf_type * __sbout);
};
template < typename _CharT,
typename _Traits > streamsize __copy_streambufs (basic_ios < _CharT,
_Traits > &__ios,
basic_streambuf < _CharT,
_Traits > *__sbin,
basic_streambuf < _CharT,
_Traits > *__sbout)
{
try
{
}
catch (exception & __fail)
{
}
}
extern template streamsize __copy_streambufs (basic_ios < wchar_t > &,
basic_streambuf < wchar_t > *,
basic_streambuf < wchar_t >
*);
}
| BackupTheBerlios/codemorpher-svn | trunk/elsa/elsa/in/t0288.cc | C++ | bsd-3-clause | 1,589 |
/*
Copyright (c) 2014, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "device/common/nn_workload_data.h"
#include "device/cpu/api_internal/nn_device_interface_0_internal.h"
#include "layer_normalization_avx2.h"
#include <immintrin.h>
#include <string.h>
#include <thread>
#include <vector>
#include "device/cpu/api_internal/data_helper.h"
// NN_CODE_UNREACHABLE signal to supporting compiler that specific location in code cannot be reached
#if defined _MSC_VER
# define NN_UNREACHABLE_CODE __assume(0)
#endif
#if defined __GNUC__
# if (__GNUC__ * 100 + __GNUC_MINOR__) >= 405
# define NN_UNREACHABLE_CODE __builtin_unreachable()
# else
# define NN_UNREACHABLE_CODE
# endif
#endif
#if defined __clang__
# if __has_builtin(__builtin_unreachable)
# define NN_UNREACHABLE_CODE __builtin_unreachable()
# else
# define NN_UNREACHABLE_CODE
# endif
#endif
// SIMD width for this implementation
const auto C_simd_width = sizeof(__m256) / sizeof(float);
static const auto C_max_acc = 12u;
static const auto C_batch_size = C_simd_width;
static const auto C_data_stride = C_batch_size * C_max_acc;
namespace layer {
///////////////////////////////////////////////////////////////////////////////////////////////////
// forward implementation
template<uint32_t T_SIZE>
void normalization_compute_block_linear_single(
float* &input_ptr,
float* &output_ptr,
const __m256 coeff_a,
const __m256 coeff_b)
{
// We are not using table of registers and unroll pragmas
// due to compiler which have issues with register allocation
// and needs special, obvious treatment. Template immediate
// arguments matching will remove all conditions in this code.
__m256 acc0, acc1, acc2, acc3, acc4,
acc5, acc6, acc7, acc8, acc9,
acc10, acc11, acc12, acc13, acc14, acc15;
// Load inputs.
if (T_SIZE >= 1) acc0 = _mm256_loadu_ps(input_ptr + 0 * C_batch_size);
if (T_SIZE >= 2) acc1 = _mm256_loadu_ps(input_ptr + 1 * C_batch_size);
if (T_SIZE >= 3) acc2 = _mm256_loadu_ps(input_ptr + 2 * C_batch_size);
if (T_SIZE >= 4) acc3 = _mm256_loadu_ps(input_ptr + 3 * C_batch_size);
if (T_SIZE >= 5) acc4 = _mm256_loadu_ps(input_ptr + 4 * C_batch_size);
if (T_SIZE >= 6) acc5 = _mm256_loadu_ps(input_ptr + 5 * C_batch_size);
if (T_SIZE >= 7) acc6 = _mm256_loadu_ps(input_ptr + 6 * C_batch_size);
if (T_SIZE >= 8) acc7 = _mm256_loadu_ps(input_ptr + 7 * C_batch_size);
if (T_SIZE >= 9) acc8 = _mm256_loadu_ps(input_ptr + 8 * C_batch_size);
if (T_SIZE >= 10) acc9 = _mm256_loadu_ps(input_ptr + 9 * C_batch_size);
if (T_SIZE >= 11) acc10 = _mm256_loadu_ps(input_ptr + 10 * C_batch_size);
if (T_SIZE >= 12) acc11 = _mm256_loadu_ps(input_ptr + 11 * C_batch_size);
if (T_SIZE >= 13) acc12 = _mm256_loadu_ps(input_ptr + 12 * C_batch_size);
if (T_SIZE >= 14) acc13 = _mm256_loadu_ps(input_ptr + 13 * C_batch_size);
if (T_SIZE >= 15) acc14 = _mm256_loadu_ps(input_ptr + 14 * C_batch_size);
// Perform a*x + b
if (T_SIZE >= 1) acc0 = _mm256_fmadd_ps(coeff_a, acc0, coeff_b);
if (T_SIZE >= 2) acc1 = _mm256_fmadd_ps(coeff_a, acc1, coeff_b);
if (T_SIZE >= 3) acc2 = _mm256_fmadd_ps(coeff_a, acc2, coeff_b);
if (T_SIZE >= 4) acc3 = _mm256_fmadd_ps(coeff_a, acc3, coeff_b);
if (T_SIZE >= 5) acc4 = _mm256_fmadd_ps(coeff_a, acc4, coeff_b);
if (T_SIZE >= 6) acc5 = _mm256_fmadd_ps(coeff_a, acc5, coeff_b);
if (T_SIZE >= 7) acc6 = _mm256_fmadd_ps(coeff_a, acc6, coeff_b);
if (T_SIZE >= 8) acc7 = _mm256_fmadd_ps(coeff_a, acc7, coeff_b);
if (T_SIZE >= 9) acc8 = _mm256_fmadd_ps(coeff_a, acc8, coeff_b);
if (T_SIZE >= 10) acc9 = _mm256_fmadd_ps(coeff_a, acc9, coeff_b);
if (T_SIZE >= 11) acc10 = _mm256_fmadd_ps(coeff_a, acc10, coeff_b);
if (T_SIZE >= 12) acc11 = _mm256_fmadd_ps(coeff_a, acc11, coeff_b);
if (T_SIZE >= 13) acc12 = _mm256_fmadd_ps(coeff_a, acc12, coeff_b);
if (T_SIZE >= 14) acc13 = _mm256_fmadd_ps(coeff_a, acc13, coeff_b);
if (T_SIZE >= 15) acc14 = _mm256_fmadd_ps(coeff_a, acc14, coeff_b);
// Store results.
if (T_SIZE >= 1) _mm256_storeu_ps(output_ptr + 0 * C_batch_size, acc0);
if (T_SIZE >= 2) _mm256_storeu_ps(output_ptr + 1 * C_batch_size, acc1);
if (T_SIZE >= 3) _mm256_storeu_ps(output_ptr + 2 * C_batch_size, acc2);
if (T_SIZE >= 4) _mm256_storeu_ps(output_ptr + 3 * C_batch_size, acc3);
if (T_SIZE >= 5) _mm256_storeu_ps(output_ptr + 4 * C_batch_size, acc4);
if (T_SIZE >= 6) _mm256_storeu_ps(output_ptr + 5 * C_batch_size, acc5);
if (T_SIZE >= 7) _mm256_storeu_ps(output_ptr + 6 * C_batch_size, acc6);
if (T_SIZE >= 8) _mm256_storeu_ps(output_ptr + 7 * C_batch_size, acc7);
if (T_SIZE >= 9) _mm256_storeu_ps(output_ptr + 8 * C_batch_size, acc8);
if (T_SIZE >= 10) _mm256_storeu_ps(output_ptr + 9 * C_batch_size, acc9);
if (T_SIZE >= 11) _mm256_storeu_ps(output_ptr + 10 * C_batch_size, acc10);
if (T_SIZE >= 12) _mm256_storeu_ps(output_ptr + 11 * C_batch_size, acc11);
if (T_SIZE >= 13) _mm256_storeu_ps(output_ptr + 12 * C_batch_size, acc12);
if (T_SIZE >= 14) _mm256_storeu_ps(output_ptr + 13 * C_batch_size, acc13);
if (T_SIZE >= 15) _mm256_storeu_ps(output_ptr + 14 * C_batch_size, acc14);
input_ptr += T_SIZE*C_batch_size;
output_ptr += T_SIZE*C_batch_size;
}
void normalization_elementwise_linear_f32::run_normalization_work_item_linear_single_batch8(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x];
const auto output_width = output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1;
const auto num_full_blocks = output_width / C_max_acc;
const auto partial_block_size = output_width % C_max_acc;
const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x] * C_batch_size;
const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x] * C_batch_size;
auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset];
auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset];
const __m256 coeff_a = _mm256_set1_ps(alpha);
const __m256 coeff_b = _mm256_set1_ps(beta);
{
for (auto block = 0u; block < num_full_blocks; ++block)
{
// Run computation.
normalization_compute_block_linear_single<C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b);
}
switch (partial_block_size)
{
case 0: break;
case 1: normalization_compute_block_linear_single< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 2: normalization_compute_block_linear_single< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 3: normalization_compute_block_linear_single< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 4: normalization_compute_block_linear_single< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 5: normalization_compute_block_linear_single< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 6: normalization_compute_block_linear_single< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 7: normalization_compute_block_linear_single< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 8: normalization_compute_block_linear_single< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 9: normalization_compute_block_linear_single< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 10: normalization_compute_block_linear_single<10>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 11: normalization_compute_block_linear_single<11>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 12: normalization_compute_block_linear_single<12>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 13: normalization_compute_block_linear_single<13>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 14: normalization_compute_block_linear_single<14>(input_buffer, output_buffer, coeff_a, coeff_b); break;
default: NN_UNREACHABLE_CODE;
}
}
}
void normalization_elementwise_linear_f32::run_normalization_work_item_linear_single_batch8X(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
const auto BatchSize = output_view->parent->lengths.t[NN_DATA_COORD_n];
const auto NoBatches = BatchSize / C_batch_size;
const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x] * BatchSize;
const auto output_width = (output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1) * BatchSize;
const auto num_full_blocks = (output_width / C_simd_width) / C_max_acc;
const auto partial_block_size = (output_width / C_simd_width ) % C_max_acc;
const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x] * BatchSize;
const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x] * BatchSize;
//for (auto itrB = 0; itrB < BatchSize / C_batch_size; ++itrB)
{
auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset];
auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset];
const __m256 coeff_a = _mm256_set1_ps(alpha);
const __m256 coeff_b = _mm256_set1_ps(beta);
for (auto block = 0u; block < num_full_blocks; ++block)
{
// Run computation.
normalization_compute_block_linear_single<C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b);
}
switch (partial_block_size)
{
case 0: break;
case 1: normalization_compute_block_linear_single< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 2: normalization_compute_block_linear_single< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 3: normalization_compute_block_linear_single< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 4: normalization_compute_block_linear_single< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 5: normalization_compute_block_linear_single< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 6: normalization_compute_block_linear_single< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 7: normalization_compute_block_linear_single< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 8: normalization_compute_block_linear_single< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 9: normalization_compute_block_linear_single< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 10: normalization_compute_block_linear_single<10>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 11: normalization_compute_block_linear_single<11>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 12: normalization_compute_block_linear_single<12>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 13: normalization_compute_block_linear_single<13>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 14: normalization_compute_block_linear_single<14>(input_buffer, output_buffer, coeff_a, coeff_b); break;
default: NN_UNREACHABLE_CODE;
}
}
}
template<uint32_t T_NUM_ITERATIONS>
void normalization_compute_subsimd_linear_single(
float* &input_ptr,
float* &output_ptr,
const float coeff_a,
const float coeff_b)
{
for (auto iteration = 0u; iteration < T_NUM_ITERATIONS; ++iteration)
{
*output_ptr = (*input_ptr) * coeff_a + coeff_b;
++input_ptr;
++output_ptr;
}
}
void normalization_elementwise_linear_f32::run_normalization_work_item_linear_single_latency(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x];
const auto output_width = output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1;
const auto num_full_blocks = output_width / C_data_stride;
const auto partial_block_size = (output_width / C_simd_width) % C_max_acc;
const auto subsimd_block_size = output_width % C_simd_width;
const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x];
const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x];
auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset];
auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset];
const __m256 coeff_a = _mm256_set1_ps(alpha);
const __m256 coeff_b = _mm256_set1_ps(beta);
for (auto block = 0u; block < num_full_blocks; ++block)
{
// Run computation.
normalization_compute_block_linear_single<C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b);
}
switch (partial_block_size)
{
case 0: break;
case 1: normalization_compute_block_linear_single< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 2: normalization_compute_block_linear_single< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 3: normalization_compute_block_linear_single< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 4: normalization_compute_block_linear_single< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 5: normalization_compute_block_linear_single< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 6: normalization_compute_block_linear_single< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 7: normalization_compute_block_linear_single< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 8: normalization_compute_block_linear_single< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 9: normalization_compute_block_linear_single< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 10: normalization_compute_block_linear_single<10>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 11: normalization_compute_block_linear_single<11>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 12: normalization_compute_block_linear_single<12>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 13: normalization_compute_block_linear_single<13>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 14: normalization_compute_block_linear_single<14>(input_buffer, output_buffer, coeff_a, coeff_b); break;
default: NN_UNREACHABLE_CODE;
}
switch (subsimd_block_size)
{
case 0: break;
case 1: normalization_compute_subsimd_linear_single<1>(input_buffer, output_buffer, alpha, beta); break;
case 2: normalization_compute_subsimd_linear_single<2>(input_buffer, output_buffer, alpha, beta); break;
case 3: normalization_compute_subsimd_linear_single<3>(input_buffer, output_buffer, alpha, beta); break;
case 4: normalization_compute_subsimd_linear_single<4>(input_buffer, output_buffer, alpha, beta); break;
case 5: normalization_compute_subsimd_linear_single<5>(input_buffer, output_buffer, alpha, beta); break;
case 6: normalization_compute_subsimd_linear_single<6>(input_buffer, output_buffer, alpha, beta); break;
case 7: normalization_compute_subsimd_linear_single<7>(input_buffer, output_buffer, alpha, beta); break;
default: NN_UNREACHABLE_CODE;
}
}
void normalization_elementwise_linear_f32::choose_normalization_work_item_linear_single_batching_mode(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
auto batch_size = input_view->parent->lengths.t[NN_DATA_COORD_n];
switch (batch_size)
{
case 1:
run_normalization_work_item_linear_single_latency(input_view, output_view);
break;
case 8:
run_normalization_work_item_linear_single_batch8(input_view, output_view);
break;
case 16:
case 24:
case 32:
case 48:
run_normalization_work_item_linear_single_batch8X(input_view, output_view);
break;
default:
break;
}
}
struct normalization_elementwise_linear_f32_request_handle {
normalization_elementwise_linear_f32 *primitive;
const nn::workload_data<float> *input_view;
nn::workload_data<float> *output_view;
};
void unpack_1d_normalization_callback_handle(
void* void_handle)
{
auto handle = reinterpret_cast<normalization_elementwise_linear_f32_request_handle *>(void_handle);
handle->primitive->choose_normalization_work_item_linear_single_batching_mode(handle->input_view,
handle->output_view);
}
void normalization_elementwise_linear_f32::run_multithreaded_1d_normalization_work_item(
const nn::workload_data<float> *input, nn::workload_data<float> *output) {
auto num_hardware_threads = std::min(static_cast<decltype(device->thread_pool.get_num_threads())>(18), device->thread_pool.get_num_threads());
const auto item_view_length =
output->view_end.t[NN_DATA_COORD_x] - output->view_begin.t[NN_DATA_COORD_x] + 1;
const auto items_per_thread = item_view_length / num_hardware_threads;
const auto items_modulo = item_view_length % num_hardware_threads;
// Check if we have enough data to cover all threads.
if (items_per_thread == 0 && items_modulo < 2)
{
// Its tiny data - just do it single threaded way.
choose_normalization_work_item_linear_single_batching_mode(input, output);
}
else
{
// Not all threads will be used.
if (items_per_thread == 0)
num_hardware_threads = items_modulo;
// Full cores utilization version.
std::vector<normalization_elementwise_linear_f32_request_handle> request_handles(num_hardware_threads);
std::vector<const nn::workload_data<float> *> input_views(num_hardware_threads);
std::vector<nn::workload_data<float> *> output_views(num_hardware_threads);
uint32_t* thread_items_sums = static_cast<uint32_t*>(alloca(num_hardware_threads * sizeof(uint32_t)));
if (thread_items_sums == nullptr) throw std::bad_alloc();
// Distribute elements more evenly.
auto elements_left = items_modulo;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_items_sums[thread_id] = items_per_thread;
if (elements_left)
{
++thread_items_sums[thread_id];
--elements_left;
}
}
// Now create table of thread sums.
auto thread_sum = 0u;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_sum += thread_items_sums[thread_id];
thread_items_sums[thread_id] = thread_sum;
}
// Fill slave work items.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
auto work_begin = 0u;
if (thread_id > 0u)
work_begin = thread_items_sums[thread_id - 1];
auto work_end = thread_items_sums[thread_id] - 1;
// Replace nn_workload_datas pointers with views.
nn_workload_data_coords_t nn_view_begin =
{
0,
work_begin,
0,
0,
0,
0
};
nn_workload_data_coords_t nn_view_end =
{
input->get_length(NN_DATA_COORD_n) - 1,
work_end,
input->get_length(NN_DATA_COORD_y) - 1,
input->get_length(NN_DATA_COORD_z) - 1,
input->get_length(NN_DATA_COORD_p) - 1,
input->get_length(NN_DATA_COORD_q) - 1
};
input_views[thread_id] = new nn::workload_data<float>(*input, nn_view_begin, nn_view_end);
output_views[thread_id] = new nn::workload_data<float>(*output, nn_view_begin, nn_view_end);
}
// Run threads.
std::vector<nn_multithreaded_request> job(num_hardware_threads);
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
request_handles[thread_id].primitive = this;
request_handles[thread_id].input_view = input_views[thread_id];
request_handles[thread_id].output_view = output_views[thread_id];
job[thread_id].callback = unpack_1d_normalization_callback_handle;
job[thread_id].request_handle = &request_handles[thread_id];
}
// Wait for all sub threads.
device->thread_pool.push_job(job);
// Cleanup dynamic memory.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
delete input_views[thread_id];
delete output_views[thread_id];
}
}
}
void normalization_elementwise_linear_f32::forward(const nn::workload_data<float> *input,
nn::workload_data<float> *output) {
nn_workload_data_coords_t in_out_view_coords =
{
input->parent->lengths.t[NN_DATA_COORD_n],
input->parent->buffer_size / static_cast<uint32_t>(sizeof(float)) / input->parent->lengths.t[NN_DATA_COORD_n],
1,
1,
1,
1
};
nn_workload_data_layout_t in_out_view_layout = nn::workload_data<float>::layout.nxyzpq;
nn::workload_data<float>* input_view = new nn::workload_data<float>(NN_WORKLOAD_DATA_TAG_UNKNOWN, input->parent->data_buffer, in_out_view_coords, in_out_view_layout);
nn::workload_data<float>* output_view = new nn::workload_data<float>(NN_WORKLOAD_DATA_TAG_UNKNOWN, output->parent->data_buffer, in_out_view_coords, in_out_view_layout);
if (device->thread_pool.get_num_threads() > 1)
{
run_multithreaded_1d_normalization_work_item(input_view, output_view);
}
else
{
choose_normalization_work_item_linear_single_batching_mode(input_view, output_view);
}
delete output_view;
delete input_view;
}
void normalization_elementwise_linear_f32::forward(const std::vector<const nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> ¶meters, const std::vector<nn_workload_data_t *> &outputs)
{
assert(inputs.size() == 1);
assert(parameters.size() == 0);
assert(outputs.size() == 1);
forward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]),
reinterpret_cast<nn::workload_data<float> *>(outputs[0]));
}
__m256 _inner_mm256_invpow075_ps(__m256 arg)
{
__m256i e = _mm256_slli_epi32(
_mm256_sub_epi32(
_mm256_and_si256(
_mm256_castps_si256(arg),
_mm256_set1_epi32(0x7f800000)),
_mm256_set1_epi32(0x3f800000)),
1);
__m256 p0 = _mm256_castsi256_ps(
_mm256_srli_epi32(
_mm256_add_epi32(
_mm256_mullo_epi32(
_mm256_srai_epi32(
_mm256_and_si256(
e,
_mm256_set1_epi32(0xfc000000)),
2),
_mm256_set1_epi32(-3)),
_mm256_set1_epi32(0x7f000000)),
1));
__m256 p1 = _mm256_blendv_ps(
_mm256_set1_ps(0.59460355750136053335874998528f),
_mm256_set1_ps(1.0f),
_mm256_castsi256_ps(
_mm256_cmpeq_epi32(
_mm256_and_si256(
e,
_mm256_set1_epi32(1<<24)),
_mm256_set1_epi32(0))));
__m256 p2 = _mm256_blendv_ps(
_mm256_set1_ps(0.35355339059327376220042218105f),
_mm256_set1_ps(1.0f),
_mm256_castsi256_ps(
_mm256_cmpeq_epi32(
_mm256_and_si256(
e,
_mm256_set1_epi32(2<<24)),
_mm256_set1_epi32(0))));
arg = _mm256_castsi256_ps(
_mm256_or_si256(
_mm256_and_si256(
_mm256_castps_si256(arg),
_mm256_set1_epi32(0x007fffff)),
_mm256_set1_epi32(0x3f800000)));
__m256 intermediate_result;
intermediate_result = _mm256_fmadd_ps(arg, _mm256_set1_ps(-0.06251362156237f), _mm256_set1_ps(0.56657226995864f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(-2.12314847503624f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(4.22879355263332f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(-4.79039952143706f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(3.18069569544757f));
intermediate_result =
_mm256_mul_ps(
_mm256_mul_ps(
p0,
p1),
_mm256_mul_ps(
p2,
intermediate_result));
return intermediate_result;
}
void normalization_response_across_maps_f32::run_3d_normalization_work_item(const nn::workload_data<float> *input_view,
nn::workload_data<float> *output_view) {
const auto input_column_size = input_view->parent->lengths.t[NN_DATA_COORD_z];
const auto input_row_size = input_view->parent->lengths.t[NN_DATA_COORD_x] * input_column_size;
const auto input_batch_size = input_view->parent->lengths.t[NN_DATA_COORD_y] * input_row_size;
const auto output_column_size = output_view->parent->lengths.t[NN_DATA_COORD_z];
const auto output_row_size = output_view->parent->lengths.t[NN_DATA_COORD_x] * output_column_size;
const auto output_batch_size = output_view->parent->lengths.t[NN_DATA_COORD_y] * output_row_size;
auto input_buffer = static_cast<float*>(input_view->parent->data_buffer);
auto output_buffer = static_cast<float*>(output_view->parent->data_buffer);
// Const data.
const uint32_t permutation_mask[8] = { 1, 2, 3, 4, 5, 6, 7, 0 };
uint32_t first_load_mask[8] = { 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000 };
uint32_t last_load_mask[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
const auto neighbourhood = n / 2;
for (uint32_t neighbour = 0; neighbour < neighbourhood; ++neighbour)
{
first_load_mask[neighbour] ^= 0x80000000;
last_load_mask[neighbour] ^= 0x80000000;
}
// Permuters and masks.
const __m256i forward_permuter = _mm256_loadu_si256((__m256i*)permutation_mask);
const __m256i first_masker = _mm256_loadu_si256((__m256i*)first_load_mask);
const __m256i last_masker = _mm256_loadu_si256((__m256i*)last_load_mask);
for (uint32_t batch = input_view->view_begin.t[NN_DATA_COORD_n]; batch <= input_view->view_end.t[NN_DATA_COORD_n]; ++batch)
{
for (uint32_t row = input_view->view_begin.t[NN_DATA_COORD_y], out_row = output_view->view_begin.t[NN_DATA_COORD_y];
row <= input_view->view_end.t[NN_DATA_COORD_y];
++row, ++out_row)
{
for (uint32_t column = input_view->view_begin.t[NN_DATA_COORD_x], out_column = output_view->view_begin.t[NN_DATA_COORD_x];
column <= input_view->view_end.t[NN_DATA_COORD_x];
++column, ++out_column)
{
const auto input_address = &input_buffer[batch*input_batch_size + row*input_row_size + column*input_column_size];
const auto output_address = &output_buffer[batch*output_batch_size + out_row*output_row_size + out_column*output_column_size];
// Prepare first data chunk.
__m256 source_tmp = _mm256_maskload_ps(input_address - neighbourhood, first_masker);
source_tmp = _mm256_mul_ps(source_tmp, source_tmp);
for (uint32_t feature_map = input_view->view_begin.t[NN_DATA_COORD_z], out_feature_map = output_view->view_begin.t[NN_DATA_COORD_z];
feature_map <= input_view->view_end.t[NN_DATA_COORD_z];
feature_map += C_simd_width, out_feature_map += C_simd_width)
{
// Initialize accumulator.
__m256 acc = _mm256_setzero_ps();
// Move previous saved chunk to first and load new one as a next.
__m256 source_first = source_tmp;
__m256 source_second =
(feature_map + C_simd_width <= input_view->view_end.t[NN_DATA_COORD_z])
? _mm256_loadu_ps(input_address + feature_map - neighbourhood + C_simd_width)
: _mm256_maskload_ps(input_address + feature_map - neighbourhood + C_simd_width, last_masker);
// Square of new chunk and save for next iteration.
source_tmp = source_second = _mm256_mul_ps(source_second, source_second);
// Required for final computation.
__m256 source_raw = _mm256_loadu_ps(input_address + feature_map);
// Forward permute - five times.
for (int i = 0; i < n; ++i)
{
acc = _mm256_add_ps(source_first, acc);
source_first = _mm256_permutevar8x32_ps(source_first, forward_permuter);
source_second = _mm256_permutevar8x32_ps(source_second, forward_permuter);
source_first = _mm256_blend_ps(source_first, source_second, 0x80);
}
// Do k + alpha * acc.
acc = _mm256_fmadd_ps(acc, _mm256_set1_ps(alpha), _mm256_set1_ps(k));
// Magic happens here. (acc^-0.75)
acc = _inner_mm256_invpow075_ps(acc);
// Multiply with input data.
acc = _mm256_mul_ps(acc, source_raw);
// Save data.
_mm256_storeu_ps(output_address + out_feature_map, acc);
}
}
}
}
}
struct normalization_response_across_maps_f32_request_handle {
normalization_response_across_maps_f32 *primitive;
const nn::workload_data<float> *input_view;
nn::workload_data<float> *output_view;
};
struct normalization_response_across_maps_f32_backward_request_handle {
normalization_response_across_maps_f32 *primitive;
const nn::workload_data<float> *forward_input;
const nn::workload_data<float> *forward_output;
const nn::workload_data<float> *backward_input;
nn::workload_data<float> *backward_output;
};
void unpack_3d_normalization_callback_handle(
void* void_handle)
{
auto handle = reinterpret_cast<normalization_response_across_maps_f32_request_handle *>(void_handle);
handle->primitive->run_3d_normalization_work_item(handle->input_view, handle->output_view);
}
void unpack_3d_normalization_callback_handle_backward(
void* void_handle)
{
auto handle = reinterpret_cast<normalization_response_across_maps_f32_backward_request_handle *>(void_handle);
handle->primitive->backward(handle->forward_input, handle->forward_output, handle->backward_input, handle->backward_output);
}
void normalization_response_across_maps_f32::dispatch_backward(
const nn::workload_data<float> *forward_input,
const nn::workload_data<float> *forward_output,
const nn::workload_data<float> *backward_input,
nn::workload_data<float> *backward_output)
{
const auto num_batch_items =
(backward_output->view_end.t[NN_DATA_COORD_n] - backward_output->view_begin.t[NN_DATA_COORD_n] + 1);
const auto total_workers = num_batch_items;
if (device->thread_pool.get_num_threads() < 2 || total_workers < 2)
{
// Its tiny data or there is only one thread available - just do it singlethreaded way.
backward(forward_input, forward_output, backward_input, backward_output);
}
else
{
// Full cores utilization version.
std::vector<nn::workload_data<float> *> backprop_output_delta_views(total_workers);
// Fill slave work items.
for (auto batch_item = 0u; batch_item < num_batch_items; ++batch_item)
{
auto item_in_pool = batch_item;
// Replace nn_workload_datas pointers with views.
nn_workload_data_coords_t output_view_begin =
{
batch_item,
0,
0,
0,
0,
0
};
nn_workload_data_coords_t output_view_end =
{
batch_item,
backward_output->get_length(NN_DATA_COORD_x) - 1,
backward_output->get_length(NN_DATA_COORD_y) - 1,
backward_output->get_length(NN_DATA_COORD_z) - 1,
backward_output->get_length(NN_DATA_COORD_p) - 1,
backward_output->get_length(NN_DATA_COORD_q) - 1
};
backprop_output_delta_views[item_in_pool] =
new nn::workload_data<float>(*backward_output, output_view_begin, output_view_end);
}
// Run threads.
std::vector<nn_multithreaded_request> job(total_workers);
std::vector<normalization_response_across_maps_f32_backward_request_handle> request_handles(total_workers);
for (auto item_in_pool = 0u; item_in_pool < total_workers; ++item_in_pool)
{
request_handles[item_in_pool].primitive = this;
request_handles[item_in_pool].forward_input = forward_input;
request_handles[item_in_pool].forward_output = forward_output;
request_handles[item_in_pool].backward_input = backward_input;
request_handles[item_in_pool].backward_output = backprop_output_delta_views[item_in_pool];
job[item_in_pool].callback = unpack_3d_normalization_callback_handle_backward;
job[item_in_pool].request_handle = &request_handles[item_in_pool];
}
// Wait for all sub threads.
device->thread_pool.push_job(job);
// Cleanup dynamic memory.
for (auto item_in_pool = 0u; item_in_pool < total_workers; ++item_in_pool)
{
delete backprop_output_delta_views[item_in_pool];
}
}
}
void normalization_response_across_maps_f32::run_multithreaded_3d_normalization_work_item(
const nn::workload_data<float> *input, nn::workload_data<float> *output) {
auto num_hardware_threads = std::min(device->thread_pool.get_num_threads(), max_threads);
const auto item_view_length =
output->view_end.t[NN_DATA_COORD_y] - output->view_begin.t[NN_DATA_COORD_y] + 1;
const auto items_per_thread = item_view_length / num_hardware_threads;
const auto items_modulo = item_view_length % num_hardware_threads;
// Check if we have enough data to cover all threads.
if (items_per_thread == 0 && items_modulo < 2)
{
// Its tiny data - just do it singlethreaded way.
run_3d_normalization_work_item(input, output);
}
else
{
// Full cores utilization version.
// Not all threads will be used.
if (items_per_thread == 0)
num_hardware_threads = items_modulo;
std::vector<normalization_response_across_maps_f32_request_handle> request_handles(num_hardware_threads);
std::vector<const nn::workload_data<float> *> input_views(num_hardware_threads);
std::vector<nn::workload_data<float> *> output_views(num_hardware_threads);
uint32_t* thread_items_sums = static_cast<uint32_t*>(alloca(num_hardware_threads * sizeof(uint32_t)));
if (thread_items_sums == nullptr) throw std::bad_alloc();
// Distribute elements more evenly.
auto elements_left = items_modulo;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_items_sums[thread_id] = items_per_thread;
if (elements_left)
{
++thread_items_sums[thread_id];
--elements_left;
}
}
// Now create table of thread sums.
auto thread_sum = 0u;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_sum += thread_items_sums[thread_id];
thread_items_sums[thread_id] = thread_sum;
}
// Fill slave work items.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
auto work_begin = 0u;
if (thread_id > 0u)
work_begin = thread_items_sums[thread_id - 1];
auto work_end = thread_items_sums[thread_id] - 1;
// Replace nn_workload_datas pointers with views.
nn_workload_data_coords_t nn_view_begin =
{
0,
0,
work_begin,
0,
0,
0
};
nn_workload_data_coords_t nn_view_end =
{
input->get_length(NN_DATA_COORD_n) - 1,
input->get_length(NN_DATA_COORD_x) - 1,
work_end,
input->get_length(NN_DATA_COORD_z) - 1,
input->get_length(NN_DATA_COORD_p) - 1,
input->get_length(NN_DATA_COORD_q) - 1
};
input_views[thread_id] = new nn::workload_data<float>(*input, nn_view_begin, nn_view_end);
output_views[thread_id] = new nn::workload_data<float>(*output, nn_view_begin, nn_view_end);
}
// Run threads.
std::vector<nn_multithreaded_request> job(num_hardware_threads);
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
request_handles[thread_id].primitive = this;
request_handles[thread_id].input_view = input_views[thread_id];
request_handles[thread_id].output_view = output_views[thread_id];
job[thread_id].callback = unpack_3d_normalization_callback_handle;
job[thread_id].request_handle = &request_handles[thread_id];
}
// Wait for all sub threads.
device->thread_pool.push_job(job);
// Cleanup dynamic memory.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
delete input_views[thread_id];
delete output_views[thread_id];
}
}
}
void normalization_response_across_maps_f32::forward(const nn::workload_data<float> *input,
nn::workload_data<float> *output) {
if (device->thread_pool.get_num_threads() > 1) {
run_multithreaded_3d_normalization_work_item(input, output);
}
else {
run_3d_normalization_work_item(input, output);
}
}
void normalization_response_across_maps_f32::forward(const std::vector<const nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> ¶meters, const std::vector<nn_workload_data_t *> &outputs)
{
assert(inputs.size() == 1);
assert(parameters.size() == 0);
assert(outputs.size() == 1);
forward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]),
reinterpret_cast<nn::workload_data<float> *>(outputs[0]));
}
__m256 _internal_mm256_pow2_ps(__m256 arg)
{
__m256i e = _mm256_sub_epi32(_mm256_cvttps_epi32(arg), _mm256_and_si256(_mm256_castps_si256(_mm256_cmp_ps(arg, _mm256_setzero_ps(), _CMP_LT_OQ)), _mm256_set1_epi32(1)));
arg = _mm256_sub_ps(arg, _mm256_cvtepi32_ps(e));
arg =
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
arg
, _mm256_set1_ps(0.00021871895714413f)
, _mm256_set1_ps(0.00123905464987147f))
, arg
, _mm256_set1_ps(0.00968412797528994f))
, arg
, _mm256_set1_ps(0.0554807914042966f))
, arg
, _mm256_set1_ps(0.240230343637606f))
, arg
, _mm256_set1_ps(0.693146963375785f))
, arg
, _mm256_set1_ps(0.999999999869321f));
__m256 res = _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_add_epi32(e, _mm256_set1_epi32(127)), 23));
res = _mm256_mul_ps(res, arg);
return res;
}
__m256 _internal_mm256_log2_ps(__m256 input)
{
__m256i tmp = _mm256_castps_si256(input);
__m256i e = _mm256_and_si256(tmp, _mm256_set1_epi32(0xff800000));
input = _mm256_castsi256_ps(_mm256_or_si256(_mm256_xor_si256(tmp, e), _mm256_set1_epi32(0x40000000)));
e = _mm256_srai_epi32(_mm256_sub_epi32(e, _mm256_set1_epi32(0x3f900000)), 23);
input =
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
input
, _mm256_set1_ps(-3.92272173215165e-4f)
, _mm256_set1_ps(8.44188448699613e-3f))
, input
, _mm256_set1_ps(-7.80873452751869e-2f))
, input
, _mm256_set1_ps(4.06812574432218e-1f))
, input
, _mm256_set1_ps(-1.32744857721956f))
, input
, _mm256_set1_ps(3.04806680788937f))
, input
, _mm256_set1_ps(-2.03647726245336f));
return _mm256_add_ps(input, _mm256_cvtepi32_ps(e));
}
__m256 _internal_generic_mm256_pow_ps(__m256 base, __m256 exponent)
{
return _internal_mm256_pow2_ps(_mm256_mul_ps(_internal_mm256_log2_ps(base), exponent));
}
__m256 _internal_2_33_mm256_pow_ps(__m256 base)
{
auto x = _mm256_castsi256_ps(_mm256_or_si256(_mm256_and_si256(_mm256_castps_si256(base), _mm256_set1_epi32(0x007fffff)), _mm256_set1_epi32(0x3f800000)));
auto e4 = _mm256_sub_epi32(_mm256_srai_epi32(_mm256_and_si256(_mm256_castps_si256(base), _mm256_set1_epi32(0x7f800000)), 21), _mm256_set1_epi32(508));
auto e4_3i = _mm256_srai_epi32(_mm256_add_epi32(_mm256_mullo_epi32(e4, _mm256_set1_epi32(0x5555)), _mm256_set1_epi32(0x1000)), 16);
auto e4_3f = _mm256_sub_epi32(e4, _mm256_mullo_epi32(e4_3i, _mm256_set1_epi32(3)));
auto e0 = _mm256_add_ps(_mm256_set1_ps(1.0f), _mm256_castsi256_ps(_mm256_and_si256(_mm256_cmpgt_epi32(e4_3f, _mm256_set1_epi32(0)), _mm256_castps_si256(_mm256_set1_ps(0.2599210498948731647672106072782f)))));
auto e1 = _mm256_add_ps(_mm256_set1_ps(1.0f), _mm256_castsi256_ps(_mm256_and_si256(_mm256_cmpgt_epi32(e4_3f, _mm256_set1_epi32(1)), _mm256_castps_si256(_mm256_set1_ps(0.2599210498948731647672106072782f)))));
auto e = _mm256_mul_ps(_mm256_mul_ps(_mm256_castsi256_ps(_mm256_slli_epi32(_mm256_add_epi32(e4_3i, _mm256_set1_epi32(127)), 23)), e0), e1);
x =
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
x
, _mm256_set1_ps(-6.13621063256050e-4f)
, _mm256_set1_ps(2.81846524230542e-3f))
, x
, _mm256_set1_ps(7.23755774062622e-3f))
, x
, _mm256_set1_ps(-9.05150071637931e-2f))
, x
, _mm256_set1_ps(4.30600295045482e-1f))
, x
, _mm256_set1_ps(7.04368603164122e-1f))
, x
, _mm256_set1_ps(-5.38962929654863e-2f));
return _mm256_mul_ps(_mm256_mul_ps(x, e), base);
}
enum EXP_APPROX
{
APPROX_GENERIC,
APPROX_2_33
};
template<EXP_APPROX T_approx> __m256 _internal_mm256_pow_ps (__m256 base, __m256 exponent);
template<> __m256 _internal_mm256_pow_ps<APPROX_GENERIC>(__m256 base, __m256 exponent) {return _internal_generic_mm256_pow_ps(base, exponent);}
template<> __m256 _internal_mm256_pow_ps<APPROX_2_33> (__m256 base, __m256 exponent) {return _internal_2_33_mm256_pow_ps(base);}
template<EXP_APPROX T_approx>
void backward_inner_template(
const nn::workload_data<float> *forward_input,
const nn::workload_data<float> *forward_output,
const nn::workload_data<float> *backward_input,
nn::workload_data<float> *backward_output,
const uint32_t n,
const float alpha,
const float beta)
{
const uint32_t range = (n - 1) / 2;
const auto forward_input_buffer = reinterpret_cast<float*>(forward_input->parent->data_buffer);
const auto forward_output_buffer = reinterpret_cast<float*>(forward_output->parent->data_buffer);
const auto backward_input_buffer = reinterpret_cast<float*>(backward_input->parent->data_buffer);
const auto backward_output_buffer = reinterpret_cast<float*>(backward_output->parent->data_buffer);
const auto input_depth = forward_input->parent->lengths.t[NN_DATA_COORD_z];
const auto input_width = forward_input->parent->lengths.t[NN_DATA_COORD_x];
const auto input_height = forward_input->parent->lengths.t[NN_DATA_COORD_y];
const auto output_depth = forward_output->parent->lengths.t[NN_DATA_COORD_z];
const auto output_width = forward_output->parent->lengths.t[NN_DATA_COORD_x];
const auto output_height = forward_output->parent->lengths.t[NN_DATA_COORD_y];
assert(input_depth == output_depth);
__m256i mask;
const __m256 alpha_vec = _mm256_set1_ps(alpha);
const __m256 beta_vec = _mm256_set1_ps(beta);
const __m256 const_vec = _mm256_set1_ps(-2.0f);
const __m256 pow_vec = _mm256_set1_ps(1.0f + 1.0f / beta);
uint32_t* initial_load_mask = reinterpret_cast<uint32_t*>(alloca((output_depth + n - 1) * sizeof(float)));
uint32_t load_mask[C_simd_width];
uint32_t load_mask_id = 0;
for(uint32_t i = 0; i < range; ++i, ++load_mask_id)
initial_load_mask[load_mask_id] = 0;
for(uint32_t i = 0; i < input_depth; ++i, ++load_mask_id)
initial_load_mask[load_mask_id] = 0xFFFFFFFF;
for(uint32_t i = 0; i < range; ++i, ++load_mask_id)
initial_load_mask[load_mask_id] = 0;
for (uint32_t batch = backward_output->view_begin.t[NN_DATA_COORD_n]; batch <= backward_output->view_end.t[NN_DATA_COORD_n]; ++batch)
{
for (uint32_t row = backward_output->view_begin.t[NN_DATA_COORD_y];
row <= backward_output->view_end.t[NN_DATA_COORD_y];
++row)
{
for (uint32_t column = backward_output->view_begin.t[NN_DATA_COORD_x];
column <= backward_output->view_end.t[NN_DATA_COORD_x];
++column)
{
const auto forward_input_ptr = forward_input_buffer
+ column * input_depth
+ row * input_depth * input_width
+ batch * input_depth * input_width * input_height;
const auto forward_output_ptr = forward_output_buffer
+ column * output_depth
+ row * output_depth * output_width
+ batch * output_depth * output_width * output_height;
const auto backward_input_ptr = backward_input_buffer
+ column * output_depth
+ row * output_depth * output_width
+ batch * output_depth * output_width * output_height;
#pragma forceinline recursive
for (uint32_t in_feature_map = backward_output->view_begin.t[NN_DATA_COORD_z];
in_feature_map <= backward_output->view_end.t[NN_DATA_COORD_z];
in_feature_map += C_simd_width)
{
__m256 derivative_accumulator = _mm256_setzero_ps();
for (int32_t out_feature_map = (int32_t)in_feature_map - (int32_t)range;
out_feature_map <= (int32_t)in_feature_map + (int32_t)range;
++out_feature_map)
{
const __m256i mask = _mm256_loadu_si256((__m256i*)(initial_load_mask + out_feature_map + range));
const __m256 n_out = _mm256_maskload_ps(forward_input_ptr + out_feature_map, mask);
const __m256 a_out = _mm256_maskload_ps(forward_output_ptr + out_feature_map, mask);
const __m256 n_in = _mm256_load_ps(forward_input_ptr + in_feature_map);
const __m256 error_in = _mm256_maskload_ps(backward_input_ptr + out_feature_map, mask);
// This code corresponds to:
// acc = -2.0f * alpha * beta * n_out * n_in * std::pow(a_out / n_out, 1.0f + 1.0f / beta);
__m256 acc = _mm256_mul_ps(
_mm256_mul_ps(
_internal_mm256_pow_ps<T_approx>(
_mm256_div_ps(a_out, n_out),
pow_vec),
n_in),
_mm256_mul_ps(
_mm256_mul_ps(const_vec, alpha_vec),
_mm256_mul_ps(beta_vec, n_out)));
acc = _mm256_and_ps(acc, _mm256_castsi256_ps(mask));
derivative_accumulator = _mm256_fmadd_ps(acc, error_in, derivative_accumulator);
}
{
const __m256i mask = _mm256_loadu_si256((__m256i*)(initial_load_mask + in_feature_map + range));
const __m256 n_out = _mm256_maskload_ps(forward_input_ptr + in_feature_map, mask);
const __m256 a_out = _mm256_maskload_ps(forward_output_ptr + in_feature_map, mask);
const __m256 error_in = _mm256_maskload_ps(backward_input_ptr + in_feature_map, mask);
__m256 acc = _mm256_and_ps(_mm256_div_ps(a_out, n_out), _mm256_castsi256_ps(mask));
derivative_accumulator = _mm256_fmadd_ps(acc, error_in, derivative_accumulator);
}
_mm256_store_ps( backward_output_buffer
+ in_feature_map
+ column * input_depth
+ row * input_depth * input_width
+ batch * input_depth * input_width * input_height
, derivative_accumulator);
}
}
}
}
}
void normalization_response_across_maps_f32::backward(
const nn::workload_data<float> *forward_input,
const nn::workload_data<float> *forward_output,
const nn::workload_data<float> *backward_input,
nn::workload_data<float> *backward_output)
{
if(beta == 0.75f)
{
// Fast approximated exponent = 2.333f.
backward_inner_template<APPROX_2_33>(
forward_input,
forward_output,
backward_input,
backward_output,
n,
alpha,
beta);
}
else
{
// Generic case.
backward_inner_template<APPROX_GENERIC>(
forward_input,
forward_output,
backward_input,
backward_output,
n,
alpha,
beta);
}
}
void normalization_response_across_maps_f32::backward(const std::vector<nn_workload_data_t *> &inputs,
const std::vector<const nn_workload_data_t *> ¶meters,
const std::vector<const nn_workload_data_t *> &outputs) {
assert(inputs.size() == 1);
assert(outputs.size() == 1);
const nn::workload_data<float> backward_input(outputs[0]->parent->delta_buffer, outputs[0]->parent->lengths, outputs[0]->parent->layout);
nn::workload_data<float> backward_output(inputs[0]->parent->delta_buffer, inputs[0]->parent->lengths, inputs[0]->parent->layout);
dispatch_backward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]),
reinterpret_cast<const nn::workload_data<float> *>(outputs[0]),
&backward_input,
&backward_output);
}
void wrapper_normalization_work_item_backward(nn_workload_item *const work_item) {
switch (work_item->forward_item->arguments.forward_normalization.normalization.mode) {
case NN_NORMALIZATION_MODE_LINEAR_SINGLE: {
assert(0); // Not yet implemented.
break;
}
case NN_NORMALIZATION_MODE_RESPONSE_ACROSS_MAPS: {
auto primitive = static_cast<normalization_response_across_maps_f32 *>(work_item->forward_item->primitive);
primitive->dispatch_backward(
reinterpret_cast<nn::workload_data<float> *>(work_item->forward_item->input[0].get_data_view()),
reinterpret_cast<nn::workload_data<float> *>(work_item->forward_item->output[0]),
reinterpret_cast<nn::workload_data<float> *>(work_item->input[0].get_data_view()),
reinterpret_cast<nn::workload_data<float> *>(work_item->output[0]));
break;
}
default: {
assert(0);
break;
}
}
}
normalization_elementwise_linear_f32::normalization_elementwise_linear_f32(float alpha,
float beta,
size_t image_size_x,
size_t image_size_y,
size_t image_size_z,
size_t batch_size,
nn_device_internal *device)
: primitive_zxyn_f32_base(batch_size, image_size_z, image_size_x, image_size_y, image_size_z, 0, 0, 0, 0, device),
normalization_mode(NN_NORMALIZATION_MODE_LINEAR_SINGLE),
alpha(alpha),
beta(beta) {}
size_t normalization_elementwise_linear_f32::get_required_input_w() { return output_size_x; }
size_t normalization_elementwise_linear_f32::get_required_input_h() { return output_size_y; }
bool normalization_elementwise_linear_f32::validate_input(size_t index, nn_workload_data_t *data)
{
switch (index) {
case 0:
return nn::data_helper<NN_WORKLOAD_DATA_TAG_ZXYN, float>::validate<false>(
data, get_required_input_w(), get_required_input_h(), input_size_z, batch_size, 0, 0, 0, 0);
}
throw std::invalid_argument("index out of range");
}
normalization_response_across_maps_f32::normalization_response_across_maps_f32(float alpha,
float beta,
uint32_t k,
uint32_t n,
size_t image_size_x,
size_t image_size_y,
size_t image_size_z,
size_t batch_size,
size_t output_padding_left,
size_t output_padding_right,
size_t output_padding_top,
size_t output_padding_bottom,
nn_device_internal *device)
: primitive_zxyn_f32_base(batch_size,
image_size_z,
image_size_x,
image_size_y,
image_size_z,
output_padding_left,
output_padding_right,
output_padding_top,
output_padding_bottom,
device),
normalization_mode(NN_NORMALIZATION_MODE_LINEAR_SINGLE),
alpha(alpha),
beta(beta),
k(k),
n(n) {}
size_t normalization_response_across_maps_f32::get_required_input_w() { return output_size_x; }
size_t normalization_response_across_maps_f32::get_required_input_h() { return output_size_y; }
bool normalization_response_across_maps_f32::validate_input(size_t index, nn_workload_data_t *data)
{
switch (index) {
case 0:
return nn::data_helper<NN_WORKLOAD_DATA_TAG_ZXYN, float>::validate<true>(
data, get_required_input_w(), get_required_input_h(), input_size_z, batch_size, 0, 0, 0, 0);
}
throw std::invalid_argument("index out of range");
}
} // namespace layer
nn_primitive_handle_t NN_API_CALL_CONVENTION
nn_primitives_normalization_elementwise_linear_f32_create_0(nn_device_t *device, /* IDLF device handle */
float alpha, /* multiplier */
float beta, /* offset */
size_t image_size_x, /* image width */
size_t image_size_y, /* image height */
size_t image_size_z, /* number of feature maps */
size_t batch_size, /* size of input batch */
NN_API_STATUS *status /* NN_API_STATUS_OK on success */) {
SET_STATUS(NN_API_STATUS_OK);
return new layer::normalization_elementwise_linear_f32(alpha,
beta,
image_size_x,
image_size_y,
image_size_z,
batch_size,
reinterpret_cast<nn_device_internal *>(device));
}
nn_primitive_handle_t NN_API_CALL_CONVENTION nn_primitives_normalization_response_across_maps_f32_create_0(
nn_device_t *device, /* IDLF device handle */
float alpha, /* sum scale */
float beta, /* sum power */
uint32_t k, /* square sum weight */
uint32_t n, /* size of moving window on the feature maps */
size_t image_size_x, /* image width */
size_t image_size_y, /* image height */
size_t image_size_z, /* number of feature maps */
size_t batch_size, /* size of input batch */
const nn_primitives_normalization_response_across_maps_hints_t *hints,
NN_API_STATUS *status /* NN_API_STATUS_OK on success */) {
SET_STATUS(NN_API_STATUS_OK);
std::remove_const<std::remove_pointer<decltype(hints)>::type>::type hints_ = {};
if (hints != nullptr)
hints_ = *hints;
return new layer::normalization_response_across_maps_f32(alpha,
beta,
k,
n,
image_size_x,
image_size_y,
image_size_z,
batch_size,
hints_.output_padding.left,
hints_.output_padding.right,
hints_.output_padding.top,
hints_.output_padding.bottom,
reinterpret_cast<nn_device_internal *>(device));
}
| MatrixPlayer/idlf | device/cpu/core/layer_normalization_avx2.cpp | C++ | bsd-3-clause | 63,958 |
<?php
/* Prototype : string vsprintf(string format, array args)
* Description: Return a formatted string
* Source code: ext/standard/formatted_print.c
*/
/*
* Test vsprintf() when different hexa formats and hexa values are passed to
* the '$format' and '$args' arguments of the function
*/
echo "*** Testing vsprintf() : hexa formats with hexa values ***\n";
// defining array of different hexa formats
$formats = array(
"%x",
"%+x %-x %X",
"%lx %Lx, %4x %-4x",
"%10.4x %-10.4x %04x %04.4x",
"%'#2x %'2x %'$2x %'_2x",
"%x %x %x %x",
"% %%x x%",
'%3$x %4$x %1$x %2$x'
);
// Arrays of hexa values for the format defined in $format.
// Each sub array contains hexa values which correspond to each format string in $format
$args_array = array(
array(0x0),
array(-0x1, 0x1, +0x22),
array(0x7FFFFFFF, -0x7fffffff, +0x7000000, -0x80000000),
array(123456, 12345678, -1234567, 1234567),
array(1, 0x2222, 0333333, -0x44444444),
array(0x123b, 0xfAb, "0xaxz", 012),
array(0x1234, 0x34, 0x2ff),
array(0x3, 0x4, 0x1, 0x2)
);
// looping to test vsprintf() with different char octal from the above $format array
// and with octal values from the above $args_array array
$counter = 1;
foreach($formats as $format) {
echo "\n-- Iteration $counter --\n";
var_dump( vsprintf($format, $args_array[$counter-1]) );
$counter++;
}
echo "Done";
?>
| JSchwehn/php | testdata/fuzzdir/corpus/ext_standard_tests_strings_vsprintf_variation13_64bit.php | PHP | bsd-3-clause | 1,377 |
# TODO list
- [ ] Update rustup
- [ ] Update dependency `cargo upgrade`
- [ ] Run `cargo clippy`
- [ ] Run all test
- [ ] Stable: `RSTEST_TEST_CHANNEL=stable; cargo +${RSTEST_TEST_CHANNEL} test`
- [ ] Beta: `RSTEST_TEST_CHANNEL=beta; cargo +${RSTEST_TEST_CHANNEL} test`
- [ ] Nightly: `RSTEST_TEST_CHANNEL=nightly; cargo +${RSTEST_TEST_CHANNEL} test`
- [ ] Check Cargo.toml version
- [ ] Create docs and checks links
- [ ] Check CHANGELOG: **RELEASE DATE** and remove empty blocks
- [ ] Check README
- [ ] Create tag (Use github release)
- [ ] prepare deploy `cargo publish --dry-run`
- [ ] deploy `cargo publish`
- [ ] Change next version
- [ ] `Cargo.toml`
- [ ] `README.md`
- [ ] `CHANGELOG.md`
- [ ] Change dependency (inner `rstest` and `rstest_ruse`)
- [ ] Prepare next changelog | chromium/chromium | third_party/rust/rstest/v0_12/crate/checkoutlist.md | Markdown | bsd-3-clause | 798 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BLIMP_NET_INPUT_MESSAGE_GENERATOR_H_
#define BLIMP_NET_INPUT_MESSAGE_GENERATOR_H_
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "blimp/net/blimp_net_export.h"
#include "net/base/completion_callback.h"
namespace blink {
class WebInputEvent;
}
namespace blimp {
class BlimpMessage;
class BlimpMessageProcessor;
// Handles creating serialized InputMessage protos from a stream of
// WebInputEvents. This class may be stateful to optimize the size of the
// serialized transmission data. See InputMessageConverter for the deserialize
// code.
class BLIMP_NET_EXPORT InputMessageGenerator {
public:
InputMessageGenerator();
~InputMessageGenerator();
// Builds a BlimpMessage from |event| that has the basic input event fields
// populated. This might make use of state sent from previous
// BlimpMessage::INPUT messages. It is up to the caller to populate the
// non-input fields and to send the BlimpMessage.
scoped_ptr<BlimpMessage> GenerateMessage(const blink::WebInputEvent& event);
private:
DISALLOW_COPY_AND_ASSIGN(InputMessageGenerator);
};
} // namespace blimp
#endif // BLIMP_NET_INPUT_MESSAGE_GENERATOR_H_
| js0701/chromium-crosswalk | blimp/net/input_message_generator.h | C | bsd-3-clause | 1,342 |
/*
* Copyright (C) 2006, 2007, 2009, 2010, 2011 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef EventHandler_h
#define EventHandler_h
#include "core/CoreExport.h"
#include "core/events/PointerEventFactory.h"
#include "core/events/TextEventInputType.h"
#include "core/layout/HitTestRequest.h"
#include "core/page/DragActions.h"
#include "core/page/EventWithHitTestResults.h"
#include "core/style/ComputedStyleConstants.h"
#include "platform/Cursor.h"
#include "platform/PlatformMouseEvent.h"
#include "platform/PlatformTouchPoint.h"
#include "platform/Timer.h"
#include "platform/UserGestureIndicator.h"
#include "platform/geometry/LayoutPoint.h"
#include "platform/heap/Handle.h"
#include "platform/scroll/ScrollTypes.h"
#include "public/platform/WebFocusType.h"
#include "public/platform/WebInputEventResult.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/HashTraits.h"
#include "wtf/RefPtr.h"
#include <deque>
namespace blink {
class AutoscrollController;
class DataTransfer;
class PaintLayer;
class PaintLayerScrollableArea;
class Document;
class DragState;
class Element;
class Event;
class EventTarget;
template <typename EventType>
class EventWithHitTestResults;
class FloatPoint;
class FloatQuad;
class HTMLFrameSetElement;
class HitTestRequest;
class HitTestResult;
class KeyboardEvent;
class LayoutObject;
class LocalFrame;
class Node;
class OptionalCursor;
class PlatformGestureEvent;
class PlatformKeyboardEvent;
class PlatformTouchEvent;
class PlatformWheelEvent;
class ScrollableArea;
class Scrollbar;
class ScrollState;
class SelectionController;
class TextEvent;
class WheelEvent;
class Widget;
enum class DragInitiator;
class CORE_EXPORT EventHandler final : public NoBaseWillBeGarbageCollectedFinalized<EventHandler> {
WTF_MAKE_NONCOPYABLE(EventHandler);
USING_FAST_MALLOC_WILL_BE_REMOVED(EventHandler);
public:
explicit EventHandler(LocalFrame*);
~EventHandler();
DECLARE_TRACE();
void clear();
void nodeWillBeRemoved(Node&);
void updateSelectionForMouseDrag();
#if OS(WIN)
void startPanScrolling(LayoutObject*);
#endif
void stopAutoscroll();
void dispatchFakeMouseMoveEventSoon();
void dispatchFakeMouseMoveEventSoonInQuad(const FloatQuad&);
HitTestResult hitTestResultAtPoint(const LayoutPoint&,
HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active,
const LayoutSize& padding = LayoutSize());
bool mousePressed() const { return m_mousePressed; }
void setCapturingMouseEventsNode(PassRefPtrWillBeRawPtr<Node>); // A caller is responsible for resetting capturing node to 0.
WebInputEventResult updateDragAndDrop(const PlatformMouseEvent&, DataTransfer*);
void cancelDragAndDrop(const PlatformMouseEvent&, DataTransfer*);
WebInputEventResult performDragAndDrop(const PlatformMouseEvent&, DataTransfer*);
void updateDragStateAfterEditDragIfNeeded(Element* rootEditableElement);
void scheduleHoverStateUpdate();
void scheduleCursorUpdate();
// Return whether a mouse cursor update is currently pending. Used for testing.
bool cursorUpdatePending();
void setResizingFrameSet(HTMLFrameSetElement*);
void resizeScrollableAreaDestroyed();
IntPoint lastKnownMousePosition() const;
// Attempts to scroll the DOM tree. If that fails, scrolls the view.
// If the view can't be scrolled either, recursively bubble to the parent frame.
bool bubblingScroll(ScrollDirection, ScrollGranularity, Node* startingNode = nullptr);
WebInputEventResult handleMouseMoveEvent(const PlatformMouseEvent&);
void handleMouseLeaveEvent(const PlatformMouseEvent&);
WebInputEventResult handleMousePressEvent(const PlatformMouseEvent&);
WebInputEventResult handleMouseReleaseEvent(const PlatformMouseEvent&);
WebInputEventResult handleWheelEvent(const PlatformWheelEvent&);
void defaultWheelEventHandler(Node*, WheelEvent*);
// Called on the local root frame exactly once per gesture event.
WebInputEventResult handleGestureEvent(const PlatformGestureEvent&);
WebInputEventResult handleGestureEvent(const GestureEventWithHitTestResults&);
// Clear the old hover/active state within frames before moving the hover state to the another frame
void updateGestureHoverActiveState(const HitTestRequest&, Element*);
// Hit-test the provided (non-scroll) gesture event, applying touch-adjustment and updating
// hover/active state across all frames if necessary. This should be called at most once
// per gesture event, and called on the local root frame.
// Note: This is similar to (the less clearly named) prepareMouseEvent.
// FIXME: Remove readOnly param when there is only ever a single call to this.
GestureEventWithHitTestResults targetGestureEvent(const PlatformGestureEvent&, bool readOnly = false);
GestureEventWithHitTestResults hitTestResultForGestureEvent(const PlatformGestureEvent&, HitTestRequest::HitTestRequestType);
// Handle the provided non-scroll gesture event. Should be called only on the inner frame.
WebInputEventResult handleGestureEventInFrame(const GestureEventWithHitTestResults&);
// Handle the provided scroll gesture event, propagating down to child frames as necessary.
WebInputEventResult handleGestureScrollEvent(const PlatformGestureEvent&);
WebInputEventResult handleGestureScrollEnd(const PlatformGestureEvent&);
bool isScrollbarHandlingGestures() const;
bool bestClickableNodeForHitTestResult(const HitTestResult&, IntPoint& targetPoint, Node*& targetNode);
bool bestContextMenuNodeForHitTestResult(const HitTestResult&, IntPoint& targetPoint, Node*& targetNode);
// FIXME: This doesn't appear to be used outside tests anymore, what path are we using now and is it tested?
bool bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode);
WebInputEventResult sendContextMenuEvent(const PlatformMouseEvent&, Node* overrideTargetNode = nullptr);
WebInputEventResult sendContextMenuEventForKey(Element* overrideTargetElement = nullptr);
WebInputEventResult sendContextMenuEventForGesture(const GestureEventWithHitTestResults&);
void setMouseDownMayStartAutoscroll() { m_mouseDownMayStartAutoscroll = true; }
static PlatformEvent::Modifiers accessKeyModifiers();
bool handleAccessKey(const PlatformKeyboardEvent&);
WebInputEventResult keyEvent(const PlatformKeyboardEvent&);
void defaultKeyboardEventHandler(KeyboardEvent*);
bool handleTextInputEvent(const String& text, Event* underlyingEvent = nullptr, TextEventInputType = TextEventInputKeyboard);
void defaultTextInputEventHandler(TextEvent*);
void dragSourceEndedAt(const PlatformMouseEvent&, DragOperation);
void focusDocumentView();
void capsLockStateMayHaveChanged(); // Only called by FrameSelection
WebInputEventResult handleTouchEvent(const PlatformTouchEvent&);
bool useHandCursor(Node*, bool isOverLink);
void notifyElementActivated();
PassRefPtr<UserGestureToken> takeLastMouseDownGestureToken() { return m_lastMouseDownUserGestureToken.release(); }
int clickCount() { return m_clickCount; }
SelectionController& selectionController() const { return *m_selectionController; }
class TouchInfo {
DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
public:
DEFINE_INLINE_TRACE()
{
visitor->trace(touchTarget);
visitor->trace(targetFrame);
}
PlatformTouchPoint point;
RefPtrWillBeMember<EventTarget> touchTarget;
RefPtrWillBeMember<LocalFrame> targetFrame;
FloatPoint adjustedPagePoint;
FloatSize adjustedRadius;
bool knownTarget;
bool consumed;
};
private:
static DragState& dragState();
DataTransfer* createDraggingDataTransfer() const;
WebInputEventResult handleMouseMoveOrLeaveEvent(const PlatformMouseEvent&, HitTestResult* hoveredNode = nullptr, bool onlyUpdateScrollbars = false, bool forceLeave = false);
WebInputEventResult handleMousePressEvent(const MouseEventWithHitTestResults&);
WebInputEventResult handleMouseFocus(const MouseEventWithHitTestResults&, InputDeviceCapabilities* sourceCapabilities);
WebInputEventResult handleMouseDraggedEvent(const MouseEventWithHitTestResults&);
WebInputEventResult handleMouseReleaseEvent(const MouseEventWithHitTestResults&);
HitTestRequest::HitTestRequestType getHitTypeForGestureType(PlatformEvent::Type);
void applyTouchAdjustment(PlatformGestureEvent*, HitTestResult*);
WebInputEventResult handleGestureTap(const GestureEventWithHitTestResults&);
WebInputEventResult handleGestureLongPress(const GestureEventWithHitTestResults&);
WebInputEventResult handleGestureLongTap(const GestureEventWithHitTestResults&);
WebInputEventResult handleGestureScrollUpdate(const PlatformGestureEvent&);
WebInputEventResult handleGestureScrollBegin(const PlatformGestureEvent&);
void clearGestureScrollState();
void updateGestureTargetNodeForMouseEvent(const GestureEventWithHitTestResults&);
bool shouldApplyTouchAdjustment(const PlatformGestureEvent&) const;
OptionalCursor selectCursor(const HitTestResult&);
OptionalCursor selectAutoCursor(const HitTestResult&, Node*, const Cursor& iBeam);
void hoverTimerFired(Timer<EventHandler>*);
void cursorUpdateTimerFired(Timer<EventHandler>*);
void activeIntervalTimerFired(Timer<EventHandler>*);
void fakeMouseMoveEventTimerFired(Timer<EventHandler>*);
void cancelFakeMouseMoveEvent();
bool isCursorVisible() const;
void updateCursor();
ScrollableArea* associatedScrollableArea(const PaintLayer*) const;
// Scrolls the elements of the DOM tree. Returns true if a node was scrolled.
// False if we reached the root and couldn't scroll anything.
// direction - The direction to scroll in. If this is a logical direction, it will be
// converted to the physical direction based on a node's writing mode.
// granularity - The units that the scroll delta parameter is in.
// startNode - The node to start bubbling the scroll from. If a node can't scroll,
// the scroll bubbles up to the containing block.
// stopNode - On input, if provided and non-null, the node at which we should stop bubbling on input.
// On output, if provided and a node was scrolled stopNode will point to that node.
// delta - The delta to scroll by, in the units of the granularity parameter. (e.g. pixels, lines, pages, etc.)
// absolutePoint - For wheel scrolls - the location, in absolute coordinates, where the event occured.
ScrollResultOneDimensional scroll(ScrollDirection, ScrollGranularity, Node* startNode = nullptr, Node** stopNode = nullptr, float delta = 1.0f, IntPoint absolutePoint = IntPoint());
void resetOverscroll(bool didScrollX, bool didScrollY);
void handleOverscroll(const ScrollResult&, const FloatPoint& position = FloatPoint(), const FloatSize& velocity = FloatSize());
void customizedScroll(const Node& startNode, ScrollState&);
HitTestResult hitTestResultInFrame(LocalFrame*, const LayoutPoint&, HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active);
void invalidateClick();
void updateMouseEventTargetNode(Node*, const PlatformMouseEvent&);
// Returns true when the sent PE has defaultPrevented or defaultHandled set.
WebInputEventResult dispatchPointerEvent(Node* target, const AtomicString& eventType, const PlatformMouseEvent&, Node* relatedTarget = nullptr);
// Dispatches mouseover, mouseout, mouseenter and mouseleave events to appropriate nodes when the mouse pointer moves from one node to another.
void sendMouseEventsForNodeTransition(Node*, Node*, const PlatformMouseEvent&);
MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const PlatformMouseEvent&);
WebInputEventResult dispatchMouseEvent(const AtomicString& eventType, Node* target, int clickCount, const PlatformMouseEvent&);
// Dispatches ME after corresponding PE provided the PE has not been canceled. The eventType arg
// must be a mouse event that can be gated though a preventDefaulted pointerdown (i.e., one of
// {mousedown, mousemove, mouseup}).
// TODO(mustaq): Can we avoid the clickCount param, instead use PlatformMouseEvent's count?
// Same applied to dispatchMouseEvent() above.
WebInputEventResult updatePointerTargetAndDispatchEvents(const AtomicString& mouseEventType, Node* target,
int clickCount, const PlatformMouseEvent&);
WebInputEventResult dispatchDragEvent(const AtomicString& eventType, Node* target, const PlatformMouseEvent&, DataTransfer*);
void clearDragDataTransfer();
bool handleDrag(const MouseEventWithHitTestResults&, DragInitiator);
bool tryStartDrag(const MouseEventWithHitTestResults&);
void clearDragState();
WebInputEventResult dispatchDragSrcEvent(const AtomicString& eventType, const PlatformMouseEvent&);
bool dragHysteresisExceeded(const IntPoint&) const;
WebInputEventResult passMousePressEventToSubframe(MouseEventWithHitTestResults&, LocalFrame* subframe);
WebInputEventResult passMouseMoveEventToSubframe(MouseEventWithHitTestResults&, LocalFrame* subframe, HitTestResult* hoveredNode = nullptr);
WebInputEventResult passMouseReleaseEventToSubframe(MouseEventWithHitTestResults&, LocalFrame* subframe);
bool passMousePressEventToScrollbar(MouseEventWithHitTestResults&);
WebInputEventResult passWheelEventToWidget(const PlatformWheelEvent&, Widget&);
void defaultSpaceEventHandler(KeyboardEvent*);
void defaultBackspaceEventHandler(KeyboardEvent*);
void defaultTabEventHandler(KeyboardEvent*);
void defaultEscapeEventHandler(KeyboardEvent*);
void defaultArrowEventHandler(WebFocusType, KeyboardEvent*);
void updateLastScrollbarUnderMouse(Scrollbar*, bool);
void setFrameWasScrolledByUser();
bool capturesDragging() const { return m_capturesDragging; }
WebInputEventResult handleGestureShowPress();
bool handleScrollGestureOnResizer(Node*, const PlatformGestureEvent&);
WebInputEventResult passScrollGestureEventToWidget(const PlatformGestureEvent&, LayoutObject*);
AutoscrollController* autoscrollController() const;
bool panScrollInProgress() const;
void setLastKnownMousePosition(const PlatformMouseEvent&);
void conditionallyEnableMouseEventForPointerTypeMouse(const PlatformMouseEvent&);
bool shouldTopControlsConsumeScroll(FloatSize) const;
// If the given element is a shadow host and its root has delegatesFocus=false flag,
// slide focus to its inner element. Returns true if the resulting focus is different from
// the given element.
bool slideFocusOnShadowHostIfNecessary(const Element&);
void dispatchPointerEvents(const PlatformTouchEvent&, WillBeHeapVector<TouchInfo>&);
void sendPointerCancels(WillBeHeapVector<TouchInfo>&);
WebInputEventResult dispatchTouchEvents(const PlatformTouchEvent&, WillBeHeapVector<TouchInfo>&, bool, bool);
// NOTE: If adding a new field to this class please ensure that it is
// cleared in |EventHandler::clear()|.
const RawPtrWillBeMember<LocalFrame> m_frame;
// Current button-press state for mouse/mouse-like-stylus.
// TODO(crbug.com/563676): Buggy for chorded buttons.
bool m_mousePressed;
bool m_capturesDragging;
RefPtrWillBeMember<Node> m_mousePressNode;
bool m_mouseDownMayStartDrag;
const OwnPtrWillBeMember<SelectionController> m_selectionController;
LayoutPoint m_dragStartPos;
Timer<EventHandler> m_hoverTimer;
// TODO(rbyers): Mouse cursor update is page-wide, not per-frame. Page-wide state
// should move out of EventHandler to a new PageEventHandler class. crbug.com/449649
Timer<EventHandler> m_cursorUpdateTimer;
bool m_mouseDownMayStartAutoscroll;
Timer<EventHandler> m_fakeMouseMoveEventTimer;
bool m_svgPan;
RawPtrWillBeMember<PaintLayerScrollableArea> m_resizeScrollableArea;
RefPtrWillBeMember<Node> m_capturingMouseEventsNode;
bool m_eventHandlerWillResetCapturingMouseEventsNode;
RefPtrWillBeMember<Node> m_nodeUnderMouse;
RefPtrWillBeMember<LocalFrame> m_lastMouseMoveEventSubframe;
RefPtrWillBeMember<Scrollbar> m_lastScrollbarUnderMouse;
int m_clickCount;
RefPtrWillBeMember<Node> m_clickNode;
RefPtrWillBeMember<Node> m_dragTarget;
bool m_shouldOnlyFireDragOverEvent;
RefPtrWillBeMember<HTMLFrameSetElement> m_frameSetBeingResized;
LayoutSize m_offsetFromResizeCorner; // In the coords of m_resizeScrollableArea.
FloatSize m_accumulatedRootOverscroll;
bool m_mousePositionIsUnknown;
// The last mouse movement position this frame has seen in root frame coordinates.
IntPoint m_lastKnownMousePosition;
IntPoint m_lastKnownMouseGlobalPosition;
IntPoint m_mouseDownPos; // In our view's coords.
double m_mouseDownTimestamp;
PlatformMouseEvent m_mouseDown;
RefPtr<UserGestureToken> m_lastMouseDownUserGestureToken;
RefPtrWillBeMember<Node> m_previousWheelScrolledNode;
// The target of each active touch point indexed by the touch ID.
using TouchTargetMap = WillBeHeapHashMap<unsigned, RefPtrWillBeMember<EventTarget>, DefaultHash<unsigned>::Hash, WTF::UnsignedWithZeroKeyHashTraits<unsigned>>;
TouchTargetMap m_targetForTouchID;
// If set, the document of the active touch sequence. Unset if no touch sequence active.
RefPtrWillBeMember<Document> m_touchSequenceDocument;
RefPtr<UserGestureToken> m_touchSequenceUserGestureToken;
bool m_touchPressed;
PointerEventFactory m_pointerEventFactory;
// Prevents firing mousedown, mousemove & mouseup in-between a canceled pointerdown and next pointerup/pointercancel.
// See "PREVENT MOUSE EVENT flag" in the spec:
// https://w3c.github.io/pointerevents/#compatibility-mapping-with-mouse-events
bool m_preventMouseEventForPointerTypeMouse;
// This is set upon sending a pointercancel for touch, prevents PE dispatches for touches until
// all touch-points become inactive.
// TODO(mustaq): Consider a state per pointerType, as in PointerIdManager? Exclude mouse?
bool m_inPointerCanceledState;
RefPtrWillBeMember<Node> m_scrollGestureHandlingNode;
bool m_lastGestureScrollOverWidget;
// The most recent element to scroll natively during this scroll
// sequence. Null if no native element has scrolled this scroll
// sequence, or if the most recent element to scroll used scroll
// customization.
RefPtrWillBeMember<Node> m_previousGestureScrolledNode;
RefPtrWillBeMember<Scrollbar> m_scrollbarHandlingScrollGesture;
double m_maxMouseMovedDuration;
bool m_longTapShouldInvokeContextMenu;
Timer<EventHandler> m_activeIntervalTimer;
double m_lastShowPressTimestamp;
RefPtrWillBeMember<Element> m_lastDeferredTapElement;
// Only used with the ScrollCustomization runtime enabled feature.
std::deque<int> m_currentScrollChain;
// True iff some of the delta has been consumed for the current
// scroll sequence in this frame, or any child frames. Only used
// with ScrollCustomization. If some delta has been consumed, a
// scroll which shouldn't propagate can't cause any element to
// scroll other than the |m_previousGestureScrolledNode|.
bool m_deltaConsumedForScrollSequence;
};
} // namespace blink
WTF_ALLOW_INIT_WITH_MEM_FUNCTIONS(blink::EventHandler::TouchInfo);
#endif // EventHandler_h
| js0701/chromium-crosswalk | third_party/WebKit/Source/core/input/EventHandler.h | C | bsd-3-clause | 21,034 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY 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 AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
__ace_shadowed__.define('ace/mode/ruby', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ruby_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/folding/coffee'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var FoldMode = require("./folding/coffee").FoldMode;
var Mode = function() {
this.HighlightRules = RubyHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "#";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/);
var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/);
var startingConditional = line.match(/^\s*(if|else)\s*/)
if (match || startingClassOrMethod || startingDoBlock || startingConditional) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return /^\s+end$/.test(line + input) || /^\s+}$/.test(line + input) || /^\s+else$/.test(line + input);
};
this.autoOutdent = function(state, doc, row) {
var indent = this.$getIndent(doc.getLine(row));
var tab = doc.getTabString();
if (indent.slice(-tab.length) == tab)
doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
};
this.$id = "ace/mode/ruby";
}).call(Mode.prototype);
exports.Mode = Mode;
});
__ace_shadowed__.define('ace/mode/ruby_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var constantOtherSymbol = exports.constantOtherSymbol = {
token : "constant.other.symbol.ruby", // symbol
regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"
};
var qString = exports.qString = {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
};
var qqString = exports.qqString = {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
};
var tString = exports.tString = {
token : "string", // backtick string
regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"
};
var constantNumericHex = exports.constantNumericHex = {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"
};
var constantNumericFloat = exports.constantNumericFloat = {
token : "constant.numeric", // float
regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"
};
var RubyHighlightRules = function() {
var builtinFunctions = (
"abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" +
"assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" +
"assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" +
"assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" +
"assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" +
"assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" +
"attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" +
"caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" +
"exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" +
"gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" +
"link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" +
"p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" +
"raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" +
"set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" +
"throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" +
"render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" +
"content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" +
"fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" +
"time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" +
"select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" +
"file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" +
"protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" +
"send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" +
"validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" +
"validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" +
"authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" +
"filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" +
"translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" +
"cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" +
"has_many|has_one|belongs_to|has_and_belongs_to_many"
);
var keywords = (
"alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" +
"__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" +
"redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield"
);
var buildinConstants = (
"true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" +
"RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING"
);
var builtinVariables = (
"\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" +
"$!|root_url|flash|session|cookies|params|request|response|logger|self"
);
var keywordMapper = this.$keywords = this.createKeywordMapper({
"keyword": keywords,
"constant.language": buildinConstants,
"variable.language": builtinVariables,
"support.function": builtinFunctions,
"invalid.deprecated": "debugger" // TODO is this a remnant from js mode?
}, "identifier");
this.$rules = {
"start" : [
{
token : "comment",
regex : "#.*$"
}, {
token : "comment", // multi line comment
regex : "^=begin(?:$|\\s.*$)",
next : "comment"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
},
qString,
qqString,
tString,
{
token : "text", // namespaces aren't symbols
regex : "::"
}, {
token : "variable.instance", // instance variable
regex : "@{1,2}[a-zA-Z_\\d]+"
}, {
token : "support.class", // class name
regex : "[A-Z][a-zA-Z_\\d]+"
},
constantOtherSymbol,
constantNumericHex,
constantNumericFloat,
{
token : "constant.language.boolean",
regex : "(?:true|false)\\b"
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "punctuation.separator.key-value",
regex : "=>"
}, {
stateName: "heredoc",
onMatch : function(value, currentState, stack) {
var next = value[2] == '-' ? "indentedHeredoc" : "heredoc";
var tokens = value.split(this.splitRegex);
stack.push(next, tokens[3]);
return [
{type:"constant", value: tokens[1]},
{type:"string", value: tokens[2]},
{type:"support.class", value: tokens[3]},
{type:"string", value: tokens[4]}
];
},
regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)",
rules: {
heredoc: [{
onMatch: function(value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}],
indentedHeredoc: [{
token: "string",
regex: "^ +"
}, {
onMatch: function(value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}]
}
}, {
regex : "$",
token : "empty",
next : function(currentState, stack) {
if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc")
return stack[0];
return currentState;
}
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : "^=end(?:$|\\s.*$)",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
]
};
this.normalizeRules();
};
oop.inherits(RubyHighlightRules, TextHighlightRules);
exports.RubyHighlightRules = RubyHighlightRules;
});
__ace_shadowed__.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
__ace_shadowed__.define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidgetRange = function(session, foldStyle, row) {
var range = this.indentationBlock(session, row);
if (range)
return range;
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1 || line[startLevel] != "#")
return;
var startColumn = line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
line = session.getLine(row);
var level = line.search(re);
if (level == -1)
continue;
if (line[level] != "#")
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
var indent = line.search(/\S/);
var next = session.getLine(row + 1);
var prev = session.getLine(row - 1);
var prevIndent = prev.search(/\S/);
var nextIndent = next.search(/\S/);
if (indent == -1) {
session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : "";
return "";
}
if (prevIndent == -1) {
if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") {
session.foldWidgets[row - 1] = "";
session.foldWidgets[row + 1] = "";
return "start";
}
} else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") {
if (session.getLine(row - 2).search(/\S/) == -1) {
session.foldWidgets[row - 1] = "start";
session.foldWidgets[row + 1] = "";
return "";
}
}
if (prevIndent!= -1 && prevIndent < indent)
session.foldWidgets[row - 1] = "start";
else
session.foldWidgets[row - 1] = "";
if (indent < nextIndent)
return "start";
else
return "";
};
}).call(FoldMode.prototype);
});
| kang/ace-builds | textarea/src/mode-ruby.js | JavaScript | bsd-3-clause | 17,646 |
a.reference.image-reference {
border-bottom: none;
}
| dejlek/pulsar | docs/source/_static/pulsar.css | CSS | bsd-3-clause | 58 |
// RUN: %clang_builtins %s %librt -o %t && %run %t
// REQUIRES: librt_has_absvdi2
//===-- absvdi2_test.c - Test __absvdi2 -----------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file tests __absvdi2 for the compiler_rt library.
//
//===----------------------------------------------------------------------===//
#include "int_lib.h"
#include <stdio.h>
#include <stdlib.h>
// Returns: absolute value
// Effects: aborts if abs(x) < 0
COMPILER_RT_ABI di_int __absvdi2(di_int a);
int test__absvdi2(di_int a)
{
di_int x = __absvdi2(a);
di_int expected = a;
if (expected < 0)
expected = -expected;
if (x != expected || expected < 0)
printf("error in __absvdi2(0x%llX) = %lld, expected positive %lld\n",
a, x, expected);
return x != expected;
}
int main()
{
// if (test__absvdi2(0x8000000000000000LL)) // should abort
// return 1;
if (test__absvdi2(0x0000000000000000LL))
return 1;
if (test__absvdi2(0x0000000000000001LL))
return 1;
if (test__absvdi2(0x0000000000000002LL))
return 1;
if (test__absvdi2(0x7FFFFFFFFFFFFFFELL))
return 1;
if (test__absvdi2(0x7FFFFFFFFFFFFFFFLL))
return 1;
if (test__absvdi2(0x8000000000000001LL))
return 1;
if (test__absvdi2(0x8000000000000002LL))
return 1;
if (test__absvdi2(0xFFFFFFFFFFFFFFFELL))
return 1;
if (test__absvdi2(0xFFFFFFFFFFFFFFFFLL))
return 1;
int i;
for (i = 0; i < 10000; ++i)
if (test__absvdi2(((di_int)rand() << 32) | rand()))
return 1;
return 0;
}
| endlessm/chromium-browser | third_party/llvm/compiler-rt/test/builtins/Unit/absvdi2_test.c | C | bsd-3-clause | 1,888 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Currently this file is only used for the uninstall prompt. The install prompt
// code is in extension_install_prompt2_gtk.cc.
#include "chrome/browser/extensions/extension_uninstall_dialog.h"
#include <gtk/gtk.h>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/gtk_util.h"
namespace {
// Left or right margin.
const int kPanelHorizMargin = 13;
// GTK implementation of the uninstall dialog.
class ExtensionUninstallDialogGtk : public ExtensionUninstallDialog {
public:
ExtensionUninstallDialogGtk(Browser* browser, Delegate* delegate);
virtual ~ExtensionUninstallDialogGtk() OVERRIDE;
private:
virtual void Show() OVERRIDE;
CHROMEGTK_CALLBACK_1(ExtensionUninstallDialogGtk, void, OnResponse, int);
GtkWidget* dialog_;
};
ExtensionUninstallDialogGtk::ExtensionUninstallDialogGtk(
Browser* browser, ExtensionUninstallDialog::Delegate* delegate)
: ExtensionUninstallDialog(browser, delegate),
dialog_(NULL) {}
void ExtensionUninstallDialogGtk::Show() {
BrowserWindow* browser_window = browser_->window();
if (!browser_window) {
delegate_->ExtensionUninstallCanceled();
return;
}
// Build the dialog.
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE).c_str(),
browser_window->GetNativeWindow(),
GTK_DIALOG_MODAL,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CLOSE,
l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON).c_str(),
GTK_RESPONSE_ACCEPT,
NULL);
#if !GTK_CHECK_VERSION(2, 22, 0)
gtk_dialog_set_has_separator(GTK_DIALOG(dialog_), FALSE);
#endif
// Create a two column layout.
GtkWidget* content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog_));
gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing);
GtkWidget* icon_hbox = gtk_hbox_new(FALSE, ui::kContentAreaSpacing);
gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0);
// Put Icon in the left column.
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(*icon_.bitmap());
GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(icon_hbox), icon, TRUE, TRUE, 0);
// Create a new vbox for the right column.
GtkWidget* right_column_area = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0);
std::string heading_text = l10n_util::GetStringFUTF8(
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING, UTF8ToUTF16(extension_->name()));
GtkWidget* heading_label = gtk_label_new(heading_text.c_str());
gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(right_column_area), heading_label, TRUE, TRUE, 0);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);
gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);
gtk_widget_show_all(dialog_);
}
ExtensionUninstallDialogGtk::~ExtensionUninstallDialogGtk() {
delegate_ = NULL;
if (dialog_) {
gtk_widget_destroy(dialog_);
dialog_ = NULL;
}
}
void ExtensionUninstallDialogGtk::OnResponse(
GtkWidget* dialog, int response_id) {
CHECK_EQ(dialog_, dialog);
gtk_widget_destroy(dialog_);
dialog_ = NULL;
if (delegate_) {
if (response_id == GTK_RESPONSE_ACCEPT)
delegate_->ExtensionUninstallAccepted();
else
delegate_->ExtensionUninstallCanceled();
}
}
} // namespace
// static
// Platform specific implementation of the uninstall dialog show method.
ExtensionUninstallDialog* ExtensionUninstallDialog::Create(
Browser* browser, Delegate* delegate) {
return new ExtensionUninstallDialogGtk(browser, delegate);
}
| junmin-zhu/chromium-rivertrail | chrome/browser/ui/gtk/extensions/extension_uninstall_dialog_gtk.cc | C++ | bsd-3-clause | 4,153 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Cocoa/Cocoa.h>
#include "base/callback.h"
#include "remoting/host/disconnect_window.h"
namespace remoting {
class ChromotingHost;
}
// Controller for the disconnect window which allows the host user to
// quickly disconnect a session.
@interface DisconnectWindowController : NSWindowController {
@private
remoting::ChromotingHost* host_;
base::Closure disconnect_callback_;
NSString* username_;
IBOutlet NSTextField* connectedToField_;
IBOutlet NSButton* disconnectButton_;
}
- (id)initWithHost:(remoting::ChromotingHost*)host
callback:(const base::Closure&)disconnect_callback
username:(NSString*)username;
- (IBAction)stopSharing:(id)sender;
@end
// A floating window with a custom border. The custom border and background
// content is defined by DisconnectView. Declared here so that it can be
// instantiated via a xib.
@interface DisconnectWindow : NSWindow
@end
// The custom background/border for the DisconnectWindow. Declared here so that
// it can be instantiated via a xib.
@interface DisconnectView : NSView
@end
| leighpauls/k2cro4 | remoting/host/disconnect_window_mac.h | C | bsd-3-clause | 1,242 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "components/nacl/common/nacl_types.h"
#include "ipc/ipc_platform_file.h"
namespace nacl {
NaClStartParams::NaClStartParams()
: nexe_file(IPC::InvalidPlatformFileForTransit()),
irt_handle(IPC::InvalidPlatformFileForTransit()),
#if defined(OS_MACOSX)
mac_shm_fd(IPC::InvalidPlatformFileForTransit()),
#endif
#if defined(OS_POSIX)
debug_stub_server_bound_socket(IPC::InvalidPlatformFileForTransit()),
#endif
validation_cache_enabled(false),
enable_debug_stub(false),
process_type(kUnknownNaClProcessType),
crash_info_shmem_handle(base::SharedMemory::NULLHandle()) {
}
NaClStartParams::~NaClStartParams() {
}
NaClResourcePrefetchResult::NaClResourcePrefetchResult()
: file(IPC::InvalidPlatformFileForTransit()) {
}
NaClResourcePrefetchResult::NaClResourcePrefetchResult(
const IPC::PlatformFileForTransit& file,
const base::FilePath& file_path_metadata,
const std::string& file_key)
: file(file), file_path_metadata(file_path_metadata), file_key(file_key) {
}
NaClResourcePrefetchResult::~NaClResourcePrefetchResult() {
}
NaClResourcePrefetchRequest::NaClResourcePrefetchRequest() {
}
NaClResourcePrefetchRequest::NaClResourcePrefetchRequest(
const std::string& file_key,
const std::string& resource_url)
: file_key(file_key),
resource_url(resource_url) {
}
NaClResourcePrefetchRequest::~NaClResourcePrefetchRequest() {
}
NaClLaunchParams::NaClLaunchParams()
: nexe_file(IPC::InvalidPlatformFileForTransit()),
nexe_token_lo(0),
nexe_token_hi(0),
render_view_id(0),
permission_bits(0),
process_type(kUnknownNaClProcessType) {
}
NaClLaunchParams::NaClLaunchParams(
const std::string& manifest_url,
const IPC::PlatformFileForTransit& nexe_file,
uint64_t nexe_token_lo,
uint64_t nexe_token_hi,
const std::vector<NaClResourcePrefetchRequest>&
resource_prefetch_request_list,
int render_view_id,
uint32_t permission_bits,
bool uses_nonsfi_mode,
NaClAppProcessType process_type)
: manifest_url(manifest_url),
nexe_file(nexe_file),
nexe_token_lo(nexe_token_lo),
nexe_token_hi(nexe_token_hi),
resource_prefetch_request_list(resource_prefetch_request_list),
render_view_id(render_view_id),
permission_bits(permission_bits),
uses_nonsfi_mode(uses_nonsfi_mode),
process_type(process_type) {}
NaClLaunchParams::~NaClLaunchParams() {
}
NaClLaunchResult::NaClLaunchResult()
: ppapi_ipc_channel_handle(),
trusted_ipc_channel_handle(),
plugin_pid(base::kNullProcessId),
plugin_child_id(0),
crash_info_shmem_handle(base::SharedMemory::NULLHandle()) {
}
NaClLaunchResult::NaClLaunchResult(
const IPC::ChannelHandle& ppapi_ipc_channel_handle,
const IPC::ChannelHandle& trusted_ipc_channel_handle,
const IPC::ChannelHandle& manifest_service_ipc_channel_handle,
base::ProcessId plugin_pid,
int plugin_child_id,
base::SharedMemoryHandle crash_info_shmem_handle)
: ppapi_ipc_channel_handle(ppapi_ipc_channel_handle),
trusted_ipc_channel_handle(trusted_ipc_channel_handle),
manifest_service_ipc_channel_handle(manifest_service_ipc_channel_handle),
plugin_pid(plugin_pid),
plugin_child_id(plugin_child_id),
crash_info_shmem_handle(crash_info_shmem_handle) {
}
NaClLaunchResult::~NaClLaunchResult() {
}
} // namespace nacl
| hujiajie/chromium-crosswalk | components/nacl/common/nacl_types.cc | C++ | bsd-3-clause | 3,616 |
// Copyright (c) 2006, 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.
//
// Author: Satoru Takabayashi
// Stack-footprint reduction work done by Raksit Ashok
//
// Implementation note:
//
// We don't use heaps but only use stacks. We want to reduce the
// stack consumption so that the symbolizer can run on small stacks.
//
// Here are some numbers collected with GCC 4.1.0 on x86:
// - sizeof(Elf32_Sym) = 16
// - sizeof(Elf32_Shdr) = 40
// - sizeof(Elf64_Sym) = 24
// - sizeof(Elf64_Shdr) = 64
//
// This implementation is intended to be async-signal-safe but uses
// some functions which are not guaranteed to be so, such as memchr()
// and memmove(). We assume they are async-signal-safe.
//
// Additional header can be specified by the GLOG_BUILD_CONFIG_INCLUDE
// macro to add platform specific defines (e.g. OS_OPENBSD).
#ifdef GLOG_BUILD_CONFIG_INCLUDE
#include GLOG_BUILD_CONFIG_INCLUDE
#endif // GLOG_BUILD_CONFIG_INCLUDE
#include "build/build_config.h"
#include "utilities.h"
#if defined(HAVE_SYMBOLIZE)
#include <string.h>
#include <algorithm>
#include <limits>
#include "symbolize.h"
#include "demangle.h"
_START_GOOGLE_NAMESPACE_
// We don't use assert() since it's not guaranteed to be
// async-signal-safe. Instead we define a minimal assertion
// macro. So far, we don't need pretty printing for __FILE__, etc.
// A wrapper for abort() to make it callable in ? :.
static int AssertFail() {
abort();
return 0; // Should not reach.
}
#define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
static SymbolizeCallback g_symbolize_callback = NULL;
void InstallSymbolizeCallback(SymbolizeCallback callback) {
g_symbolize_callback = callback;
}
static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback =
NULL;
void InstallSymbolizeOpenObjectFileCallback(
SymbolizeOpenObjectFileCallback callback) {
g_symbolize_open_object_file_callback = callback;
}
// This function wraps the Demangle function to provide an interface
// where the input symbol is demangled in-place.
// To keep stack consumption low, we would like this function to not
// get inlined.
static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) {
char demangled[256]; // Big enough for sane demangled symbols.
if (Demangle(out, demangled, sizeof(demangled))) {
// Demangling succeeded. Copy to out if the space allows.
size_t len = strlen(demangled);
if (len + 1 <= (size_t)out_size) { // +1 for '\0'.
SAFE_ASSERT(len < sizeof(demangled));
memmove(out, demangled, len + 1);
}
}
}
_END_GOOGLE_NAMESPACE_
#if defined(__ELF__)
#if defined(HAVE_DLFCN_H)
#include <dlfcn.h>
#endif
#if BUILDFLAG(IS_OPENBSD)
#include <sys/exec_elf.h>
#else
#include <elf.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "symbolize.h"
#include "config.h"
#include "glog/raw_logging.h"
// Re-runs fn until it doesn't cause EINTR.
#define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR)
_START_GOOGLE_NAMESPACE_
// Read up to "count" bytes from "offset" in the file pointed by file
// descriptor "fd" into the buffer starting at "buf" while handling short reads
// and EINTR. On success, return the number of bytes read. Otherwise, return
// -1.
ssize_t ReadFromOffset(const int fd,
void* buf,
const size_t count,
const off_t offset) {
SAFE_ASSERT(fd >= 0);
SAFE_ASSERT(count <= std::numeric_limits<ssize_t>::max());
char *buf0 = reinterpret_cast<char *>(buf);
ssize_t num_bytes = 0;
while (num_bytes < count) {
ssize_t len;
NO_INTR(len = pread(fd, buf0 + num_bytes, count - num_bytes,
offset + num_bytes));
if (len < 0) { // There was an error other than EINTR.
return -1;
}
if (len == 0) { // Reached EOF.
break;
}
num_bytes += len;
}
SAFE_ASSERT(num_bytes <= count);
return num_bytes;
}
// Try reading exactly "count" bytes from "offset" bytes in a file
// pointed by "fd" into the buffer starting at "buf" while handling
// short reads and EINTR. On success, return true. Otherwise, return
// false.
static bool ReadFromOffsetExact(const int fd, void *buf,
const size_t count, const off_t offset) {
ssize_t len = ReadFromOffset(fd, buf, count, offset);
return len == count;
}
// Returns elf_header.e_type if the file pointed by fd is an ELF binary.
static int FileGetElfType(const int fd) {
ElfW(Ehdr) elf_header;
if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
return -1;
}
if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
return -1;
}
return elf_header.e_type;
}
// Read the section headers in the given ELF binary, and if a section
// of the specified type is found, set the output to this section header
// and return true. Otherwise, return false.
// To keep stack consumption low, we would like this function to not get
// inlined.
static ATTRIBUTE_NOINLINE bool
GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const off_t sh_offset,
ElfW(Word) type, ElfW(Shdr) *out) {
// Read at most 16 section headers at a time to save read calls.
ElfW(Shdr) buf[16];
for (int i = 0; i < sh_num;) {
const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]);
const ssize_t num_bytes_to_read =
(sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf);
const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read,
sh_offset + i * sizeof(buf[0]));
if (len == -1) {
return false;
}
SAFE_ASSERT(len % sizeof(buf[0]) == 0);
const ssize_t num_headers_in_buf = len / sizeof(buf[0]);
SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0]));
for (int j = 0; j < num_headers_in_buf; ++j) {
if (buf[j].sh_type == type) {
*out = buf[j];
return true;
}
}
i += num_headers_in_buf;
}
return false;
}
// There is no particular reason to limit section name to 63 characters,
// but there has (as yet) been no need for anything longer either.
const int kMaxSectionNameLen = 64;
// name_len should include terminating '\0'.
bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
ElfW(Shdr) *out) {
ElfW(Ehdr) elf_header;
if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
return false;
}
ElfW(Shdr) shstrtab;
off_t shstrtab_offset = (elf_header.e_shoff +
elf_header.e_shentsize * elf_header.e_shstrndx);
if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) {
return false;
}
for (int i = 0; i < elf_header.e_shnum; ++i) {
off_t section_header_offset = (elf_header.e_shoff +
elf_header.e_shentsize * i);
if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) {
return false;
}
char header_name[kMaxSectionNameLen];
if (sizeof(header_name) < name_len) {
RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); "
"section will not be found (even if present).", name, name_len);
// No point in even trying.
return false;
}
off_t name_offset = shstrtab.sh_offset + out->sh_name;
ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
if (n_read == -1) {
return false;
} else if (n_read != name_len) {
// Short read -- name could be at end of file.
continue;
}
if (memcmp(header_name, name, name_len) == 0) {
return true;
}
}
return false;
}
// Read a symbol table and look for the symbol containing the
// pc. Iterate over symbols in a symbol table and look for the symbol
// containing "pc". On success, return true and write the symbol name
// to out. Otherwise, return false.
// To keep stack consumption low, we would like this function to not get
// inlined.
static ATTRIBUTE_NOINLINE bool
FindSymbol(uint64_t pc, const int fd, char *out, int out_size,
uint64_t symbol_offset, const ElfW(Shdr) *strtab,
const ElfW(Shdr) *symtab) {
if (symtab == NULL) {
return false;
}
const int num_symbols = symtab->sh_size / symtab->sh_entsize;
for (int i = 0; i < num_symbols;) {
off_t offset = symtab->sh_offset + i * symtab->sh_entsize;
// If we are reading Elf64_Sym's, we want to limit this array to
// 32 elements (to keep stack consumption low), otherwise we can
// have a 64 element Elf32_Sym array.
#if __WORDSIZE == 64
#define NUM_SYMBOLS 32
#else
#define NUM_SYMBOLS 64
#endif
// Read at most NUM_SYMBOLS symbols at once to save read() calls.
ElfW(Sym) buf[NUM_SYMBOLS];
int num_symbols_to_read = std::min(NUM_SYMBOLS, num_symbols - i);
const ssize_t len =
ReadFromOffset(fd, &buf, sizeof(buf[0]) * num_symbols_to_read, offset);
SAFE_ASSERT(len % sizeof(buf[0]) == 0);
const ssize_t num_symbols_in_buf = len / sizeof(buf[0]);
SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read);
for (int j = 0; j < num_symbols_in_buf; ++j) {
const ElfW(Sym)& symbol = buf[j];
uint64_t start_address = symbol.st_value;
start_address += symbol_offset;
uint64_t end_address = start_address + symbol.st_size;
if (symbol.st_value != 0 && // Skip null value symbols.
symbol.st_shndx != 0 && // Skip undefined symbols.
start_address <= pc && pc < end_address) {
ssize_t len1 = ReadFromOffset(fd, out, out_size,
strtab->sh_offset + symbol.st_name);
if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) {
memset(out, 0, out_size);
return false;
}
return true; // Obtained the symbol name.
}
}
i += num_symbols_in_buf;
}
return false;
}
// Get the symbol name of "pc" from the file pointed by "fd". Process
// both regular and dynamic symbol tables if necessary. On success,
// write the symbol name to "out" and return true. Otherwise, return
// false.
static bool GetSymbolFromObjectFile(const int fd,
uint64_t pc,
char* out,
int out_size,
uint64_t base_address) {
// Read the ELF header.
ElfW(Ehdr) elf_header;
if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
return false;
}
ElfW(Shdr) symtab, strtab;
// Consult a regular symbol table first.
if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
SHT_SYMTAB, &symtab)) {
if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
symtab.sh_link * sizeof(symtab))) {
return false;
}
if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
return true; // Found the symbol in a regular symbol table.
}
}
// If the symbol is not found, then consult a dynamic symbol table.
if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
SHT_DYNSYM, &symtab)) {
if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
symtab.sh_link * sizeof(symtab))) {
return false;
}
if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
return true; // Found the symbol in a dynamic symbol table.
}
}
return false;
}
// Thin wrapper around a file descriptor so that the file descriptor
// gets closed for sure.
FileDescriptor::FileDescriptor(int fd) : fd_(fd) {}
FileDescriptor::~FileDescriptor() {
if (fd_ >= 0) {
close(fd_);
}
}
namespace {
// Helper class for reading lines from file.
//
// Note: we don't use ProcMapsIterator since the object is big (it has
// a 5k array member) and uses async-unsafe functions such as sscanf()
// and snprintf().
class LineReader {
public:
explicit LineReader(int fd, char *buf, int buf_len, off_t offset)
: fd_(fd),
buf_(buf),
buf_len_(buf_len),
offset_(offset),
bol_(buf),
eol_(buf),
eod_(buf) {}
// Read '\n'-terminated line from file. On success, modify "bol"
// and "eol", then return true. Otherwise, return false.
//
// Note: if the last line doesn't end with '\n', the line will be
// dropped. It's an intentional behavior to make the code simple.
bool ReadLine(const char **bol, const char **eol) {
if (BufferIsEmpty()) { // First time.
const ssize_t num_bytes = ReadFromOffset(fd_, buf_, buf_len_, offset_);
if (num_bytes <= 0) { // EOF or error.
return false;
}
offset_ += num_bytes;
eod_ = buf_ + num_bytes;
bol_ = buf_;
} else {
bol_ = eol_ + 1; // Advance to the next line in the buffer.
SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_".
if (!HasCompleteLine()) {
const int incomplete_line_length = eod_ - bol_;
// Move the trailing incomplete line to the beginning.
memmove(buf_, bol_, incomplete_line_length);
// Read text from file and append it.
char * const append_pos = buf_ + incomplete_line_length;
const int capacity_left = buf_len_ - incomplete_line_length;
const ssize_t num_bytes =
ReadFromOffset(fd_, append_pos, capacity_left, offset_);
if (num_bytes <= 0) { // EOF or error.
return false;
}
offset_ += num_bytes;
eod_ = append_pos + num_bytes;
bol_ = buf_;
}
}
eol_ = FindLineFeed();
if (eol_ == NULL) { // '\n' not found. Malformed line.
return false;
}
*eol_ = '\0'; // Replace '\n' with '\0'.
*bol = bol_;
*eol = eol_;
return true;
}
// Beginning of line.
const char *bol() {
return bol_;
}
// End of line.
const char *eol() {
return eol_;
}
private:
explicit LineReader(const LineReader&);
void operator=(const LineReader&);
char *FindLineFeed() {
return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
}
bool BufferIsEmpty() {
return buf_ == eod_;
}
bool HasCompleteLine() {
return !BufferIsEmpty() && FindLineFeed() != NULL;
}
const int fd_;
char * const buf_;
const int buf_len_;
off_t offset_;
char *bol_;
char *eol_;
const char *eod_; // End of data in "buf_".
};
} // namespace
// Place the hex number read from "start" into "*hex". The pointer to
// the first non-hex character or "end" is returned.
static char *GetHex(const char *start, const char *end, uint64_t *hex) {
*hex = 0;
const char *p;
for (p = start; p < end; ++p) {
int ch = *p;
if ((ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) {
*hex = (*hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9);
} else { // Encountered the first non-hex character.
break;
}
}
SAFE_ASSERT(p <= end);
return const_cast<char *>(p);
}
// Searches for the object file (from /proc/self/maps) that contains
// the specified pc. If found, sets |start_address| to the start address
// of where this object file is mapped in memory, sets the module base
// address into |base_address|, copies the object file name into
// |out_file_name|, and attempts to open the object file. If the object
// file is opened successfully, returns the file descriptor. Otherwise,
// returns -1. |out_file_name_size| is the size of the file name buffer
// (including the null-terminator).
ATTRIBUTE_NOINLINE int OpenObjectFileContainingPcAndGetStartAddress(
uint64_t pc,
uint64_t& start_address,
uint64_t& end_address,
uint64_t& base_address,
char* out_file_name,
int out_file_name_size) {
int object_fd;
int maps_fd;
NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY));
FileDescriptor wrapped_maps_fd(maps_fd);
if (wrapped_maps_fd.get() < 0) {
return -1;
}
int mem_fd;
NO_INTR(mem_fd = open("/proc/self/mem", O_RDONLY));
FileDescriptor wrapped_mem_fd(mem_fd);
if (wrapped_mem_fd.get() < 0) {
return -1;
}
// Iterate over maps and look for the map containing the pc. Then
// look into the symbol tables inside.
char buf[1024]; // Big enough for line of sane /proc/self/maps
int num_maps = 0;
LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf), 0);
while (true) {
num_maps++;
const char *cursor;
const char *eol;
if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line.
return -1;
}
// Start parsing line in /proc/self/maps. Here is an example:
//
// 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat
//
// We want start address (08048000), end address (0804c000), flags
// (r-xp) and file name (/bin/cat).
// Read start address.
cursor = GetHex(cursor, eol, &start_address);
if (cursor == eol || *cursor != '-') {
return -1; // Malformed line.
}
++cursor; // Skip '-'.
// Read end address.
cursor = GetHex(cursor, eol, &end_address);
if (cursor == eol || *cursor != ' ') {
return -1; // Malformed line.
}
++cursor; // Skip ' '.
// Read flags. Skip flags until we encounter a space or eol.
const char * const flags_start = cursor;
while (cursor < eol && *cursor != ' ') {
++cursor;
}
// We expect at least four letters for flags (ex. "r-xp").
if (cursor == eol || cursor < flags_start + 4) {
return -1; // Malformed line.
}
// Determine the base address by reading ELF headers in process memory.
ElfW(Ehdr) ehdr;
// Skip non-readable maps.
if (flags_start[0] == 'r' &&
ReadFromOffsetExact(mem_fd, &ehdr, sizeof(ElfW(Ehdr)), start_address) &&
memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
switch (ehdr.e_type) {
case ET_EXEC:
base_address = 0;
break;
case ET_DYN:
// Find the segment containing file offset 0. This will correspond
// to the ELF header that we just read. Normally this will have
// virtual address 0, but this is not guaranteed. We must subtract
// the virtual address from the address where the ELF header was
// mapped to get the base address.
//
// If we fail to find a segment for file offset 0, use the address
// of the ELF header as the base address.
base_address = start_address;
for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
ElfW(Phdr) phdr;
if (ReadFromOffsetExact(
mem_fd, &phdr, sizeof(phdr),
start_address + ehdr.e_phoff + i * sizeof(phdr)) &&
phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
base_address = start_address - phdr.p_vaddr;
break;
}
}
break;
default:
// ET_REL or ET_CORE. These aren't directly executable, so they don't
// affect the base address.
break;
}
}
// Check start and end addresses.
if (!(start_address <= pc && pc < end_address)) {
continue; // We skip this map. PC isn't in this map.
}
// Check flags. We are only interested in "r*x" maps.
if (flags_start[0] != 'r' || flags_start[2] != 'x') {
continue; // We skip this map.
}
++cursor; // Skip ' '.
// Read file offset.
uint64_t file_offset;
cursor = GetHex(cursor, eol, &file_offset);
if (cursor == eol || *cursor != ' ') {
return -1; // Malformed line.
}
++cursor; // Skip ' '.
// Skip to file name. "cursor" now points to dev. We need to
// skip at least two spaces for dev and inode.
int num_spaces = 0;
while (cursor < eol) {
if (*cursor == ' ') {
++num_spaces;
} else if (num_spaces >= 2) {
// The first non-space character after skipping two spaces
// is the beginning of the file name.
break;
}
++cursor;
}
if (cursor == eol) {
return -1; // Malformed line.
}
// Finally, "cursor" now points to file name of our interest.
NO_INTR(object_fd = open(cursor, O_RDONLY));
if (object_fd < 0) {
// Failed to open object file. Copy the object file name to
// |out_file_name|.
strncpy(out_file_name, cursor, out_file_name_size);
// Making sure |out_file_name| is always null-terminated.
out_file_name[out_file_name_size - 1] = '\0';
return -1;
}
return object_fd;
}
}
// POSIX doesn't define any async-signal safe function for converting
// an integer to ASCII. We'll have to define our own version.
// itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
// conversion was successful or NULL otherwise. It never writes more than "sz"
// bytes. Output will be truncated as needed, and a NUL character is always
// appended.
// NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
// Make sure we can write at least one NUL byte.
size_t n = 1;
if (n > sz)
return NULL;
if (base < 2 || base > 16) {
buf[0] = '\000';
return NULL;
}
char *start = buf;
uintptr_t j = i;
// Handle negative numbers (only for base 10).
if (i < 0 && base == 10) {
// This does "j = -i" while avoiding integer overflow.
j = static_cast<uintptr_t>(-(i + 1)) + 1;
// Make sure we can write the '-' character.
if (++n > sz) {
buf[0] = '\000';
return NULL;
}
*start++ = '-';
}
// Loop until we have converted the entire number. Output at least one
// character (i.e. '0').
char *ptr = start;
do {
// Make sure there is still enough space left in our output buffer.
if (++n > sz) {
buf[0] = '\000';
return NULL;
}
// Output the next digit.
*ptr++ = "0123456789abcdef"[j % base];
j /= base;
if (padding > 0)
padding--;
} while (j > 0 || padding > 0);
// Terminate the output with a NUL character.
*ptr = '\000';
// Conversion to ASCII actually resulted in the digits being in reverse
// order. We can't easily generate them in forward order, as we can't tell
// the number of characters needed until we are done converting.
// So, now, we reverse the string (except for the possible "-" sign).
while (--ptr > start) {
char ch = *ptr;
*ptr = *start;
*start++ = ch;
}
return buf;
}
// Safely appends string |source| to string |dest|. Never writes past the
// buffer size |dest_size| and guarantees that |dest| is null-terminated.
static void SafeAppendString(const char* source, char* dest, int dest_size) {
int dest_string_length = strlen(dest);
SAFE_ASSERT(dest_string_length < dest_size);
dest += dest_string_length;
dest_size -= dest_string_length;
strncpy(dest, source, dest_size);
// Making sure |dest| is always null-terminated.
dest[dest_size - 1] = '\0';
}
// Converts a 64-bit value into a hex string, and safely appends it to |dest|.
// Never writes past the buffer size |dest_size| and guarantees that |dest| is
// null-terminated.
static void SafeAppendHexNumber(uint64_t value, char* dest, int dest_size) {
// 64-bit numbers in hex can have up to 16 digits.
char buf[17] = {'\0'};
SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size);
}
// The implementation of our symbolization routine. If it
// successfully finds the symbol containing "pc" and obtains the
// symbol name, returns true and write the symbol name to "out".
// Otherwise, returns false. If Callback function is installed via
// InstallSymbolizeCallback(), the function is also called in this function,
// and "out" is used as its output.
// To keep stack consumption low, we would like this function to not
// get inlined.
static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
int out_size) {
uint64_t pc0 = reinterpret_cast<uintptr_t>(pc);
uint64_t start_address = 0;
uint64_t end_address = 0;
uint64_t base_address = 0;
int object_fd = -1;
if (out_size < 1) {
return false;
}
out[0] = '\0';
SafeAppendString("(", out, out_size);
if (g_symbolize_open_object_file_callback) {
object_fd = g_symbolize_open_object_file_callback(pc0, start_address,
base_address, out + 1,
out_size - 1);
} else {
object_fd = OpenObjectFileContainingPcAndGetStartAddress(
pc0, start_address, base_address, end_address, out + 1, out_size - 1);
}
FileDescriptor wrapped_object_fd(object_fd);
#if defined(PRINT_UNSYMBOLIZED_STACK_TRACES)
{
#else
// Check whether a file name was returned.
if (object_fd < 0) {
#endif
if (out[1]) {
// The object file containing PC was determined successfully however the
// object file was not opened successfully. This is still considered
// success because the object file name and offset are known and tools
// like asan_symbolize.py can be used for the symbolization.
out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated.
SafeAppendString("+0x", out, out_size);
SafeAppendHexNumber(pc0 - base_address, out, out_size);
SafeAppendString(")", out, out_size);
return true;
}
// Failed to determine the object file containing PC. Bail out.
return false;
}
int elf_type = FileGetElfType(wrapped_object_fd.get());
if (elf_type == -1) {
return false;
}
if (g_symbolize_callback) {
// Run the call back if it's installed.
// Note: relocation (and much of the rest of this code) will be
// wrong for prelinked shared libraries and PIE executables.
uint64_t relocation = (elf_type == ET_DYN) ? start_address : 0;
int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(),
pc, out, out_size,
relocation);
if (num_bytes_written > 0) {
out += num_bytes_written;
out_size -= num_bytes_written;
}
}
if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0,
out, out_size, base_address)) {
if (out[1] && !g_symbolize_callback) {
// The object file containing PC was opened successfully however the
// symbol was not found. The object may have been stripped. This is still
// considered success because the object file name and offset are known
// and tools like asan_symbolize.py can be used for the symbolization.
out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated.
SafeAppendString("+0x", out, out_size);
SafeAppendHexNumber(pc0 - base_address, out, out_size);
SafeAppendString(")", out, out_size);
return true;
}
return false;
}
// Symbolization succeeded. Now we try to demangle the symbol.
DemangleInplace(out, out_size);
return true;
}
_END_GOOGLE_NAMESPACE_
#elif BUILDFLAG(IS_APPLE) && defined(HAVE_DLADDR)
#include <dlfcn.h>
#include <string.h>
_START_GOOGLE_NAMESPACE_
static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
int out_size) {
Dl_info info;
if (dladdr(pc, &info)) {
if ((int)strlen(info.dli_sname) < out_size) {
strcpy(out, info.dli_sname);
// Symbolization succeeded. Now we try to demangle the symbol.
DemangleInplace(out, out_size);
return true;
}
}
return false;
}
_END_GOOGLE_NAMESPACE_
#elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
#include <windows.h>
#include <dbghelp.h>
#ifdef _MSC_VER
#pragma comment(lib, "dbghelp")
#endif
_START_GOOGLE_NAMESPACE_
class SymInitializer {
public:
HANDLE process;
bool ready;
SymInitializer() : process(NULL), ready(false) {
// Initialize the symbol handler.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680344(v=vs.85).aspx
process = GetCurrentProcess();
// Defer symbol loading.
// We do not request undecorated symbols with SYMOPT_UNDNAME
// because the mangling library calls UnDecorateSymbolName.
SymSetOptions(SYMOPT_DEFERRED_LOADS);
if (SymInitialize(process, NULL, true)) {
ready = true;
}
}
~SymInitializer() {
SymCleanup(process);
// We do not need to close `HANDLE process` because it's a "pseudo handle."
}
private:
SymInitializer(const SymInitializer&);
SymInitializer& operator=(const SymInitializer&);
};
static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
int out_size) {
const static SymInitializer symInitializer;
if (!symInitializer.ready) {
return false;
}
// Resolve symbol information from address.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx
char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(buf);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
// We use the ANSI version to ensure the string type is always `char *`.
// This could break if a symbol has Unicode in it.
BOOL ret = SymFromAddr(symInitializer.process,
reinterpret_cast<DWORD64>(pc), 0, symbol);
if (ret == 1 && static_cast<int>(symbol->NameLen) < out_size) {
// `NameLen` does not include the null terminating character.
strncpy(out, symbol->Name, static_cast<size_t>(symbol->NameLen) + 1);
out[static_cast<size_t>(symbol->NameLen)] = '\0';
// Symbolization succeeded. Now we try to demangle the symbol.
DemangleInplace(out, out_size);
return true;
}
return false;
}
_END_GOOGLE_NAMESPACE_
#else
# error BUG: HAVE_SYMBOLIZE was wrongly set
#endif
_START_GOOGLE_NAMESPACE_
bool Symbolize(void *pc, char *out, int out_size) {
SAFE_ASSERT(out_size >= 0);
return SymbolizeAndDemangle(pc, out, out_size);
}
_END_GOOGLE_NAMESPACE_
#else /* HAVE_SYMBOLIZE */
#include <assert.h>
#include "config.h"
_START_GOOGLE_NAMESPACE_
// TODO: Support other environments.
bool Symbolize(void *pc, char *out, int out_size) {
assert(0);
return false;
}
_END_GOOGLE_NAMESPACE_
#endif
| chromium/chromium | base/third_party/symbolize/symbolize.cc | C++ | bsd-3-clause | 32,173 |
/*
* Copyright (C) 2010, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_DEFERRED_TASK_HANDLER_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_DEFERRED_TASK_HANDLER_H_
#include <atomic>
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/thread_safe_ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/threading.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
namespace base {
class SingleThreadTaskRunner;
}
namespace blink {
class BaseAudioContext;
class OfflineAudioContext;
class AudioHandler;
class AudioNodeOutput;
class AudioSummingJunction;
// DeferredTaskHandler manages the major part of pre- and post- rendering tasks,
// and provides a lock mechanism against the audio rendering graph. A
// DeferredTaskHandler object is created when an BaseAudioContext object is
// created.
//
// DeferredTaskHandler outlives the BaseAudioContext only if all of the
// following conditions match:
// - An audio rendering thread is running,
// - It is requested to stop,
// - The audio rendering thread calls requestToDeleteHandlersOnMainThread(),
// - It posts a task of deleteHandlersOnMainThread(), and
// - GC happens and it collects the BaseAudioContext before the task execution.
//
class MODULES_EXPORT DeferredTaskHandler final
: public ThreadSafeRefCounted<DeferredTaskHandler>,
public base::SupportsWeakPtr<DeferredTaskHandler> {
public:
static scoped_refptr<DeferredTaskHandler> Create(
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~DeferredTaskHandler();
void HandleDeferredTasks();
void ContextWillBeDestroyed();
// BaseAudioContext can pull node(s) at the end of each render quantum even
// when they are not connected to any downstream nodes. These two methods are
// called by the nodes who want to add/remove themselves into/from the
// automatic pull lists.
void AddAutomaticPullNode(scoped_refptr<AudioHandler>);
void RemoveAutomaticPullNode(AudioHandler*);
// Return true if there is one or more nodes in the automatic pull node list.
bool HasAutomaticPullNodes();
// Called right before handlePostRenderTasks() to handle nodes which need to
// be pulled even when they are not connected to anything.
void ProcessAutomaticPullNodes(uint32_t frames_to_process);
// Keep track of AudioNode's that have their channel count mode changed. We
// process the changes in the post rendering phase.
void AddChangedChannelCountMode(AudioHandler*);
void RemoveChangedChannelCountMode(AudioHandler*);
// Keep track of AudioNode's that have their channel interpretation
// changed. We process the changes in the post rendering phase.
void AddChangedChannelInterpretation(AudioHandler*);
void RemoveChangedChannelInterpretation(AudioHandler*);
// Only accessed when the graph lock is held.
void MarkSummingJunctionDirty(AudioSummingJunction*);
// Only accessed when the graph lock is held. Must be called on the main
// thread.
void RemoveMarkedSummingJunction(AudioSummingJunction*);
void MarkAudioNodeOutputDirty(AudioNodeOutput*);
void RemoveMarkedAudioNodeOutput(AudioNodeOutput*);
// Break connections between nodes. This is done on the audio thread with the
// graph lock.
void BreakConnections();
void AddRenderingOrphanHandler(scoped_refptr<AudioHandler>);
void RequestToDeleteHandlersOnMainThread();
void ClearHandlersToBeDeleted();
// Clear the context from the rendering and deletable orphan handlers.
void ClearContextFromOrphanHandlers();
bool AcceptsTailProcessing() const { return accepts_tail_processing_; }
void StopAcceptingTailProcessing() { accepts_tail_processing_ = false; }
// If |node| requires tail processing, add it to the list of tail
// nodes so the tail is processed.
void AddTailProcessingHandler(scoped_refptr<AudioHandler>);
// Remove |node| from the list of tail nodes (because the tail processing is
// complete). Set |disable_outputs| to true if the outputs of the handler
// should also be disabled. This should be true if the tail is done. But if
// we're reconnected or re-enabled, then |disable_outputs| should be false.
void RemoveTailProcessingHandler(AudioHandler*, bool disable_outputs);
// Remove all tail processing nodes. Should be called only when the
// context is done.
void FinishTailProcessing();
// For handlers that have finished processing their tail and require disabling
// the ouputs of the handler, we do that here.
void DisableOutputsForTailProcessing();
//
// Thread Safety and Graph Locking:
//
void SetAudioThreadToCurrentThread();
// It is okay to use a relaxed (no-barrier) load here. Because the data
// referenced by m_audioThread is not actually being used, thus we do not
// need a barrier between the load of m_audioThread and of that data.
bool IsAudioThread() const {
return CurrentThread() == audio_thread_.load(std::memory_order_relaxed);
}
void lock() EXCLUSIVE_LOCK_FUNCTION(context_graph_mutex_);
bool TryLock() EXCLUSIVE_TRYLOCK_FUNCTION(true, context_graph_mutex_);
void unlock() UNLOCK_FUNCTION(context_graph_mutex_);
// This locks the audio render thread for OfflineAudioContext rendering.
// MUST NOT be used in the real-time audio context.
void OfflineLock() EXCLUSIVE_LOCK_FUNCTION(context_graph_mutex_);
// In DCHECK builds, fails if this thread does not own the context's lock.
void AssertGraphOwner() const ASSERT_EXCLUSIVE_LOCK(context_graph_mutex_) {
context_graph_mutex_.AssertAcquired();
}
class MODULES_EXPORT GraphAutoLocker {
STACK_ALLOCATED();
public:
explicit GraphAutoLocker(DeferredTaskHandler& handler) : handler_(handler) {
handler_.lock();
}
explicit GraphAutoLocker(const BaseAudioContext*);
~GraphAutoLocker() { handler_.unlock(); }
private:
DeferredTaskHandler& handler_;
};
// This is for locking offline render thread (which is considered as the
// audio thread) with unlocking on self-destruction at the end of the scope.
// Also note that it uses lock() rather than tryLock() because the timing
// MUST be accurate on offline rendering.
class MODULES_EXPORT OfflineGraphAutoLocker {
STACK_ALLOCATED();
public:
explicit OfflineGraphAutoLocker(OfflineAudioContext*);
~OfflineGraphAutoLocker() { handler_.unlock(); }
private:
DeferredTaskHandler& handler_;
};
HashSet<scoped_refptr<AudioHandler>>* GetActiveSourceHandlers() {
return &active_source_handlers_;
}
Vector<scoped_refptr<AudioHandler>>* GetFinishedSourceHandlers() {
return &finished_source_handlers_;
}
// The number of frames to render each time. After construction, this value
// is only read (never modified), and may be read by both the audio thread and
// the main thread.
unsigned int RenderQuantumFrames() const { return render_quantum_frames_; }
private:
explicit DeferredTaskHandler(scoped_refptr<base::SingleThreadTaskRunner>);
void UpdateAutomaticPullNodes();
void UpdateChangedChannelCountMode();
void UpdateChangedChannelInterpretation();
void HandleDirtyAudioSummingJunctions();
void HandleDirtyAudioNodeOutputs();
void DeleteHandlersOnMainThread();
// Check tail processing handlers and remove any handler if the tail
// has been processed.
void UpdateTailProcessingHandlers();
// For the sake of thread safety, we maintain a seperate Vector of
// AudioHandlers for "automatic-pull nodes":
// |rendering_automatic_pull_handlers|. This storage will be copied from
// |automatic_pull_handlers| by |UpdateAutomaticPullNodes()| at the beginning
// or end of the render quantum.
HashSet<scoped_refptr<AudioHandler>> automatic_pull_handlers_;
Vector<scoped_refptr<AudioHandler>> rendering_automatic_pull_handlers_;
// Keeps track if the |automatic_pull_handlers| storage is touched.
bool automatic_pull_handlers_need_updating_;
// Number of frames to use when rendering the graph. This is the frames to
// process for each node.
unsigned int render_quantum_frames_ = 128;
// Collection of nodes where the channel count mode has changed. We want the
// channel count mode to change in the pre- or post-rendering phase so as
// not to disturb the running audio thread.
HashSet<AudioHandler*> deferred_count_mode_change_;
HashSet<AudioHandler*> deferred_channel_interpretation_change_;
// These two HashSet must be accessed only when the graph lock is held.
// These raw pointers are safe because their destructors unregister them.
HashSet<AudioSummingJunction*> dirty_summing_junctions_;
HashSet<AudioNodeOutput*> dirty_audio_node_outputs_;
Vector<scoped_refptr<AudioHandler>> rendering_orphan_handlers_;
Vector<scoped_refptr<AudioHandler>> deletable_orphan_handlers_;
// Nodes that are processing its tail.
Vector<scoped_refptr<AudioHandler>> tail_processing_handlers_;
// Tail processing nodes that are now finished and want the output to be
// disabled. This is updated in the audio thread (with the graph lock). The
// main thread will disable the outputs.
Vector<scoped_refptr<AudioHandler>> finished_tail_processing_handlers_;
// Once the associated context closes, new tail processing handlers are not
// accepted.
bool accepts_tail_processing_ = true;
// When source nodes are started, we place the handlers here to keep track of
// these active sources. We must call AudioHandler::makeConnection() when we
// add an AudioNode to this, and must call AudioHandler::breakConnection()
// when we remove an AudioNode from this.
//
// This can be accessed from either the main thread or the audio thread, so it
// must be protected by the graph lock.
HashSet<scoped_refptr<AudioHandler>> active_source_handlers_;
// When source nodes are finished, the handler is placed here to make a note
// of it. At a render quantum boundary, these are used to break the
// connection and elements here are removed from |active_source_handlers_|.
//
// This must be accessed only from the audio thread.
Vector<scoped_refptr<AudioHandler>> finished_source_handlers_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
// Graph locking.
RecursiveMutex context_graph_mutex_;
// Protects |rendering_automatic_pull_handlers| when updating, processing, and
// clearing. (See crbug.com/1061018)
mutable Mutex automatic_pull_handlers_lock_;
std::atomic<base::PlatformThreadId> audio_thread_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_DEFERRED_TASK_HANDLER_H_
| chromium/chromium | third_party/blink/renderer/modules/webaudio/deferred_task_handler.h | C | bsd-3-clause | 12,181 |
from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = 'testuser@buymore.com'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
| jinnykoo/christmas | src/oscar/test/testcases.py | Python | bsd-3-clause | 3,477 |
/*
* Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2009 Anthony Ricaud <rik@webkit.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 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.
*/
.resources.panel .sidebar {
padding-left: 0;
z-index: 10;
display: block;
}
.resources.panel .sidebar li {
height: 18px;
white-space: nowrap;
}
.resources.panel .sidebar li.selected {
color: white;
text-shadow: rgba(0, 0, 0, 0.33) 1px 1px 0;
}
.resources.panel .sidebar li.selected .selection {
background-image: linear-gradient(to bottom, rgb(162, 177, 207), rgb(120, 138, 177));
border-top: 1px solid #979797;
height: 18px;
}
.resources.panel .sidebar :focus li.selected .selection {
background-image: linear-gradient(to bottom, rgb(92, 147, 213), rgb(21, 83, 170));
border-top: 1px solid rgb(68, 128, 200);
}
body.inactive .resources.panel .sidebar li.selected .selection {
background-image: linear-gradient(to bottom, rgb(180, 180, 180), rgb(138, 138, 138));
border-top: 1px solid rgb(151, 151, 151);
}
.resources.panel .sidebar .icon {
width: 16px;
height: 16px;
float: left;
}
.resources.panel .base-storage-tree-element-title {
overflow: hidden;
position: relative;
text-overflow: ellipsis;
padding-left: 2px;
top: 1px;
}
.resources-toolbar {
border-top: 1px solid #ccc;
background-color: #eee;
}
li.selected .base-storage-tree-element-subtitle {
color: white;
}
.base-storage-tree-element-subtitle {
padding-left: 2px;
color: rgb(80, 80, 80);
text-shadow: none;
}
.resources.panel .status {
float: right;
height: 16px;
margin-top: 1px;
margin-left: 4px;
line-height: 1em;
}
.resources.panel li .status .bubble-repeat-count {
height: 13px;
margin-top: 1px;
padding-top: 0;
}
.storage-view {
display: flex;
overflow: hidden;
}
.storage-view {
overflow: hidden;
}
.storage-view .data-grid:not(.inline) {
border: none;
flex: auto;
}
.storage-view .storage-table-error {
color: rgb(66%, 33%, 33%);
font-size: 24px;
font-weight: bold;
padding: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.storage-view.query {
padding: 2px 0;
overflow-y: overlay;
overflow-x: hidden;
}
.database-query-prompt {
position: relative;
padding: 1px 22px 1px 24px;
min-height: 16px;
white-space: pre-wrap;
-webkit-user-modify: read-write-plaintext-only;
-webkit-user-select: text;
}
.database-user-query::before,
.database-query-prompt::before,
.database-query-result::before {
position: absolute;
display: block;
content: "";
left: 7px;
top: 0.8em;
width: 10px;
height: 10px;
margin-top: -7px;
-webkit-user-select: none;
background-image: url(Images/toolbarButtonGlyphs.png);
background-size: 352px 168px;
}
@media (-webkit-min-device-pixel-ratio: 1.5) {
.database-user-query::before,
.database-query-prompt::before,
.database-query-result::before {
background-image: url(Images/toolbarButtonGlyphs_2x.png);
}
} /* media */
.database-query-prompt::before {
background-position: -192px -96px;
}
.database-user-query {
position: relative;
border-bottom: 1px solid rgb(245, 245, 245);
padding: 1px 22px 1px 24px;
min-height: 16px;
flex-shrink: 0;
}
.database-user-query::before {
background-position: -192px -107px;
}
.database-query-text {
color: rgb(0, 128, 255);
-webkit-user-select: text;
}
.database-query-result {
position: relative;
padding: 1px 22px 1px 24px;
min-height: 16px;
margin-left: -24px;
padding-right: 0;
}
.database-query-result.error {
color: red;
-webkit-user-select: text;
}
.database-query-result.error::before {
background-position: -213px -96px;
}
.resource-sidebar-tree-item .icon {
content: url(Images/resourcePlainIcon.png);
}
.children.small .resource-sidebar-tree-item .icon {
content: url(Images/resourcePlainIconSmall.png);
}
.resource-sidebar-tree-item.resources-type-image .icon {
position: relative;
background-image: url(Images/resourcePlainIcon.png);
background-repeat: no-repeat;
content: "";
}
.resources-type-image .image-resource-icon-preview {
position: absolute;
margin: auto;
top: 3px;
bottom: 4px;
left: 5px;
right: 5px;
max-width: 18px;
max-height: 21px;
min-width: 1px;
min-height: 1px;
}
.children.small .resource-sidebar-tree-item.resources-type-image .icon {
background-image: url(Images/resourcePlainIconSmall.png);
content: "";
}
.children.small .resources-type-image .image-resource-icon-preview {
top: 2px;
bottom: 1px;
left: 3px;
right: 3px;
max-width: 8px;
max-height: 11px;
overflow: hidden;
}
.resource-sidebar-tree-item.resources-type-document .icon {
content: url(Images/resourceDocumentIcon.png);
}
.children.small .resource-sidebar-tree-item.resources-type-document .icon {
content: url(Images/resourceDocumentIconSmall.png);
}
.resource-sidebar-tree-item.resources-type-stylesheet .icon {
content: url(Images/resourceCSSIcon.png);
}
.children.small .resource-sidebar-tree-item.resources-type-stylesheet .icon {
content: url(Images/resourceDocumentIconSmall.png);
}
.resource-sidebar-tree-item.resources-type-image .icon {
position: relative;
background-image: url(Images/resourcePlainIcon.png);
background-repeat: no-repeat;
content: "";
}
.children.small .resource-sidebar-tree-item.resources-type-image .icon {
background-image: url(Images/resourcePlainIconSmall.png);
content: "";
}
.resource-sidebar-tree-item.resources-type-font .icon {
content: url(Images/resourcePlainIcon.png);
}
.children.small .resource-sidebar-tree-item.resources-type-font .icon {
content: url(Images/resourcePlainIconSmall.png);
}
.resource-sidebar-tree-item.resources-type-script .icon {
content: url(Images/resourceJSIcon.png);
}
.children.small .resource-sidebar-tree-item.resources-type-script .icon {
content: url(Images/resourceDocumentIconSmall.png);
}
.resource-sidebar-tree-item.resources-type-xhr .icon {
content: url(Images/resourcePlainIcon.png);
}
.children.small .resource-sidebar-tree-item.resources-type-xhr .icon {
content: url(Images/resourceDocumentIconSmall.png);
}
.frame-storage-tree-item .icon {
content: url(Images/frame.png);
}
.database-storage-tree-item .icon {
content: url(Images/database.png);
}
.database-table-storage-tree-item .icon {
content: url(Images/databaseTable.png);
}
.indexed-db-storage-tree-item .icon {
content: url(Images/indexedDB.png);
}
.indexed-db-object-store-storage-tree-item .icon {
content: url(Images/indexedDBObjectStore.png);
}
.indexed-db-index-storage-tree-item .icon {
content: url(Images/indexedDBIndex.png);
}
.service-worker-cache-tree-item .icon {
content: url(Images/indexedDBObjectStore.png);
}
.service-worker-cache-storage-tree-item .icon {
content: url(Images/indexedDB.png);
}
.service-workers-tree-item .icon {
content: url(Images/serviceWorker.svg);
}
.domstorage-storage-tree-item.local-storage .icon {
content: url(Images/localStorage.png);
}
.domstorage-storage-tree-item.session-storage .icon {
content: url(Images/sessionStorage.png);
}
.cookie-storage-tree-item .icon {
content: url(Images/cookie.png);
}
.application-cache-storage-tree-item .icon {
content: url(Images/applicationCache.png);
}
.file-system-storage-tree-item .icon {
content: url(Images/fileSystem.png);
}
| vadimtk/chrome4sdp | third_party/WebKit/Source/devtools/front_end/resources/resourcesPanel.css | CSS | bsd-3-clause | 9,056 |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROMEOS_SERVICES_LIBASSISTANT_GRPC_UTILS_TIMER_UTILS_H_
#define CHROMEOS_SERVICES_LIBASSISTANT_GRPC_UTILS_TIMER_UTILS_H_
#include "chromeos/assistant/internal/libassistant/shared_headers.h"
#include "chromeos/services/libassistant/public/cpp/assistant_timer.h"
namespace assistant {
namespace api {
class OnAlarmTimerEventRequest;
namespace params {
enum class TimerStatus;
class Timer;
class TimerParams;
} // namespace params
} // namespace api
} // namespace assistant
namespace chromeos {
namespace libassistant {
::assistant::api::OnAlarmTimerEventRequest
CreateOnAlarmTimerEventRequestProtoForV1(
const std::vector<chromeos::assistant::AssistantTimer>& all_curr_timers);
// `timer_params` contains the information of all the current timers.
std::vector<assistant::AssistantTimer> ConstructAssistantTimersFromProto(
const ::assistant::api::params::TimerParams& timer_params);
void ConvertAssistantTimerToProtoTimer(const assistant::AssistantTimer& input,
::assistant::api::params::Timer* output);
void ConvertProtoTimerToAssistantTimer(
const ::assistant::api::params::Timer& input,
chromeos::assistant::AssistantTimer* output);
// Used both in |AssistantClientV1| and |FakeAssistantClient|.
std::vector<chromeos::assistant::AssistantTimer> GetAllCurrentTimersFromEvents(
const std::vector<assistant_client::AlarmTimerManager::Event>& events);
} // namespace libassistant
} // namespace chromeos
#endif // CHROMEOS_SERVICES_LIBASSISTANT_GRPC_UTILS_TIMER_UTILS_H_
| ric2b/Vivaldi-browser | chromium/chromeos/services/libassistant/grpc/utils/timer_utils.h | C | bsd-3-clause | 1,720 |
/**
* Copyright (c) 2014-present, The osquery authors
*
* This source code is licensed as defined by the LICENSE file found in the
* root directory of this source tree.
*
* SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only)
*/
#include <string>
#include <boost/filesystem.hpp>
#include <boost/optional.hpp>
#include <sqlite3.h>
namespace osquery {
static boost::optional<std::string> findExistingProgramPathFromCommand(
const char* path, char escape_symbol, bool allow_quoting, bool shortest) {
size_t length = strlen(path);
std::string result;
size_t pos = 0;
// Skip spaces
for (; pos < length; ++pos) {
if (!isspace(path[pos])) {
break;
}
}
std::string temp_string;
bool is_quoted = false;
bool is_escaped = false;
for (; pos < length; ++pos) {
if (is_escaped) {
temp_string += path[pos];
is_escaped = false;
continue;
}
if (allow_quoting && path[pos] == '"') {
is_quoted = !is_quoted;
continue;
}
if (path[pos] == escape_symbol) {
is_escaped = true;
continue;
}
if (!is_quoted && isspace(path[pos])) {
// validate temp string
boost::filesystem::path test_path = temp_string;
auto status = boost::filesystem::status(test_path);
if (boost::filesystem::exists(status) &&
!boost::filesystem::is_directory(status)) {
result = temp_string;
if (shortest) {
break;
}
}
}
temp_string += path[pos];
}
if (result.length() == 0 || !shortest) {
boost::filesystem::path test_path = temp_string;
auto status = boost::filesystem::status(test_path);
if (boost::filesystem::exists(status) &&
!boost::filesystem::is_directory(status)) {
result = temp_string;
}
}
return result;
}
static boost::optional<std::string> findExistingProgramPathFromCommandSqlArgs(
int argc, sqlite3_value** argv, bool shortest) {
if (argc == 0) {
return boost::none;
}
// NULLs are not allowed
for (int i = 0; i < argc; i++) {
if (SQLITE_NULL == sqlite3_value_type(argv[i])) {
return boost::none;
}
}
const char* path = reinterpret_cast<const char*>(sqlite3_value_text(argv[0]));
bool allow_quoting = false;
if (argc > 1) {
allow_quoting = sqlite3_value_int(argv[1]) != 0 ? true : false;
}
#ifdef WIN32
char escape_symbol = '^';
#else
char escape_symbol = '\\';
#endif
if (argc > 2) {
const char* escape_symbol_string =
reinterpret_cast<const char*>(sqlite3_value_text(argv[2]));
if (escape_symbol_string == NULL ||
std::strlen(escape_symbol_string) != 1) {
return boost::none;
}
escape_symbol = escape_symbol_string[0];
}
return findExistingProgramPathFromCommand(
path, escape_symbol, allow_quoting, shortest);
}
static void findFilePathInLaunchCommand(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
auto result = findExistingProgramPathFromCommandSqlArgs(argc, argv, true);
if (result) {
sqlite3_result_text(context,
result->c_str(),
static_cast<int>(result->size()),
SQLITE_TRANSIENT);
} else {
sqlite3_result_error(
context, "Invalid inputs to find_binary_path_from_cmd", -1);
}
}
static void isPathDeterministic(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
auto shortest = findExistingProgramPathFromCommandSqlArgs(argc, argv, true);
if (shortest) {
const char* path = (const char*)sqlite3_value_text(argv[0]);
if (shortest->length() == 0 || shortest->length() == strlen(path)) {
// There are 2 cases:
// 1 - empty string, all parts of path are invalid,
// so path is deterministic
// 2 - short == full, then there is only 1 valid path
sqlite3_result_int(context, 1);
return;
} else {
auto longest =
findExistingProgramPathFromCommandSqlArgs(argc, argv, false);
if (longest) {
sqlite3_result_int(context,
shortest->length() == longest->length() ? 1 : 0);
return;
}
}
}
sqlite3_result_error(context, "Invalid inputs to is_path_deterministic", -1);
}
static void getParentDirectory(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
if (sqlite3_value_type(argv[0]) != SQLITE_TEXT) {
sqlite3_result_error(
context, "Invalid inputs to parent_directory, TEXT was expected", -1);
return;
}
const char* path = reinterpret_cast<const char*>(sqlite3_value_text(argv[0]));
if (path == nullptr) {
sqlite3_result_null(context);
return;
}
int pos = 0;
int last_slash_pos = -1;
#if defined(OSQUERY_WINDOWS)
char directory_symbol = '\\';
#elif defined(OSQUERY_POSIX)
char directory_symbol = '/';
#else
#error Unsupported platform
#endif
while (path[pos] != '\0') {
if (path[pos] == directory_symbol) {
last_slash_pos = pos;
}
pos++;
}
if (last_slash_pos < 0) {
// No parent directory
sqlite3_result_null(context);
return;
}
char* result = reinterpret_cast<char*>(malloc(last_slash_pos));
memcpy(result, path, last_slash_pos);
sqlite3_result_text(context, result, last_slash_pos, free);
}
void registerFilesystemExtensions(sqlite3* db) {
sqlite3_create_function(db,
"is_path_deterministic",
-1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
isPathDeterministic,
nullptr,
nullptr);
sqlite3_create_function(db,
"find_file_path_in_cmd",
-1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
findFilePathInLaunchCommand,
nullptr,
nullptr);
sqlite3_create_function(db,
"parent_directory",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
getParentDirectory,
nullptr,
nullptr);
}
} // namespace osquery
| lwhsu/osquery | osquery/sql/sqlite_filesystem.cpp | C++ | bsd-3-clause | 6,498 |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace Kooboo.CMS.Common.Runtime.Mvc
{
public class MvcDependencyAttributeFilterProvider : FilterAttributeFilterProvider
{
private readonly IEngine _engine;
/// <summary>
/// Initializes a new instance of the <see cref="NinjectFilterAttributeFilterProvider"/> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
public MvcDependencyAttributeFilterProvider(IEngine engine)
{
this._engine = engine;
}
/// <summary>
/// Gets the controller attributes.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="actionDescriptor">The action descriptor.</param>
/// <returns>The filters defined by attributes</returns>
protected override IEnumerable<FilterAttribute> GetControllerAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor)
{
var attributes = base.GetControllerAttributes(controllerContext, actionDescriptor);
foreach (var attribute in attributes)
{
this._engine.InjectProperties(attribute);
}
return attributes;
}
/// <summary>
/// Gets the action attributes.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="actionDescriptor">The action descriptor.</param>
/// <returns>The filters defined by attributes.</returns>
protected override IEnumerable<FilterAttribute> GetActionAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor)
{
var attributes = base.GetActionAttributes(controllerContext, actionDescriptor);
foreach (var attribute in attributes)
{
this._engine.InjectProperties(attribute);
}
return attributes;
}
}
}
| lingxyd/CMS | Kooboo.CMS/Kooboo.CMS.Common/Runtime/Mvc/MvcDependencyAttributeFilterProvider.cs | C# | bsd-3-clause | 2,292 |
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\optipng-bin\cli.js" %*
) ELSE (
node "%~dp0\..\optipng-bin\cli.js" %*
) | subtirelumihail/addit-game | node_modules/gulp-imagemin/node_modules/image-min/node_modules/.bin/optipng.cmd | Batchfile | mit | 133 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fscc
{
/// <summary>
/// the response packet of FSCTL_PIPE_TRANSCEIVE
/// </summary>
public class FsccFsctlPipeTransceiveResponsePacket : FsccStandardPacket<FSCTL_PIPE_TRANSCEIVE>
{
#region Properties
/// <summary>
/// the command of fscc packet
/// </summary>
public override uint Command
{
get
{
return (uint)FsControlCommand.FSCTL_PIPE_TRANSCEIVE;
}
}
#endregion
#region Constructors
/// <summary>
/// default constructor
/// </summary>
public FsccFsctlPipeTransceiveResponsePacket()
: base()
{
}
#endregion
#region Marshaling and Unmarshaling Methods
/// <summary>
/// marshaling this packet to bytes.
/// </summary>
/// <returns>the bytes of this packet </returns>
public override byte[] ToBytes()
{
byte[] payload;
if (this.Payload.Data == null || this.Payload.Data.Length == 0)
{
payload = new byte[0];
}
else
{
payload = new byte[this.Payload.Data.Length];
Array.Copy(this.Payload.Data, payload, payload.Length);
}
return payload;
}
/// <summary>
/// unmarshaling packet from bytes
/// </summary>
/// <param name = "packetBytes">the bytes of packet </param>
public override void FromBytes(byte[] packetBytes)
{
byte[] payload;
if (packetBytes == null || packetBytes.Length == 0)
{
payload = new byte[0];
}
else
{
payload = new byte[packetBytes.Length];
Array.Copy(packetBytes, payload, packetBytes.Length);
}
FSCTL_PIPE_TRANSCEIVE transceivePayload = new FSCTL_PIPE_TRANSCEIVE();
transceivePayload.Data = payload;
this.Payload = transceivePayload;
}
#endregion
}
}
| dongruiqing/WindowsProtocolTestSuites | ProtoSDK/MS-FSCC/Messages/FsccFsctlPipeTransceiveResponsePacket.cs | C# | mit | 2,384 |
<?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Tests\RuleSet\Sets;
/**
* @internal
*
* @covers \PhpCsFixer\RuleSet\Sets\PHPUnit60MigrationRiskySet
*/
final class PHPUnit60MigrationRiskySetTest extends AbstractSetTest
{
}
| gharlan/PHP-CS-Fixer | tests/RuleSet/Sets/PHPUnit60MigrationRiskySetTest.php | PHP | mit | 496 |
---
title: Telerik.Web.UI.GridEditableItem
page_title: Telerik.Web.UI.GridEditableItem
description: Telerik.Web.UI.GridEditableItem
---
# Telerik.Web.UI.GridEditableItem
Represents the base class for any items that display and edit data in a
Telerik.Web.UI.GridTableView GridTableViewof RadGrid. Inheritors has the
capabilities to:bullet Locate a table cell based on the column unique namesExtract values from the cells of column editorsHas a dictionary of saved-old-values that are necessary for optimistic concurency
editing oprationsEdit/browse modeEditManager instance, which is capable of locating the column
editors
## Inheritance Hierarchy
* System.Object
* System.Web.UI.Control
* System.Web.UI.WebControls.WebControl
* System.Web.UI.WebControls.TableRow
* Telerik.Web.UI.GridTableRow
* Telerik.Web.UI.GridItem
* Telerik.Web.UI.GridEditableItem
## Properties
### EditManager `GridEditManager`
Allows you to access the column editors
### Item `TableCell`
### Item `TableCell`
### SavedOldValues `IDictionary`
Gets the old value of the edited item
### CanExtractValues `Boolean`
### KeyValues `String`
### OwnerTableView `GridTableView`
Gets a reference to the GridTableView that owns this
GridItem.
### OwnerID `String`
Gets the ClientID of the GridTableView that
owns this instance.
### OwnerGridID `String`
Gets the ClientID of the RadGrid instance that
owns the item.
#### Remarks
This would be useful if several controls use the same eventhandler and you need
to diferentiate the Grid instances in the handler.
### HasChildItems `Boolean`
Gets a value indicating whether this item has child items - or items somehow
related to this.
### CanExpand `Boolean`
Gets a value indicating whether the item can be "expanded" to show its child items
### DataItem `Object`
The original DataItem from the DataSource. See
examples section below.
### DataSetIndex `Int32`
Gets the index of the GridDataItem in the underlying
DataTable/specified table from a DataSet.
### ItemIndex `Int32`
Gets the index of the grid item among the
collection. This index also can be used to get the DataKeyValues
corresponding to this item from a GridTableView.
### ClientRowIndex `Int32`
Gets the index of the row as in the html table object rendered on the client
### RowIndex `Int32`
Gets the index of the item in the rows collection of the underlying Table server control
### ItemIndexHierarchical `Int32`
Get the unique item index among all the item in the hierarchy. This index is used when setting item to selected, edited, etc
### ItemType `GridItemType`
Gets the respective GridItemType of the grid item.
### Expanded `Boolean`
Gets or sets a value indicating whether the grid item is expanded or
collapsed.
### ConditionalExpanded `Boolean`
Used in HierarchyLoadMode="Conditional"
### Display `Boolean`
Sets whether the GridItem will be visible or with style="display:none;"
### Selected `Boolean`
Gets or set a value indicating whether the grid item is selected
### SelectableMode `GridItemSelectableMode`
Gets or sets a value determining if the chould be selected
either on the client or on the server.
### Edit `Boolean`
Sets the Item in edit mode. Requires Telerik RadGrid to rebind.
#### Remarks
If is set to InPlace, the grid column
editors will be displayed inline of this item.
If is set to EditForms, a new
GridItem will be created, which will be child of this item
(GridEditFormItem). The new item will hold the edit form.
### GroupIndex `String`
Gets the index of the Item in the group. This works only when grouping.
### IsDataBound `Boolean`
Gets a value indicating whether the grid item is bound to a data source.
### IsInEditMode `Boolean`
Gets a value indicating whether the grid item is in edit mode at the
moment.
### OriginalClientID `String`
### ClientID `String`
Gets the server control identifier generated by ASP.NET.
## Methods
### InitializeEditorInCell
#### Returns
`System.Void`
### ExtractValues
Extracts values for each column, using
#### Parameters
#### newValues `System.Collections.IDictionary`
This dictionary to fill, this parameter should not be null
#### Returns
`System.Void`
### UpdateValues
Extracts values for each column, using and updates values in provided object;
#### Parameters
#### objectToUpdate `System.Object`
The object that should be updated
#### Returns
`System.Void`
### GetDataKeyValue
Get the DataKeyValues from the owner GridTableView with the corresponding item ItemIndex and keyName.
The keyName should be one of the specified in the array
#### Parameters
#### keyName `System.String`
data key name
#### Returns
`System.Object` data key value
### FireCommandEvent
Use this method to simulate item command event that bubbles to RadGrid and can be handeled automatically or in a custom manner,
handling RadGrid.ItemCommand event.
#### Parameters
#### commandName `System.String`
command to bubble, for example 'Page'
#### commandArgument `System.Object`
command argument, for example 'Next'
#### Returns
`System.Void`
### RestoreDecorator
This method is not intended to be used directly from your code.
#### Returns
`System.Void`
### Initialize
This method is not intended to be used directly from your code
#### Returns
`System.Void`
### SetupItem
This method is not intended to be used directly from your code
#### Returns
`System.Void`
### PrepareItemStyle
Override this method to change the default logic for rendering the item
#### Returns
`System.Void`
### PrepareItemVisibility
Override this method to change the default logic for item visibility
#### Returns
`System.Void`
### SetTempIndexHierarchical
Used after postback before ViewState becomes available -
for example in ItemCreated and ItemDataBound events
#### Parameters
#### value `System.String`
#### Returns
`System.Void`
### RemoveChildSelectedItems
#### Returns
`System.Void`
### RemoveChildEditItems
#### Returns
`System.Void`
### SetChildrenVisible
#### Returns
`System.Void`
### SetVisibleChildren
#### Returns
`System.Void`
### ExpandHierarchyToTop
#### Returns
`System.Void`
### CalcColSpan
Calculate column-span value for a cell using column list, when the cell indicated
with FromCellIndex should be spanned to ToCellIndex
#### Parameters
#### columns `Telerik.Web.UI.GridColumn`
columns - visible property is taken in count
#### FromCellIndex `System.Int32`
cell inbdex of spanned cell
#### ToCellIndex `System.Int32`
cell index of next not-spanned cell or -1 for the last cell index
#### Returns
`System.Int32` ColSpan number
| scstauf/ajax-docs | api/server/Telerik.Web.UI/GridEditableItem.md | Markdown | mit | 7,012 |
{% extends "problem/base.html" %}
{% load staticfiles %}
{% load bootstrap %}
{% block title_name %}
<title>Edit Problem {{ problem.pk }}</title>
{% endblock title_name %}
{% block import_source %}
{{ block.super }}
<link rel="stylesheet" href="{% static 'problem/css/edit.css' %}">
{% endblock %}
{% block body_block %}
<div class="container" id="Body">
<h2>
{{ problem.pk }} - {{ problem.pname }}
<a href="{% url 'problem:detail' problem.pk %}" class="btn btn-primary">
See this problem
</a>
<a href="{% url 'problem:problem' %}" class="btn btn-info">
Back to problem panel
</a>
</h2>
<div style="width:80%; float:left;">
<ul class="nav nav-tabs" role="tablist">
<li class="active">
<a href="#info" role="tab" data-toggle="tab">Info</a>
</li>
<li>
<a href="#description" role="tab" data-toggle="tab">Description</a>
</li>
<li>
<a href="#sample_io" role="tab" data-toggle="tab">Sample IO</a>
</li>
<li>
<a href="#tag" role="tab" data-toggle="tab">Tag</a>
</li>
<li>
<a href="#testcase" role="tab" data-toggle="tab">TestCase</a>
</li>
</ul>
<div class="tab-content">
<form method="POST" id="problem_info" action="" enctype="multipart/form-data">
{{ form.media }}
<div>
<input type="submit" value="Preview" class="btn btn-success" id="preview_button">
<input type="submit" value="Save" class="btn btn-primary" id="save_button">
<a class="btn btn-warning" href="{% url 'problem:detail' problem.pk %}">Cancel</a>
</div>
{% csrf_token %}
<div class="tab-pane active" id="info">
{% include "problem/editTab/info.html" with form=form pid=problem.pk path=path %}
</div>
<div class="tab-pane" id="description">
{{ form.description|bootstrap }}
{{ form.input|bootstrap }}
{{ form.output|bootstrap }}
</div>
<div class="tab-pane" id="sample_io">
<div class="panel panel-default" style="float:left;width:47%">
<div class="panel-heading">Sample Input</div>
<textarea name="sample_in" class="panel-body"
style="width:100%" rows="20">{{ problem.sample_in }}</textarea>
</div>
<div class="panel panel-default" style="float:right;width:47%">
<div class="panel-heading">Sample Output</div>
<textarea name="sample_out" class="panel-body"
style="width:100%" rows="20">{{ problem.sample_out }}</textarea>
</div>
</div>
</form>
<div class="tab-pane" id="tag">
{% include "problem/editTab/tag.html" with pid=problem.pk %}
</div>
<div class="tab-pane" id="testcase">
{% include "problem/editTab/testcase.html" with pid=problem.pk %}
</div>
</div>
</div>
</div>
<script src="{% static 'problem/js/edit.js' %}"></script>
</body>
{% endblock %}
| drowsy810301/NTHUOJ_web | problem/templates/problem/edit.html | HTML | mit | 3,000 |
package org.knowm.xchange.dsx.dto.trade;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
import org.knowm.xchange.dsx.dto.DSXReturn;
/** @author Mikhail Wall */
public class DSXOrderHistoryReturn extends DSXReturn<Map<Long, DSXOrderHistoryResult>> {
public DSXOrderHistoryReturn(
@JsonProperty("success") boolean success,
@JsonProperty("return") Map<Long, DSXOrderHistoryResult> value,
@JsonProperty("error") String error) {
super(success, value, error);
}
}
| chrisrico/XChange | xchange-dsx/src/main/java/org/knowm/xchange/dsx/dto/trade/DSXOrderHistoryReturn.java | Java | mit | 517 |
<?php
namespace Sabre\CardDAV;
use Sabre\HTTP;
use Sabre\DAV;
require_once 'Sabre/HTTP/ResponseMock.php';
class MultiGetTest extends AbstractPluginTest {
function testMultiGet() {
$request = HTTP\Sapi::createFromServerArray([
'REQUEST_METHOD' => 'REPORT',
'REQUEST_URI' => '/addressbooks/user1/book1',
]);
$request->setBody(
'<?xml version="1.0"?>
<c:addressbook-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
<d:prop>
<d:getetag />
<c:address-data />
</d:prop>
<d:href>/addressbooks/user1/book1/card1</d:href>
</c:addressbook-multiget>'
);
$response = new HTTP\ResponseMock();
$this->server->httpRequest = $request;
$this->server->httpResponse = $response;
$this->server->exec();
$this->assertEquals(207, $response->status, 'Incorrect status code. Full response body:' . $response->body);
// using the client for parsing
$client = new DAV\Client(['baseUri' => '/']);
$result = $client->parseMultiStatus($response->body);
$this->assertEquals([
'/addressbooks/user1/book1/card1' => [
200 => [
'{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"',
'{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD",
]
]
], $result);
}
function testMultiGetVCard4() {
$request = HTTP\Sapi::createFromServerArray([
'REQUEST_METHOD' => 'REPORT',
'REQUEST_URI' => '/addressbooks/user1/book1',
]);
$request->setBody(
'<?xml version="1.0"?>
<c:addressbook-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
<d:prop>
<d:getetag />
<c:address-data content-type="text/vcard" version="4.0" />
</d:prop>
<d:href>/addressbooks/user1/book1/card1</d:href>
</c:addressbook-multiget>'
);
$response = new HTTP\ResponseMock();
$this->server->httpRequest = $request;
$this->server->httpResponse = $response;
$this->server->exec();
$this->assertEquals(207, $response->status, 'Incorrect status code. Full response body:' . $response->body);
// using the client for parsing
$client = new DAV\Client(['baseUri' => '/']);
$result = $client->parseMultiStatus($response->body);
$prodId = "PRODID:-//Sabre//Sabre VObject " . \Sabre\VObject\Version::VERSION . "//EN";
$this->assertEquals([
'/addressbooks/user1/book1/card1' => [
200 => [
'{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"',
'{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\r\nVERSION:4.0\r\n$prodId\r\nUID:12345\r\nEND:VCARD\r\n",
]
]
], $result);
}
}
| wave72/hubzilla-dev | vendor/sabre/dav/tests/Sabre/CardDAV/MultiGetTest.php | PHP | mit | 3,074 |
<?php
namespace Kunstmaan\NodeBundle\Twig;
use Kunstmaan\NodeBundle\Helper\URLHelper;
class UrlReplaceTwigExtension extends \Twig_Extension
{
/**
* @var URLHelper
*/
private $urlHelper;
/**
* @param URLHelper $urlHelper
*/
public function __construct(URLHelper $urlHelper)
{
$this->urlHelper = $urlHelper;
}
/**
* @return array
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('replace_url', array($this, 'replaceUrl'))
);
}
public function replaceUrl($text)
{
return $this->urlHelper->replaceUrl($text);
}
}
| webtown-php/KunstmaanBundlesCMS | src/Kunstmaan/NodeBundle/Twig/UrlReplaceTwigExtension.php | PHP | mit | 664 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Diagnostics.Tests
{
public partial class FileVersionInfoTest
{
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void NonRegularFile_Throws()
{
string pipePath = GetTestFilePath();
Assert.Equal(0, mkfifo(pipePath, 0));
Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(pipePath));
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void Symlink_ValidFile_Succeeds()
{
string filePath = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName);
string linkPath = GetTestFilePath();
Assert.Equal(0, symlink(filePath, linkPath));
// Assembly1.dll
VerifyVersionInfo(linkPath, new MyFVI()
{
Comments = "Have you played a Contoso amusement device today?",
CompanyName = "The name of the company.",
FileBuildPart = 2,
FileDescription = "My File",
FileMajorPart = 4,
FileMinorPart = 3,
FileName = linkPath,
FilePrivatePart = 1,
FileVersion = "4.3.2.1",
InternalName = Path.GetFileName(linkPath),
IsDebug = false,
IsPatched = false,
IsPrivateBuild = false,
IsPreRelease = false,
IsSpecialBuild = false,
Language = GetFileVersionLanguage(0x0000),
Language2 = null,
LegalCopyright = "Copyright, you betcha!",
LegalTrademarks = "TM",
OriginalFilename = Path.GetFileName(linkPath),
PrivateBuild = "",
ProductBuildPart = 3,
ProductMajorPart = 1,
ProductMinorPart = 2,
ProductName = "The greatest product EVER",
ProductPrivatePart = 0,
ProductVersion = "1.2.3-beta.4",
SpecialBuild = "",
});
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void Symlink_InvalidFile_Throws()
{
string filePath = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName);
string linkPath = GetTestFilePath();
Assert.Equal(0, symlink(filePath, linkPath));
File.Delete(filePath);
Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(linkPath));
}
private static string GetFileVersionLanguage(uint langid) => "Language Neutral";
[DllImport("libc", SetLastError = true)]
private static extern int mkfifo(string path, int mode);
[DllImport("libc", SetLastError = true)]
private static extern int symlink(string target, string linkpath);
}
}
| Petermarcu/corefx | src/System.Diagnostics.FileVersionInfo/tests/System.Diagnostics.FileVersionInfo.Tests/FileVersionInfoTest.Unix.cs | C# | mit | 3,188 |
/* libunwind - a platform-independent unwind library
Copyright (C) 2008 CodeSourcery
Copyright 2011 Linaro Limited
This file is part of libunwind.
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 "unwind_i.h"
#include "offsets.h"
#include "ex_tables.h"
#include <signal.h>
#define arm_exidx_step UNW_OBJ(arm_exidx_step)
static inline int
arm_exidx_step (struct cursor *c)
{
unw_word_t old_ip, old_cfa;
uint8_t buf[32];
int ret;
old_ip = c->dwarf.ip;
old_cfa = c->dwarf.cfa;
/* mark PC unsaved */
c->dwarf.loc[UNW_ARM_R15] = DWARF_NULL_LOC;
if ((ret = tdep_find_proc_info (&c->dwarf, c->dwarf.ip, 1)) < 0)
return ret;
if (c->dwarf.pi.format != UNW_INFO_FORMAT_ARM_EXIDX)
return -UNW_ENOINFO;
ret = arm_exidx_extract (&c->dwarf, buf);
if (ret == -UNW_ESTOPUNWIND)
return 0;
else if (ret < 0)
return ret;
ret = arm_exidx_decode (buf, ret, &c->dwarf);
if (ret < 0)
return ret;
if (c->dwarf.ip == old_ip && c->dwarf.cfa == old_cfa)
{
Dprintf ("%s: ip and cfa unchanged; stopping here (ip=0x%lx)\n",
__FUNCTION__, (long) c->dwarf.ip);
return -UNW_EBADFRAME;
}
return (c->dwarf.ip == 0) ? 0 : 1;
}
PROTECTED int
unw_handle_signal_frame (unw_cursor_t *cursor)
{
struct cursor *c = (struct cursor *) cursor;
int ret;
unw_word_t sc_addr, sp, sp_addr = c->dwarf.cfa;
struct dwarf_loc sp_loc = DWARF_LOC (sp_addr, 0);
if ((ret = dwarf_get (&c->dwarf, sp_loc, &sp)) < 0)
return -UNW_EUNSPEC;
/* Obtain signal frame type (non-RT or RT). */
ret = unw_is_signal_frame (cursor);
/* Save the SP and PC to be able to return execution at this point
later in time (unw_resume). */
c->sigcontext_sp = c->dwarf.cfa;
c->sigcontext_pc = c->dwarf.ip;
/* Since kernel version 2.6.18 the non-RT signal frame starts with a
ucontext while the RT signal frame starts with a siginfo, followed
by a sigframe whose first element is an ucontext.
Prior 2.6.18 the non-RT signal frame starts with a sigcontext while
the RT signal frame starts with two pointers followed by a siginfo
and an ucontext. The first pointer points to the start of the siginfo
structure and the second one to the ucontext structure. */
if (ret == 1)
{
/* Handle non-RT signal frames. Check if the first word on the stack
is the magic number. */
if (sp == 0x5ac3c35a)
{
c->sigcontext_format = ARM_SCF_LINUX_SIGFRAME;
sc_addr = sp_addr + LINUX_UC_MCONTEXT_OFF;
}
else
{
c->sigcontext_format = ARM_SCF_LINUX_OLD_SIGFRAME;
sc_addr = sp_addr;
}
c->sigcontext_addr = sp_addr;
}
else if (ret == 2)
{
/* Handle RT signal frames. Check if the first word on the stack is a
pointer to the siginfo structure. */
if (sp == sp_addr + 8)
{
c->sigcontext_format = ARM_SCF_LINUX_OLD_RT_SIGFRAME;
c->sigcontext_addr = sp_addr + 8 + sizeof (siginfo_t);
}
else
{
c->sigcontext_format = ARM_SCF_LINUX_RT_SIGFRAME;
c->sigcontext_addr = sp_addr + sizeof (siginfo_t);
}
sc_addr = c->sigcontext_addr + LINUX_UC_MCONTEXT_OFF;
}
else
return -UNW_EUNSPEC;
/* Update the dwarf cursor.
Set the location of the registers to the corresponding addresses of the
uc_mcontext / sigcontext structure contents. */
c->dwarf.loc[UNW_ARM_R0] = DWARF_LOC (sc_addr + LINUX_SC_R0_OFF, 0);
c->dwarf.loc[UNW_ARM_R1] = DWARF_LOC (sc_addr + LINUX_SC_R1_OFF, 0);
c->dwarf.loc[UNW_ARM_R2] = DWARF_LOC (sc_addr + LINUX_SC_R2_OFF, 0);
c->dwarf.loc[UNW_ARM_R3] = DWARF_LOC (sc_addr + LINUX_SC_R3_OFF, 0);
c->dwarf.loc[UNW_ARM_R4] = DWARF_LOC (sc_addr + LINUX_SC_R4_OFF, 0);
c->dwarf.loc[UNW_ARM_R5] = DWARF_LOC (sc_addr + LINUX_SC_R5_OFF, 0);
c->dwarf.loc[UNW_ARM_R6] = DWARF_LOC (sc_addr + LINUX_SC_R6_OFF, 0);
c->dwarf.loc[UNW_ARM_R7] = DWARF_LOC (sc_addr + LINUX_SC_R7_OFF, 0);
c->dwarf.loc[UNW_ARM_R8] = DWARF_LOC (sc_addr + LINUX_SC_R8_OFF, 0);
c->dwarf.loc[UNW_ARM_R9] = DWARF_LOC (sc_addr + LINUX_SC_R9_OFF, 0);
c->dwarf.loc[UNW_ARM_R10] = DWARF_LOC (sc_addr + LINUX_SC_R10_OFF, 0);
c->dwarf.loc[UNW_ARM_R11] = DWARF_LOC (sc_addr + LINUX_SC_FP_OFF, 0);
c->dwarf.loc[UNW_ARM_R12] = DWARF_LOC (sc_addr + LINUX_SC_IP_OFF, 0);
c->dwarf.loc[UNW_ARM_R13] = DWARF_LOC (sc_addr + LINUX_SC_SP_OFF, 0);
c->dwarf.loc[UNW_ARM_R14] = DWARF_LOC (sc_addr + LINUX_SC_LR_OFF, 0);
c->dwarf.loc[UNW_ARM_R15] = DWARF_LOC (sc_addr + LINUX_SC_PC_OFF, 0);
/* Set SP/CFA and PC/IP. */
dwarf_get (&c->dwarf, c->dwarf.loc[UNW_ARM_R13], &c->dwarf.cfa);
dwarf_get (&c->dwarf, c->dwarf.loc[UNW_ARM_R15], &c->dwarf.ip);
return 1;
}
PROTECTED int
unw_step (unw_cursor_t *cursor)
{
struct cursor *c = (struct cursor *) cursor;
int ret = -UNW_EUNSPEC;
Debug (1, "(cursor=%p)\n", c);
/* Check if this is a signal frame. */
if (unw_is_signal_frame (cursor))
return unw_handle_signal_frame (cursor);
#ifdef CONFIG_DEBUG_FRAME
/* First, try DWARF-based unwinding. */
if (UNW_TRY_METHOD(UNW_ARM_METHOD_DWARF))
{
ret = dwarf_step (&c->dwarf);
Debug(1, "dwarf_step()=%d\n", ret);
if (likely (ret > 0))
return 1;
else if (unlikely (ret == -UNW_ESTOPUNWIND))
return ret;
if (ret < 0 && ret != -UNW_ENOINFO)
{
Debug (2, "returning %d\n", ret);
return ret;
}
}
#endif /* CONFIG_DEBUG_FRAME */
/* Next, try extbl-based unwinding. */
if (UNW_TRY_METHOD (UNW_ARM_METHOD_EXIDX))
{
ret = arm_exidx_step (c);
if (ret > 0)
return 1;
if (ret == -UNW_ESTOPUNWIND || ret == 0)
return ret;
}
/* Fall back on APCS frame parsing.
Note: This won't work in case the ARM EABI is used. */
if (unlikely (ret < 0))
{
if (UNW_TRY_METHOD(UNW_ARM_METHOD_FRAME))
{
ret = UNW_ESUCCESS;
/* DWARF unwinding failed, try to follow APCS/optimized APCS frame chain */
unw_word_t instr, i;
Debug (13, "dwarf_step() failed (ret=%d), trying frame-chain\n", ret);
dwarf_loc_t ip_loc, fp_loc;
unw_word_t frame;
/* Mark all registers unsaved, since we don't know where
they are saved (if at all), except for the EBP and
EIP. */
if (dwarf_get(&c->dwarf, c->dwarf.loc[UNW_ARM_R11], &frame) < 0)
{
return 0;
}
for (i = 0; i < DWARF_NUM_PRESERVED_REGS; ++i) {
c->dwarf.loc[i] = DWARF_NULL_LOC;
}
if (frame)
{
if (dwarf_get(&c->dwarf, DWARF_LOC(frame, 0), &instr) < 0)
{
return 0;
}
instr -= 8;
if (dwarf_get(&c->dwarf, DWARF_LOC(instr, 0), &instr) < 0)
{
return 0;
}
if ((instr & 0xFFFFD800) == 0xE92DD800)
{
/* Standard APCS frame. */
ip_loc = DWARF_LOC(frame - 4, 0);
fp_loc = DWARF_LOC(frame - 12, 0);
}
else
{
/* Codesourcery optimized normal frame. */
ip_loc = DWARF_LOC(frame, 0);
fp_loc = DWARF_LOC(frame - 4, 0);
}
if (dwarf_get(&c->dwarf, ip_loc, &c->dwarf.ip) < 0)
{
return 0;
}
c->dwarf.loc[UNW_ARM_R12] = ip_loc;
c->dwarf.loc[UNW_ARM_R11] = fp_loc;
Debug(15, "ip=%lx\n", c->dwarf.ip);
}
else
{
ret = -UNW_ENOINFO;
}
}
}
return ret == -UNW_ENOINFO ? 0 : 1;
}
| adsharma/libunwind | src/arm/Gstep.c | C | mit | 8,679 |
#!/bin/bash
FN="pd.atdschip.tiling_0.32.0.tar.gz"
URLS=(
"https://bioconductor.org/packages/3.14/data/experiment/src/contrib/pd.atdschip.tiling_0.32.0.tar.gz"
"https://bioarchive.galaxyproject.org/pd.atdschip.tiling_0.32.0.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-pd.atdschip.tiling/bioconductor-pd.atdschip.tiling_0.32.0_src_all.tar.gz"
)
MD5="cd9a08a95fb9ad01e250e36818314959"
# Use a staging area in the conda dir rather than temp dirs, both to avoid
# permission issues as well as to have things downloaded in a predictable
# manner.
STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM
mkdir -p $STAGING
TARBALL=$STAGING/$FN
SUCCESS=0
for URL in ${URLS[@]}; do
curl $URL > $TARBALL
[[ $? == 0 ]] || continue
# Platform-specific md5sum checks.
if [[ $(uname -s) == "Linux" ]]; then
if md5sum -c <<<"$MD5 $TARBALL"; then
SUCCESS=1
break
fi
else if [[ $(uname -s) == "Darwin" ]]; then
if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then
SUCCESS=1
break
fi
fi
fi
done
if [[ $SUCCESS != 1 ]]; then
echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:"
printf '%s\n' "${URLS[@]}"
exit 1
fi
# Install and clean up
R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL
rm $TARBALL
rmdir $STAGING
| cokelaer/bioconda-recipes | recipes/bioconductor-pd.atdschip.tiling/post-link.sh | Shell | mit | 1,342 |
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../../../../config/environment")
require 'test_help'
| davec/radiant-events-calendar-extension | vendor/plugins/simple_time_select/test/test_helper.rb | Ruby | mit | 131 |
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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.
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
AccountKit application settings.
*/
@interface AKFSettings : NSObject
/**
Get the Account Kit Client Token used by the SDK.
If not explicitly set, the default will be read from the application's plist (AccountKitClientToken).
*/
+ (NSString *)clientToken;
/**
Set the Account Kit Client Token used by the SDK.
- Parameter clientToken: The Account Kit Client Token to be used by the SDK.
*/
+ (void)setClientToken:(NSString *)clientToken;
@end
NS_ASSUME_NONNULL_END
| alborghette/weather-app | weather/Frameworks/AccountKit.framework/Headers/AKFSettings.h | C | mit | 1,641 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Protocols.TestTools.StackSdk.Messages.Marshaling
{
/// <summary>
/// Token
/// </summary>
public class Token : IToken
{
private string text;
private TokenType type;
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Token type</param>
public Token(TokenType type)
{
this.type = type;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Token type</param>
/// <param name="text">Token text</param>
public Token(TokenType type, string text)
{
this.type = type;
this.text = text;
}
/// <summary>
/// Token text
/// </summary>
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
/// <summary>
/// Token type
/// </summary>
public virtual TokenType Type
{
get
{
return type;
}
set
{
this.type = value;
}
}
}
}
| dongruiqing/WindowsProtocolTestSuites | ProtoSDK/Messages/messagecommon/Token.cs | C# | mit | 1,525 |
#include "wrapper_common.h"
#include "cblas.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
Capability is supported if >0
Actual number can be increased over time to indicate
extensions/revisions (that do not break compatibility)
*/
DLLEXPORT int query_capability(const int capability)
{
switch (capability)
{
// SANITY CHECKS
case 0: return 0;
case 1: return -1;
// PLATFORM
case 8:
#ifdef _M_IX86
return 1;
#else
return 0;
#endif
case 9:
#ifdef _M_X64
return 1;
#else
return 0;
#endif
case 10:
#ifdef _M_IA64
return 1;
#else
return 0;
#endif
// COMMON/SHARED
case 64: return 1; // revision
case 66: return 1; // threading control
// LINEAR ALGEBRA
case 128: return 1; // basic dense linear algebra (major - breaking)
case 129: return 0; // basic dense linear algebra (minor - non-breaking)
default: return 0; // unknown or not supported
}
}
DLLEXPORT void set_max_threads(const blasint num_threads)
{
openblas_set_num_threads(num_threads);
}
DLLEXPORT char* get_build_config()
{
return openblas_get_config();
}
DLLEXPORT char* get_cpu_core()
{
return openblas_get_corename();
}
DLLEXPORT int get_parallel_type()
{
return openblas_get_parallel();
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
| albertp007/mathnet-numerics | src/NativeProviders/OpenBLAS/capabilities.cpp | C++ | mit | 1,308 |
'use strict';
// Load modules
const Http = require('http');
const Stream = require('stream');
// Declare internals
const internals = {};
exports = module.exports = class Response extends Http.ServerResponse {
constructor(req, onEnd) {
super({ method: req.method, httpVersionMajor: 1, httpVersionMinor: 1 });
this._shot = { headers: null, trailers: {}, payloadChunks: [] };
this._headers = {}; // This forces node@8 to always render the headers
this.assignSocket(internals.nullSocket());
this.once('finish', () => {
const res = internals.payload(this);
res.raw.req = req;
process.nextTick(() => onEnd(res));
});
}
writeHead() {
const result = super.writeHead.apply(this, arguments);
this._shot.headers = Object.assign({}, this._headers); // Should be .getHeaders() since node v7.7
// Add raw headers
['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => {
const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n');
const field = this._header.match(regex);
if (field) {
this._shot.headers[name.toLowerCase()] = field[1];
}
});
return result;
}
write(data, encoding, callback) {
super.write(data, encoding, callback);
this._shot.payloadChunks.push(new Buffer(data, encoding));
return true; // Write always returns false when disconnected
}
end(data, encoding, callback) {
if (data) {
this.write(data, encoding);
}
super.end(callback);
this.emit('finish');
}
destroy() {
}
addTrailers(trailers) {
for (const key in trailers) {
this._shot.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim();
}
}
};
internals.payload = function (response) {
// Prepare response object
const res = {
raw: {
res: response
},
headers: response._shot.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
trailers: {}
};
// Prepare payload and trailers
const rawBuffer = Buffer.concat(response._shot.payloadChunks);
res.rawPayload = rawBuffer;
res.payload = rawBuffer.toString();
res.trailers = response._shot.trailers;
return res;
};
// Throws away all written data to prevent response from buffering payload
internals.nullSocket = function () {
return new Stream.Writable({
write(chunk, encoding, callback) {
setImmediate(callback);
}
});
};
| shikun2014010800/manga | web/backend/node_modules/shot/lib/response.js | JavaScript | mit | 2,749 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Request represents an HTTP request.
*
* The methods dealing with URL accept / return a raw path (% encoded):
* * getBasePath
* * getBaseUrl
* * getPathInfo
* * getRequestUri
* * getUri
* * getUriForPath
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @api
*/
class Request
{
const HEADER_CLIENT_IP = 'client_ip';
const HEADER_CLIENT_HOST = 'client_host';
const HEADER_CLIENT_PROTO = 'client_proto';
const HEADER_CLIENT_PORT = 'client_port';
const METHOD_HEAD = 'HEAD';
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_PURGE = 'PURGE';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_TRACE = 'TRACE';
const METHOD_CONNECT = 'CONNECT';
protected static $trustedProxies = array();
/**
* @var string[]
*/
protected static $trustedHostPatterns = array();
/**
* @var string[]
*/
protected static $trustedHosts = array();
/**
* Names for headers that can be trusted when
* using trusted proxies.
*
* The default names are non-standard, but widely used
* by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
*/
protected static $trustedHeaders = array(
self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
);
protected static $httpMethodParameterOverride = false;
/**
* Custom parameters.
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $attributes;
/**
* Request body parameters ($_POST).
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $request;
/**
* Query string parameters ($_GET).
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $query;
/**
* Server and execution environment parameters ($_SERVER).
*
* @var \Symfony\Component\HttpFoundation\ServerBag
*
* @api
*/
public $server;
/**
* Uploaded files ($_FILES).
*
* @var \Symfony\Component\HttpFoundation\FileBag
*
* @api
*/
public $files;
/**
* Cookies ($_COOKIE).
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $cookies;
/**
* Headers (taken from the $_SERVER).
*
* @var \Symfony\Component\HttpFoundation\HeaderBag
*
* @api
*/
public $headers;
/**
* @var string
*/
protected $content;
/**
* @var array
*/
protected $languages;
/**
* @var array
*/
protected $charsets;
/**
* @var array
*/
protected $encodings;
/**
* @var array
*/
protected $acceptableContentTypes;
/**
* @var string
*/
protected $pathInfo;
/**
* @var string
*/
protected $requestUri;
/**
* @var string
*/
protected $baseUrl;
/**
* @var string
*/
protected $basePath;
/**
* @var string
*/
protected $method;
/**
* @var string
*/
protected $format;
/**
* @var \Symfony\Component\HttpFoundation\Session\SessionInterface
*/
protected $session;
/**
* @var string
*/
protected $locale;
/**
* @var string
*/
protected $defaultLocale = 'en';
/**
* @var array
*/
protected static $formats;
protected static $requestFactory;
/**
* Constructor.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string $content The raw body data
*
* @api
*/
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}
/**
* Sets the parameters for this request.
*
* This method also re-initializes all properties.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string $content The raw body data
*
* @api
*/
public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->request = new ParameterBag($request);
$this->query = new ParameterBag($query);
$this->attributes = new ParameterBag($attributes);
$this->cookies = new ParameterBag($cookies);
$this->files = new FileBag($files);
$this->server = new ServerBag($server);
$this->headers = new HeaderBag($this->server->getHeaders());
$this->content = $content;
$this->languages = null;
$this->charsets = null;
$this->encodings = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
}
/**
* Creates a new request with values from PHP's super globals.
*
* @return Request A new request
*
* @api
*/
public static function createFromGlobals()
{
// With the php's bug #66606, the php's built-in web server
// stores the Content-Type and Content-Length header values in
// HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields.
$server = $_SERVER;
if ('cli-server' === php_sapi_name()) {
if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) {
$server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH'];
}
if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) {
$server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE'];
}
}
$request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server);
if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
&& in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
) {
parse_str($request->getContent(), $data);
$request->request = new ParameterBag($data);
}
return $request;
}
/**
* Creates a Request based on a given URI and configuration.
*
* The information contained in the URI always take precedence
* over the other information (server and parameters).
*
* @param string $uri The URI
* @param string $method The HTTP method
* @param array $parameters The query (GET) or request (POST) parameters
* @param array $cookies The request cookies ($_COOKIE)
* @param array $files The request files ($_FILES)
* @param array $server The server parameters ($_SERVER)
* @param string $content The raw body data
*
* @return Request A Request instance
*
* @api
*/
public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
{
$server = array_replace(array(
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'HTTP_HOST' => 'localhost',
'HTTP_USER_AGENT' => 'Symfony/2.X',
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'REMOTE_ADDR' => '127.0.0.1',
'SCRIPT_NAME' => '',
'SCRIPT_FILENAME' => '',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_TIME' => time(),
), $server);
$server['PATH_INFO'] = '';
$server['REQUEST_METHOD'] = strtoupper($method);
$components = parse_url($uri);
if (isset($components['host'])) {
$server['SERVER_NAME'] = $components['host'];
$server['HTTP_HOST'] = $components['host'];
}
if (isset($components['scheme'])) {
if ('https' === $components['scheme']) {
$server['HTTPS'] = 'on';
$server['SERVER_PORT'] = 443;
} else {
unset($server['HTTPS']);
$server['SERVER_PORT'] = 80;
}
}
if (isset($components['port'])) {
$server['SERVER_PORT'] = $components['port'];
$server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port'];
}
if (isset($components['user'])) {
$server['PHP_AUTH_USER'] = $components['user'];
}
if (isset($components['pass'])) {
$server['PHP_AUTH_PW'] = $components['pass'];
}
if (!isset($components['path'])) {
$components['path'] = '/';
}
switch (strtoupper($method)) {
case 'POST':
case 'PUT':
case 'DELETE':
if (!isset($server['CONTENT_TYPE'])) {
$server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
}
// no break
case 'PATCH':
$request = $parameters;
$query = array();
break;
default:
$request = array();
$query = $parameters;
break;
}
$queryString = '';
if (isset($components['query'])) {
parse_str(html_entity_decode($components['query']), $qs);
if ($query) {
$query = array_replace($qs, $query);
$queryString = http_build_query($query, '', '&');
} else {
$query = $qs;
$queryString = $components['query'];
}
} elseif ($query) {
$queryString = http_build_query($query, '', '&');
}
$server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
$server['QUERY_STRING'] = $queryString;
return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content);
}
/**
* Sets a callable able to create a Request instance.
*
* This is mainly useful when you need to override the Request class
* to keep BC with an existing system. It should not be used for any
* other purpose.
*
* @param callable|null $callable A PHP callable
*/
public static function setFactory($callable)
{
self::$requestFactory = $callable;
}
/**
* Clones a request and overrides some of its parameters.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
*
* @return Request The duplicated request
*
* @api
*/
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
{
$dup = clone $this;
if ($query !== null) {
$dup->query = new ParameterBag($query);
}
if ($request !== null) {
$dup->request = new ParameterBag($request);
}
if ($attributes !== null) {
$dup->attributes = new ParameterBag($attributes);
}
if ($cookies !== null) {
$dup->cookies = new ParameterBag($cookies);
}
if ($files !== null) {
$dup->files = new FileBag($files);
}
if ($server !== null) {
$dup->server = new ServerBag($server);
$dup->headers = new HeaderBag($dup->server->getHeaders());
}
$dup->languages = null;
$dup->charsets = null;
$dup->encodings = null;
$dup->acceptableContentTypes = null;
$dup->pathInfo = null;
$dup->requestUri = null;
$dup->baseUrl = null;
$dup->basePath = null;
$dup->method = null;
$dup->format = null;
if (!$dup->get('_format') && $this->get('_format')) {
$dup->attributes->set('_format', $this->get('_format'));
}
if (!$dup->getRequestFormat(null)) {
$dup->setRequestFormat($this->getRequestFormat(null));
}
return $dup;
}
/**
* Clones the current request.
*
* Note that the session is not cloned as duplicated requests
* are most of the time sub-requests of the main one.
*/
public function __clone()
{
$this->query = clone $this->query;
$this->request = clone $this->request;
$this->attributes = clone $this->attributes;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Returns the request as a string.
*
* @return string The request
*/
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers."\r\n".
$content;
}
/**
* Overrides the PHP global variables according to this request instance.
*
* It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
* $_FILES is never overridden, see rfc1867
*
* @api
*/
public function overrideGlobals()
{
$this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null, '&')));
$_GET = $this->query->all();
$_POST = $this->request->all();
$_SERVER = $this->server->all();
$_COOKIE = $this->cookies->all();
foreach ($this->headers->all() as $key => $value) {
$key = strtoupper(str_replace('-', '_', $key));
if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
$_SERVER[$key] = implode(', ', $value);
} else {
$_SERVER['HTTP_'.$key] = implode(', ', $value);
}
}
$request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE);
$requestOrder = ini_get('request_order') ?: ini_get('variables_order');
$requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
$_REQUEST = array();
foreach (str_split($requestOrder) as $order) {
$_REQUEST = array_merge($_REQUEST, $request[$order]);
}
}
/**
* Sets a list of trusted proxies.
*
* You should only list the reverse proxies that you manage directly.
*
* @param array $proxies A list of trusted proxies
*
* @api
*/
public static function setTrustedProxies(array $proxies)
{
self::$trustedProxies = $proxies;
}
/**
* Gets the list of trusted proxies.
*
* @return array An array of trusted proxies.
*/
public static function getTrustedProxies()
{
return self::$trustedProxies;
}
/**
* Sets a list of trusted host patterns.
*
* You should only list the hosts you manage using regexs.
*
* @param array $hostPatterns A list of trusted host patterns
*/
public static function setTrustedHosts(array $hostPatterns)
{
self::$trustedHostPatterns = array_map(function ($hostPattern) {
return sprintf('#%s#i', $hostPattern);
}, $hostPatterns);
// we need to reset trusted hosts on trusted host patterns change
self::$trustedHosts = array();
}
/**
* Gets the list of trusted host patterns.
*
* @return array An array of trusted host patterns.
*/
public static function getTrustedHosts()
{
return self::$trustedHostPatterns;
}
/**
* Sets the name for trusted headers.
*
* The following header keys are supported:
*
* * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp())
* * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost())
* * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort())
* * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure())
*
* Setting an empty value allows to disable the trusted header for the given key.
*
* @param string $key The header key
* @param string $value The header name
*
* @throws \InvalidArgumentException
*/
public static function setTrustedHeaderName($key, $value)
{
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
}
self::$trustedHeaders[$key] = $value;
}
/**
* Gets the trusted proxy header name.
*
* @param string $key The header key
*
* @return string The header name
*
* @throws \InvalidArgumentException
*/
public static function getTrustedHeaderName($key)
{
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key));
}
return self::$trustedHeaders[$key];
}
/**
* Normalizes a query string.
*
* It builds a normalized query string, where keys/value pairs are alphabetized,
* have consistent escaping and unneeded delimiters are removed.
*
* @param string $qs Query string
*
* @return string A normalized query string for the Request
*/
public static function normalizeQueryString($qs)
{
if ('' == $qs) {
return '';
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $param) {
if ('' === $param || '=' === $param[0]) {
// Ignore useless delimiters, e.g. "x=y&".
// Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
// PHP also does not include them when building _GET.
continue;
}
$keyValuePair = explode('=', $param, 2);
// GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
// PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
// RFC 3986 with rawurlencode.
$parts[] = isset($keyValuePair[1]) ?
rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
rawurlencode(urldecode($keyValuePair[0]));
$order[] = urldecode($keyValuePair[0]);
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
}
/**
* Enables support for the _method request parameter to determine the intended HTTP method.
*
* Be warned that enabling this feature might lead to CSRF issues in your code.
* Check that you are using CSRF tokens when required.
* If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
* and used to send a "PUT" or "DELETE" request via the _method request parameter.
* If these methods are not protected against CSRF, this presents a possible vulnerability.
*
* The HTTP method can only be overridden when the real HTTP method is POST.
*/
public static function enableHttpMethodParameterOverride()
{
self::$httpMethodParameterOverride = true;
}
/**
* Checks whether support for the _method request parameter is enabled.
*
* @return bool True when the _method request parameter is enabled, false otherwise
*/
public static function getHttpMethodParameterOverride()
{
return self::$httpMethodParameterOverride;
}
/**
* Gets a "parameter" value.
*
* This method is mainly useful for libraries that want to provide some flexibility.
*
* Order of precedence: GET, PATH, POST
*
* Avoid using this method in controllers:
*
* * slow
* * prefer to get from a "named" source
*
* It is better to explicitly get request parameters from the appropriate
* public property instead (query, attributes, request).
*
* @param string $key the key
* @param mixed $default the default value
* @param bool $deep is parameter deep in multidimensional array
*
* @return mixed
*/
public function get($key, $default = null, $deep = false)
{
if ($this !== $result = $this->query->get($key, $this, $deep)) {
return $result;
}
if ($this !== $result = $this->attributes->get($key, $this, $deep)) {
return $result;
}
if ($this !== $result = $this->request->get($key, $this, $deep)) {
return $result;
}
return $default;
}
/**
* Gets the Session.
*
* @return SessionInterface|null The session
*
* @api
*/
public function getSession()
{
return $this->session;
}
/**
* Whether the request contains a Session which was started in one of the
* previous requests.
*
* @return bool
*
* @api
*/
public function hasPreviousSession()
{
// the check for $this->session avoids malicious users trying to fake a session cookie with proper name
return $this->hasSession() && $this->cookies->has($this->session->getName());
}
/**
* Whether the request contains a Session object.
*
* This method does not give any information about the state of the session object,
* like whether the session is started or not. It is just a way to check if this Request
* is associated with a Session instance.
*
* @return bool true when the Request contains a Session object, false otherwise
*
* @api
*/
public function hasSession()
{
return null !== $this->session;
}
/**
* Sets the Session.
*
* @param SessionInterface $session The Session
*
* @api
*/
public function setSession(SessionInterface $session)
{
$this->session = $session;
}
/**
* Returns the client IP addresses.
*
* In the returned array the most trusted IP address is first, and the
* least trusted one last. The "real" client IP address is the last one,
* but this is also the least trusted one. Trusted proxies are stripped.
*
* Use this method carefully; you should use getClientIp() instead.
*
* @return array The client IP addresses
*
* @see getClientIp()
*/
public function getClientIps()
{
$ip = $this->server->get('REMOTE_ADDR');
if (!$this->isFromTrustedProxy()) {
return array($ip);
}
if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
return array($ip);
}
$clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
$clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
$ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies
// Eliminate all IPs from the forwarded IP chain which are trusted proxies
foreach ($clientIps as $key => $clientIp) {
// Remove port on IPv4 address (unfortunately, it does happen)
if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
$clientIps[$key] = $clientIp = $match[1];
}
if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
unset($clientIps[$key]);
}
}
// Now the IP chain contains only untrusted proxies and the client IP
return $clientIps ? array_reverse($clientIps) : array($ip);
}
/**
* Returns the client IP address.
*
* This method can read the client IP address from the "X-Forwarded-For" header
* when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
* header value is a comma+space separated list of IP addresses, the left-most
* being the original client, and each successive proxy that passed the request
* adding the IP address where it received the request from.
*
* If your reverse proxy uses a different header name than "X-Forwarded-For",
* ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with
* the "client-ip" key.
*
* @return string The client IP address
*
* @see getClientIps()
* @see http://en.wikipedia.org/wiki/X-Forwarded-For
*
* @api
*/
public function getClientIp()
{
$ipAddresses = $this->getClientIps();
return $ipAddresses[0];
}
/**
* Returns current script name.
*
* @return string
*
* @api
*/
public function getScriptName()
{
return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
}
/**
* Returns the path being requested relative to the executed script.
*
* The path info always starts with a /.
*
* Suppose this request is instantiated from /mysite on localhost:
*
* * http://localhost/mysite returns an empty string
* * http://localhost/mysite/about returns '/about'
* * http://localhost/mysite/enco%20ded returns '/enco%20ded'
* * http://localhost/mysite/about?var=1 returns '/about'
*
* @return string The raw path (i.e. not urldecoded)
*
* @api
*/
public function getPathInfo()
{
if (null === $this->pathInfo) {
$this->pathInfo = $this->preparePathInfo();
}
return $this->pathInfo;
}
/**
* Returns the root path from which this request is executed.
*
* Suppose that an index.php file instantiates this request object:
*
* * http://localhost/index.php returns an empty string
* * http://localhost/index.php/page returns an empty string
* * http://localhost/web/index.php returns '/web'
* * http://localhost/we%20b/index.php returns '/we%20b'
*
* @return string The raw path (i.e. not urldecoded)
*
* @api
*/
public function getBasePath()
{
if (null === $this->basePath) {
$this->basePath = $this->prepareBasePath();
}
return $this->basePath;
}
/**
* Returns the root URL from which this request is executed.
*
* The base URL never ends with a /.
*
* This is similar to getBasePath(), except that it also includes the
* script filename (e.g. index.php) if one exists.
*
* @return string The raw URL (i.e. not urldecoded)
*
* @api
*/
public function getBaseUrl()
{
if (null === $this->baseUrl) {
$this->baseUrl = $this->prepareBaseUrl();
}
return $this->baseUrl;
}
/**
* Gets the request's scheme.
*
* @return string
*
* @api
*/
public function getScheme()
{
return $this->isSecure() ? 'https' : 'http';
}
/**
* Returns the port on which the request is made.
*
* This method can read the client port from the "X-Forwarded-Port" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Port" header must contain the client port.
*
* If your reverse proxy uses a different header name than "X-Forwarded-Port",
* configure it via "setTrustedHeaderName()" with the "client-port" key.
*
* @return string
*
* @api
*/
public function getPort()
{
if ($this->isFromTrustedProxy()) {
if (self::$trustedHeaders[self::HEADER_CLIENT_PORT] && $port = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PORT])) {
return $port;
}
if (self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && 'https' === $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO], 'http')) {
return 443;
}
}
if ($host = $this->headers->get('HOST')) {
if ($host[0] === '[') {
$pos = strpos($host, ':', strrpos($host, ']'));
} else {
$pos = strrpos($host, ':');
}
if (false !== $pos) {
return (int) substr($host, $pos + 1);
}
return 'https' === $this->getScheme() ? 443 : 80;
}
return $this->server->get('SERVER_PORT');
}
/**
* Returns the user.
*
* @return string|null
*/
public function getUser()
{
return $this->headers->get('PHP_AUTH_USER');
}
/**
* Returns the password.
*
* @return string|null
*/
public function getPassword()
{
return $this->headers->get('PHP_AUTH_PW');
}
/**
* Gets the user info.
*
* @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server
*/
public function getUserInfo()
{
$userinfo = $this->getUser();
$pass = $this->getPassword();
if ('' != $pass) {
$userinfo .= ":$pass";
}
return $userinfo;
}
/**
* Returns the HTTP host being requested.
*
* The port name will be appended to the host if it's non-standard.
*
* @return string
*
* @api
*/
public function getHttpHost()
{
$scheme = $this->getScheme();
$port = $this->getPort();
if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
return $this->getHost();
}
return $this->getHost().':'.$port;
}
/**
* Returns the requested URI (path and query string).
*
* @return string The raw URI (i.e. not URI decoded)
*
* @api
*/
public function getRequestUri()
{
if (null === $this->requestUri) {
$this->requestUri = $this->prepareRequestUri();
}
return $this->requestUri;
}
/**
* Gets the scheme and HTTP host.
*
* If the URL was called with basic authentication, the user
* and the password are not added to the generated string.
*
* @return string The scheme and HTTP host
*/
public function getSchemeAndHttpHost()
{
return $this->getScheme().'://'.$this->getHttpHost();
}
/**
* Generates a normalized URI (URL) for the Request.
*
* @return string A normalized URI (URL) for the Request
*
* @see getQueryString()
*
* @api
*/
public function getUri()
{
if (null !== $qs = $this->getQueryString()) {
$qs = '?'.$qs;
}
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
}
/**
* Generates a normalized URI for the given path.
*
* @param string $path A path to use instead of the current one
*
* @return string The normalized URI for the path
*
* @api
*/
public function getUriForPath($path)
{
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
}
/**
* Generates the normalized query string for the Request.
*
* It builds a normalized query string, where keys/value pairs are alphabetized
* and have consistent escaping.
*
* @return string|null A normalized query string for the Request
*
* @api
*/
public function getQueryString()
{
$qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
return '' === $qs ? null : $qs;
}
/**
* Checks whether the request is secure or not.
*
* This method can read the client port from the "X-Forwarded-Proto" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
*
* If your reverse proxy uses a different header name than "X-Forwarded-Proto"
* ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with
* the "client-proto" key.
*
* @return bool
*
* @api
*/
public function isSecure()
{
if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) {
return in_array(strtolower(current(explode(',', $proto))), array('https', 'on', 'ssl', '1'));
}
$https = $this->server->get('HTTPS');
return !empty($https) && 'off' !== strtolower($https);
}
/**
* Returns the host name.
*
* This method can read the client port from the "X-Forwarded-Host" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Host" header must contain the client host name.
*
* If your reverse proxy uses a different header name than "X-Forwarded-Host",
* configure it via "setTrustedHeaderName()" with the "client-host" key.
*
* @return string
*
* @throws \UnexpectedValueException when the host name is invalid
*
* @api
*/
public function getHost()
{
if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
$elements = explode(',', $host);
$host = $elements[count($elements) - 1];
} elseif (!$host = $this->headers->get('HOST')) {
if (!$host = $this->server->get('SERVER_NAME')) {
$host = $this->server->get('SERVER_ADDR', '');
}
}
// trim and remove port number from host
// host is lowercase as per RFC 952/2181
$host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
// as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
// check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
// use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
}
if (count(self::$trustedHostPatterns) > 0) {
// to avoid host header injection attacks, you should provide a list of trusted host patterns
if (in_array($host, self::$trustedHosts)) {
return $host;
}
foreach (self::$trustedHostPatterns as $pattern) {
if (preg_match($pattern, $host)) {
self::$trustedHosts[] = $host;
return $host;
}
}
throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
}
return $host;
}
/**
* Sets the request method.
*
* @param string $method
*
* @api
*/
public function setMethod($method)
{
$this->method = null;
$this->server->set('REQUEST_METHOD', $method);
}
/**
* Gets the request "intended" method.
*
* If the X-HTTP-Method-Override header is set, and if the method is a POST,
* then it is used to determine the "real" intended HTTP method.
*
* The _method request parameter can also be used to determine the HTTP method,
* but only if enableHttpMethodParameterOverride() has been called.
*
* The method is always an uppercased string.
*
* @return string The request method
*
* @api
*
* @see getRealMethod()
*/
public function getMethod()
{
if (null === $this->method) {
$this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
if ('POST' === $this->method) {
if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
$this->method = strtoupper($method);
} elseif (self::$httpMethodParameterOverride) {
$this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
}
}
}
return $this->method;
}
/**
* Gets the "real" request method.
*
* @return string The request method
*
* @see getMethod()
*/
public function getRealMethod()
{
return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
}
/**
* Gets the mime type associated with the format.
*
* @param string $format The format
*
* @return string The associated mime type (null if not found)
*
* @api
*/
public function getMimeType($format)
{
if (null === static::$formats) {
static::initializeFormats();
}
return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
}
/**
* Gets the format associated with the mime type.
*
* @param string $mimeType The associated mime type
*
* @return string|null The format (null if not found)
*
* @api
*/
public function getFormat($mimeType)
{
if (false !== $pos = strpos($mimeType, ';')) {
$mimeType = substr($mimeType, 0, $pos);
}
if (null === static::$formats) {
static::initializeFormats();
}
foreach (static::$formats as $format => $mimeTypes) {
if (in_array($mimeType, (array) $mimeTypes)) {
return $format;
}
}
}
/**
* Associates a format with mime types.
*
* @param string $format The format
* @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
*
* @api
*/
public function setFormat($format, $mimeTypes)
{
if (null === static::$formats) {
static::initializeFormats();
}
static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
}
/**
* Gets the request format.
*
* Here is the process to determine the format:
*
* * format defined by the user (with setRequestFormat())
* * _format request parameter
* * $default
*
* @param string $default The default format
*
* @return string The request format
*
* @api
*/
public function getRequestFormat($default = 'html')
{
if (null === $this->format) {
$this->format = $this->get('_format', $default);
}
return $this->format;
}
/**
* Sets the request format.
*
* @param string $format The request format.
*
* @api
*/
public function setRequestFormat($format)
{
$this->format = $format;
}
/**
* Gets the format associated with the request.
*
* @return string|null The format (null if no content type is present)
*
* @api
*/
public function getContentType()
{
return $this->getFormat($this->headers->get('CONTENT_TYPE'));
}
/**
* Sets the default locale.
*
* @param string $locale
*
* @api
*/
public function setDefaultLocale($locale)
{
$this->defaultLocale = $locale;
if (null === $this->locale) {
$this->setPhpDefaultLocale($locale);
}
}
/**
* Get the default locale.
*
* @return string
*/
public function getDefaultLocale()
{
return $this->defaultLocale;
}
/**
* Sets the locale.
*
* @param string $locale
*
* @api
*/
public function setLocale($locale)
{
$this->setPhpDefaultLocale($this->locale = $locale);
}
/**
* Get the locale.
*
* @return string
*/
public function getLocale()
{
return null === $this->locale ? $this->defaultLocale : $this->locale;
}
/**
* Checks if the request method is of specified type.
*
* @param string $method Uppercase request method (GET, POST etc).
*
* @return bool
*/
public function isMethod($method)
{
return $this->getMethod() === strtoupper($method);
}
/**
* Checks whether the method is safe or not.
*
* @return bool
*
* @api
*/
public function isMethodSafe()
{
return in_array($this->getMethod(), array('GET', 'HEAD'));
}
/**
* Returns the request body content.
*
* @param bool $asResource If true, a resource will be returned
*
* @return string|resource The request body content or a resource to read the body stream.
*
* @throws \LogicException
*/
public function getContent($asResource = false)
{
if (PHP_VERSION_ID < 50600 && (false === $this->content || (true === $asResource && null !== $this->content))) {
throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
}
if (true === $asResource) {
$this->content = false;
return fopen('php://input', 'rb');
}
if (null === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
}
/**
* Gets the Etags.
*
* @return array The entity tags
*/
public function getETags()
{
return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
}
/**
* @return bool
*/
public function isNoCache()
{
return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
}
/**
* Returns the preferred language.
*
* @param array $locales An array of ordered available locales
*
* @return string|null The preferred locale
*
* @api
*/
public function getPreferredLanguage(array $locales = null)
{
$preferredLanguages = $this->getLanguages();
if (empty($locales)) {
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
}
if (!$preferredLanguages) {
return $locales[0];
}
$extendedPreferredLanguages = array();
foreach ($preferredLanguages as $language) {
$extendedPreferredLanguages[] = $language;
if (false !== $position = strpos($language, '_')) {
$superLanguage = substr($language, 0, $position);
if (!in_array($superLanguage, $preferredLanguages)) {
$extendedPreferredLanguages[] = $superLanguage;
}
}
}
$preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
}
/**
* Gets a list of languages acceptable by the client browser.
*
* @return array Languages ordered in the user browser preferences
*
* @api
*/
public function getLanguages()
{
if (null !== $this->languages) {
return $this->languages;
}
$languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
$this->languages = array();
foreach ($languages as $lang => $acceptHeaderItem) {
if (false !== strpos($lang, '-')) {
$codes = explode('-', $lang);
if ('i' === $codes[0]) {
// Language not listed in ISO 639 that are not variants
// of any listed language, which can be registered with the
// i-prefix, such as i-cherokee
if (count($codes) > 1) {
$lang = $codes[1];
}
} else {
for ($i = 0, $max = count($codes); $i < $max; ++$i) {
if ($i === 0) {
$lang = strtolower($codes[0]);
} else {
$lang .= '_'.strtoupper($codes[$i]);
}
}
}
}
$this->languages[] = $lang;
}
return $this->languages;
}
/**
* Gets a list of charsets acceptable by the client browser.
*
* @return array List of charsets in preferable order
*
* @api
*/
public function getCharsets()
{
if (null !== $this->charsets) {
return $this->charsets;
}
return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
}
/**
* Gets a list of encodings acceptable by the client browser.
*
* @return array List of encodings in preferable order
*/
public function getEncodings()
{
if (null !== $this->encodings) {
return $this->encodings;
}
return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
}
/**
* Gets a list of content types acceptable by the client browser.
*
* @return array List of content types in preferable order
*
* @api
*/
public function getAcceptableContentTypes()
{
if (null !== $this->acceptableContentTypes) {
return $this->acceptableContentTypes;
}
return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
}
/**
* Returns true if the request is a XMLHttpRequest.
*
* It works if your JavaScript library sets an X-Requested-With HTTP header.
* It is known to work with common JavaScript frameworks:
*
* @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool true if the request is an XMLHttpRequest, false otherwise
*
* @api
*/
public function isXmlHttpRequest()
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
/*
* The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
*
* Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
*
* Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
*/
protected function prepareRequestUri()
{
$requestUri = '';
if ($this->headers->has('X_ORIGINAL_URL')) {
// IIS with Microsoft Rewrite Module
$requestUri = $this->headers->get('X_ORIGINAL_URL');
$this->headers->remove('X_ORIGINAL_URL');
$this->server->remove('HTTP_X_ORIGINAL_URL');
$this->server->remove('UNENCODED_URL');
$this->server->remove('IIS_WasUrlRewritten');
} elseif ($this->headers->has('X_REWRITE_URL')) {
// IIS with ISAPI_Rewrite
$requestUri = $this->headers->get('X_REWRITE_URL');
$this->headers->remove('X_REWRITE_URL');
} elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
// IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
$requestUri = $this->server->get('UNENCODED_URL');
$this->server->remove('UNENCODED_URL');
$this->server->remove('IIS_WasUrlRewritten');
} elseif ($this->server->has('REQUEST_URI')) {
$requestUri = $this->server->get('REQUEST_URI');
// HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
$schemeAndHttpHost = $this->getSchemeAndHttpHost();
if (strpos($requestUri, $schemeAndHttpHost) === 0) {
$requestUri = substr($requestUri, strlen($schemeAndHttpHost));
}
} elseif ($this->server->has('ORIG_PATH_INFO')) {
// IIS 5.0, PHP as CGI
$requestUri = $this->server->get('ORIG_PATH_INFO');
if ('' != $this->server->get('QUERY_STRING')) {
$requestUri .= '?'.$this->server->get('QUERY_STRING');
}
$this->server->remove('ORIG_PATH_INFO');
}
// normalize the request URI to ease creating sub-requests from this request
$this->server->set('REQUEST_URI', $requestUri);
return $requestUri;
}
/**
* Prepares the base URL.
*
* @return string
*/
protected function prepareBaseUrl()
{
$filename = basename($this->server->get('SCRIPT_FILENAME'));
if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
$baseUrl = $this->server->get('SCRIPT_NAME');
} elseif (basename($this->server->get('PHP_SELF')) === $filename) {
$baseUrl = $this->server->get('PHP_SELF');
} elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
$baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
} else {
// Backtrack up the script_filename to find the portion matching
// php_self
$path = $this->server->get('PHP_SELF', '');
$file = $this->server->get('SCRIPT_FILENAME', '');
$segs = explode('/', trim($file, '/'));
$segs = array_reverse($segs);
$index = 0;
$last = count($segs);
$baseUrl = '';
do {
$seg = $segs[$index];
$baseUrl = '/'.$seg.$baseUrl;
++$index;
} while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
}
// Does the baseUrl have anything in common with the request_uri?
$requestUri = $this->getRequestUri();
if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
// full $baseUrl matches
return $prefix;
}
if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/').'/')) {
// directory portion of $baseUrl matches
return rtrim($prefix, '/');
}
$truncatedRequestUri = $requestUri;
if (false !== $pos = strpos($requestUri, '?')) {
$truncatedRequestUri = substr($requestUri, 0, $pos);
}
$basename = basename($baseUrl);
if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
// no match whatsoever; set it blank
return '';
}
// If using mod_rewrite or ISAPI_Rewrite strip the script filename
// out of baseUrl. $pos !== 0 makes sure it is not matching a value
// from PATH_INFO or QUERY_STRING
if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) {
$baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
}
return rtrim($baseUrl, '/');
}
/**
* Prepares the base path.
*
* @return string base path
*/
protected function prepareBasePath()
{
$filename = basename($this->server->get('SCRIPT_FILENAME'));
$baseUrl = $this->getBaseUrl();
if (empty($baseUrl)) {
return '';
}
if (basename($baseUrl) === $filename) {
$basePath = dirname($baseUrl);
} else {
$basePath = $baseUrl;
}
if ('\\' === DIRECTORY_SEPARATOR) {
$basePath = str_replace('\\', '/', $basePath);
}
return rtrim($basePath, '/');
}
/**
* Prepares the path info.
*
* @return string path info
*/
protected function preparePathInfo()
{
$baseUrl = $this->getBaseUrl();
if (null === ($requestUri = $this->getRequestUri())) {
return '/';
}
$pathInfo = '/';
// Remove the query string from REQUEST_URI
if ($pos = strpos($requestUri, '?')) {
$requestUri = substr($requestUri, 0, $pos);
}
if (null !== $baseUrl && false === $pathInfo = substr($requestUri, strlen($baseUrl))) {
// If substr() returns false then PATH_INFO is set to an empty string
return '/';
} elseif (null === $baseUrl) {
return $requestUri;
}
return (string) $pathInfo;
}
/**
* Initializes HTTP request formats.
*/
protected static function initializeFormats()
{
static::$formats = array(
'html' => array('text/html', 'application/xhtml+xml'),
'txt' => array('text/plain'),
'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
'css' => array('text/css'),
'json' => array('application/json', 'application/x-json'),
'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
'rdf' => array('application/rdf+xml'),
'atom' => array('application/atom+xml'),
'rss' => array('application/rss+xml'),
'form' => array('application/x-www-form-urlencoded'),
);
}
/**
* Sets the default PHP locale.
*
* @param string $locale
*/
private function setPhpDefaultLocale($locale)
{
// if either the class Locale doesn't exist, or an exception is thrown when
// setting the default locale, the intl module is not installed, and
// the call can be ignored:
try {
if (class_exists('Locale', false)) {
\Locale::setDefault($locale);
}
} catch (\Exception $e) {
}
}
/*
* Returns the prefix as encoded in the string when the string starts with
* the given prefix, false otherwise.
*
* @param string $string The urlencoded string
* @param string $prefix The prefix not encoded
*
* @return string|false The prefix as it is encoded in $string, or false
*/
private function getUrlencodedPrefix($string, $prefix)
{
if (0 !== strpos(rawurldecode($string), $prefix)) {
return false;
}
$len = strlen($prefix);
if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
return $match[0];
}
return false;
}
private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
if (self::$requestFactory) {
$request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
if (!$request instanceof Request) {
throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
}
return $request;
}
return new static($query, $request, $attributes, $cookies, $files, $server, $content);
}
private function isFromTrustedProxy()
{
return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
}
}
| thelastsoulja/Cpanet | vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Request.php | PHP | mit | 58,515 |
#if !defined(__mips_soft_float) && __mips >= 2
#include <math.h>
float sqrtf(float x)
{
float r;
__asm__("sqrt.s %0,%1" : "=f"(r) : "f"(x));
return r;
}
#else
#include "../sqrtf.c"
#endif
| heatd/Onyx | musl/src/math/mips/sqrtf.c | C | mit | 196 |
var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var os = require('os')
var win32 = os.platform() === 'win32'
var noop = function () {}
var echo = function (name) {
return name
}
var normalize = !win32 ? echo : function (name) {
return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}
var statAll = function (fs, stat, cwd, ignore, entries, sort) {
var queue = entries || ['.']
return function loop (callback) {
if (!queue.length) return callback()
var next = queue.shift()
var nextAbs = path.join(cwd, next)
stat(nextAbs, function (err, stat) {
if (err) return callback(err)
if (!stat.isDirectory()) return callback(null, next, stat)
fs.readdir(nextAbs, function (err, files) {
if (err) return callback(err)
if (sort) files.sort()
for (var i = 0; i < files.length; i++) {
if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
}
callback(null, next, stat)
})
})
}
}
var strip = function (map, level) {
return function (header) {
header.name = header.name.split('/').slice(level).join('/')
var linkname = header.linkname
if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
header.linkname = linkname.split('/').slice(level).join('/')
}
return map(header)
}
}
exports.pack = function (cwd, opts) {
if (!cwd) cwd = '.'
if (!opts) opts = {}
var xfs = opts.fs || fs
var ignore = opts.ignore || opts.filter || noop
var map = opts.map || noop
var mapStream = opts.mapStream || echo
var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
var strict = opts.strict !== false
var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
var pack = opts.pack || tar.pack()
var finish = opts.finish || noop
if (opts.strip) map = strip(map, opts.strip)
if (opts.readable) {
dmode |= parseInt(555, 8)
fmode |= parseInt(444, 8)
}
if (opts.writable) {
dmode |= parseInt(333, 8)
fmode |= parseInt(222, 8)
}
var onsymlink = function (filename, header) {
xfs.readlink(path.join(cwd, filename), function (err, linkname) {
if (err) return pack.destroy(err)
header.linkname = normalize(linkname)
pack.entry(header, onnextentry)
})
}
var onstat = function (err, filename, stat) {
if (err) return pack.destroy(err)
if (!filename) {
if (opts.finalize !== false) pack.finalize()
return finish(pack)
}
if (stat.isSocket()) return onnextentry() // tar does not support sockets...
var header = {
name: normalize(filename),
mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
mtime: stat.mtime,
size: stat.size,
type: 'file',
uid: stat.uid,
gid: stat.gid
}
if (stat.isDirectory()) {
header.size = 0
header.type = 'directory'
header = map(header) || header
return pack.entry(header, onnextentry)
}
if (stat.isSymbolicLink()) {
header.size = 0
header.type = 'symlink'
header = map(header) || header
return onsymlink(filename, header)
}
// TODO: add fifo etc...
header = map(header) || header
if (!stat.isFile()) {
if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
return onnextentry()
}
var entry = pack.entry(header, onnextentry)
if (!entry) return
var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)
rs.on('error', function (err) { // always forward errors on destroy
entry.destroy(err)
})
pump(rs, entry)
}
var onnextentry = function (err) {
if (err) return pack.destroy(err)
statNext(onstat)
}
onnextentry()
return pack
}
var head = function (list) {
return list.length ? list[list.length - 1] : null
}
var processGetuid = function () {
return process.getuid ? process.getuid() : -1
}
var processUmask = function () {
return process.umask ? process.umask() : 0
}
exports.extract = function (cwd, opts) {
if (!cwd) cwd = '.'
if (!opts) opts = {}
var xfs = opts.fs || fs
var ignore = opts.ignore || opts.filter || noop
var map = opts.map || noop
var mapStream = opts.mapStream || echo
var own = opts.chown !== false && !win32 && processGetuid() === 0
var extract = opts.extract || tar.extract()
var stack = []
var now = new Date()
var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
var strict = opts.strict !== false
if (opts.strip) map = strip(map, opts.strip)
if (opts.readable) {
dmode |= parseInt(555, 8)
fmode |= parseInt(444, 8)
}
if (opts.writable) {
dmode |= parseInt(333, 8)
fmode |= parseInt(222, 8)
}
var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
var top
while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
if (!top) return cb()
xfs.utimes(top[0], now, top[1], cb)
}
var utimes = function (name, header, cb) {
if (opts.utimes === false) return cb()
if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?
xfs.utimes(name, now, header.mtime, function (err) {
if (err) return cb(err)
utimesParent(name, cb)
})
}
var chperm = function (name, header, cb) {
var link = header.type === 'symlink'
var chmod = link ? xfs.lchmod : xfs.chmod
var chown = link ? xfs.lchown : xfs.chown
if (!chmod) return cb()
var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
chmod(name, mode, function (err) {
if (err) return cb(err)
if (!own) return cb()
if (!chown) return cb()
chown(name, header.uid, header.gid, cb)
})
}
extract.on('entry', function (header, stream, next) {
header = map(header) || header
header.name = normalize(header.name)
var name = path.join(cwd, path.join('/', header.name))
if (ignore(name, header)) {
stream.resume()
return next()
}
var stat = function (err) {
if (err) return next(err)
utimes(name, header, function (err) {
if (err) return next(err)
if (win32) return next()
chperm(name, header, next)
})
}
var onsymlink = function () {
if (win32) return next() // skip symlinks on win for now before it can be tested
xfs.unlink(name, function () {
xfs.symlink(header.linkname, name, stat)
})
}
var onlink = function () {
if (win32) return next() // skip links on win for now before it can be tested
xfs.unlink(name, function () {
var srcpath = path.join(cwd, path.join('/', header.linkname))
xfs.link(srcpath, name, function (err) {
if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
stream = xfs.createReadStream(srcpath)
return onfile()
}
stat(err)
})
})
}
var onfile = function () {
var ws = xfs.createWriteStream(name)
var rs = mapStream(stream, header)
ws.on('error', function (err) { // always forward errors on destroy
rs.destroy(err)
})
pump(rs, ws, function (err) {
if (err) return next(err)
ws.on('close', stat)
})
}
if (header.type === 'directory') {
stack.push([name, header.mtime])
return mkdirfix(name, {
fs: xfs, own: own, uid: header.uid, gid: header.gid
}, stat)
}
var dir = path.dirname(name)
validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
if (err) return next(err)
if (!valid) return next(new Error(dir + ' is not a valid path'))
mkdirfix(dir, {
fs: xfs, own: own, uid: header.uid, gid: header.gid
}, function (err) {
if (err) return next(err)
switch (header.type) {
case 'file': return onfile()
case 'link': return onlink()
case 'symlink': return onsymlink()
}
if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))
stream.resume()
next()
})
})
})
if (opts.finish) extract.on('finish', opts.finish)
return extract
}
function validate (fs, name, root, cb) {
if (name === root) return cb(null, true)
fs.lstat(name, function (err, st) {
if (err && err.code !== 'ENOENT') return cb(err)
if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
cb(null, false)
})
}
function mkdirfix (name, opts, cb) {
mkdirp(name, {fs: opts.fs}, function (err, made) {
if (!err && made && opts.own) {
chownr(made, opts.uid, opts.gid, cb)
} else {
cb(err)
}
})
}
| february29/Learning | web/vue/AccountBook-Express/node_modules/.staging/tar-fs-f8fd0786/index.js | JavaScript | mit | 9,349 |
class AddProfileBackgroundFieldsToUser < ActiveRecord::Migration
def change
add_column :users, :show_profile_background, :boolean, default: true
add_column :users, :profile_background_photo_id, :integer
end
end
| arnkorty/photographer-io | db/migrate/20130731183731_add_profile_background_fields_to_user.rb | Ruby | mit | 223 |
χio Flow
=========
[](https://travis-ci.org/psichi/chix-flow)
| nodule/sockjs | node_modules/fbpx/node_modules/chix-flow/README.md | Markdown | mit | 123 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* 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.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Database Forge Class
*
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
abstract class CI_DB_forge {
/**
* Database object
*
* @var object
*/
protected $db;
/**
* Fields data
*
* @var array
*/
public $fields = array();
/**
* Keys data
*
* @var array
*/
public $keys = array();
/**
* Primary Keys data
*
* @var array
*/
public $primary_keys = array();
/**
* Database character set
*
* @var string
*/
public $db_char_set = '';
// --------------------------------------------------------------------
/**
* CREATE DATABASE statement
*
* @var string
*/
protected $_create_database = 'CREATE DATABASE %s';
/**
* DROP DATABASE statement
*
* @var string
*/
protected $_drop_database = 'DROP DATABASE %s';
/**
* CREATE TABLE statement
*
* @var string
*/
protected $_create_table = "%s %s (%s\n)";
/**
* CREATE TABLE IF statement
*
* @var string
*/
protected $_create_table_if = 'CREATE TABLE IF NOT EXISTS';
/**
* CREATE TABLE keys flag
*
* Whether table keys are created from within the
* CREATE TABLE statement.
*
* @var bool
*/
protected $_create_table_keys = FALSE;
/**
* DROP TABLE IF EXISTS statement
*
* @var string
*/
protected $_drop_table_if = 'DROP TABLE IF EXISTS';
/**
* RENAME TABLE statement
*
* @var string
*/
protected $_rename_table = 'ALTER TABLE %s RENAME TO %s;';
/**
* UNSIGNED support
*
* @var bool|array
*/
protected $_unsigned = TRUE;
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*/
protected $_null = '';
/**
* DEFAULT value representation in CREATE/ALTER TABLE statements
*
* @var string
*/
protected $_default = ' DEFAULT ';
// --------------------------------------------------------------------
/**
* Class constructor
*
* @param object &$db Database object
* @return void
*/
public function __construct(&$db)
{
$this->db =& $db;
log_message('info', 'Database Forge Class Initialized');
}
// --------------------------------------------------------------------
/**
* Create database
*
* @param string $db_name
* @return bool
*/
public function create_database($db_name)
{
if ($this->_create_database === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
elseif ( ! $this->db->query(sprintf($this->_create_database, $db_name, $this->db->char_set, $this->db->dbcollat)))
{
return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
}
if ( ! empty($this->db->data_cache['db_names']))
{
$this->db->data_cache['db_names'][] = $db_name;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Drop database
*
* @param string $db_name
* @return bool
*/
public function drop_database($db_name)
{
if ($this->_drop_database === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
elseif ( ! $this->db->query(sprintf($this->_drop_database, $db_name)))
{
return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
}
if ( ! empty($this->db->data_cache['db_names']))
{
$key = array_search(strtolower($db_name), array_map('strtolower', $this->db->data_cache['db_names']), TRUE);
if ($key !== FALSE)
{
unset($this->db->data_cache['db_names'][$key]);
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Add Key
*
* @param string $key
* @param bool $primary
* @return CI_DB_forge
*/
public function add_key($key, $primary = FALSE)
{
// DO NOT change this! This condition is only applicable
// for PRIMARY keys because you can only have one such,
// and therefore all fields you add to it will be included
// in the same, composite PRIMARY KEY.
//
// It's not the same for regular indexes.
if ($primary === TRUE && is_array($key))
{
foreach ($key as $one)
{
$this->add_key($one, $primary);
}
return $this;
}
if ($primary === TRUE)
{
$this->primary_keys[] = $key;
}
else
{
$this->keys[] = $key;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Add Field
*
* @param array $field
* @return CI_DB_forge
*/
public function add_field($field)
{
if (is_string($field))
{
if ($field === 'id')
{
$this->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 9,
'auto_increment' => TRUE
)
));
$this->add_key('id', TRUE);
}
else
{
if (strpos($field, ' ') === FALSE)
{
show_error('Field information is required for that operation.');
}
$this->fields[] = $field;
}
}
if (is_array($field))
{
$this->fields = array_merge($this->fields, $field);
}
return $this;
}
// --------------------------------------------------------------------
/**
* Create Table
*
* @param string $table Table name
* @param bool $if_not_exists Whether to add IF NOT EXISTS condition
* @param array $attributes Associative array of table attributes
* @return bool
*/
public function create_table($table, $if_not_exists = FALSE, array $attributes = array())
{
if ($table === '')
{
show_error('A table name is required for that operation.');
}
else
{
$table = $this->db->dbprefix.$table;
}
if (count($this->fields) === 0)
{
show_error('Field information is required.');
}
$sql = $this->_create_table($table, $if_not_exists, $attributes);
if (is_bool($sql))
{
$this->_reset();
if ($sql === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
}
if (($result = $this->db->query($sql)) !== FALSE)
{
empty($this->db->data_cache['table_names']) OR $this->db->data_cache['table_names'][] = $table;
// Most databases don't support creating indexes from within the CREATE TABLE statement
if ( ! empty($this->keys))
{
for ($i = 0, $sqls = $this->_process_indexes($table), $c = count($sqls); $i < $c; $i++)
{
$this->db->query($sqls[$i]);
}
}
}
$this->_reset();
return $result;
}
// --------------------------------------------------------------------
/**
* Create Table
*
* @param string $table Table name
* @param bool $if_not_exists Whether to add 'IF NOT EXISTS' condition
* @param array $attributes Associative array of table attributes
* @return mixed
*/
protected function _create_table($table, $if_not_exists, $attributes)
{
if ($if_not_exists === TRUE && $this->_create_table_if === FALSE)
{
if ($this->db->table_exists($table))
{
return TRUE;
}
else
{
$if_not_exists = FALSE;
}
}
$sql = ($if_not_exists)
? sprintf($this->_create_table_if, $this->db->escape_identifiers($table))
: 'CREATE TABLE';
$columns = $this->_process_fields(TRUE);
for ($i = 0, $c = count($columns); $i < $c; $i++)
{
$columns[$i] = ($columns[$i]['_literal'] !== FALSE)
? "\n\t".$columns[$i]['_literal']
: "\n\t".$this->_process_column($columns[$i]);
}
$columns = implode(',', $columns)
.$this->_process_primary_keys($table);
// Are indexes created from within the CREATE TABLE statement? (e.g. in MySQL)
if ($this->_create_table_keys === TRUE)
{
$columns .= $this->_process_indexes($table);
}
// _create_table will usually have the following format: "%s %s (%s\n)"
$sql = sprintf($this->_create_table.'%s',
$sql,
$this->db->escape_identifiers($table),
$columns,
$this->_create_table_attr($attributes)
);
return $sql;
}
// --------------------------------------------------------------------
/**
* CREATE TABLE attributes
*
* @param array $attributes Associative array of table attributes
* @return string
*/
protected function _create_table_attr($attributes)
{
$sql = '';
foreach (array_keys($attributes) as $key)
{
if (is_string($key))
{
$sql .= ' '.strtoupper($key).' '.$attributes[$key];
}
}
return $sql;
}
// --------------------------------------------------------------------
/**
* Drop Table
*
* @param string $table_name Table name
* @param bool $if_exists Whether to add an IF EXISTS condition
* @return bool
*/
public function drop_table($table_name, $if_exists = FALSE)
{
if ($table_name === '')
{
return ($this->db->db_debug) ? $this->db->display_error('db_table_name_required') : FALSE;
}
if (($query = $this->_drop_table($this->db->dbprefix.$table_name, $if_exists)) === TRUE)
{
return TRUE;
}
$query = $this->db->query($query);
// Update table list cache
if ($query && ! empty($this->db->data_cache['table_names']))
{
$key = array_search(strtolower($this->db->dbprefix.$table_name), array_map('strtolower', $this->db->data_cache['table_names']), TRUE);
if ($key !== FALSE)
{
unset($this->db->data_cache['table_names'][$key]);
}
}
return $query;
}
// --------------------------------------------------------------------
/**
* Drop Table
*
* Generates a platform-specific DROP TABLE string
*
* @param string $table Table name
* @param bool $if_exists Whether to add an IF EXISTS condition
* @return string
*/
protected function _drop_table($table, $if_exists)
{
$sql = 'DROP TABLE';
if ($if_exists)
{
if ($this->_drop_table_if === FALSE)
{
if ( ! $this->db->table_exists($table))
{
return TRUE;
}
}
else
{
$sql = sprintf($this->_drop_table_if, $this->db->escape_identifiers($table));
}
}
return $sql.' '.$this->db->escape_identifiers($table);
}
// --------------------------------------------------------------------
/**
* Rename Table
*
* @param string $table_name Old table name
* @param string $new_table_name New table name
* @return bool
*/
public function rename_table($table_name, $new_table_name)
{
if ($table_name === '' OR $new_table_name === '')
{
show_error('A table name is required for that operation.');
return FALSE;
}
elseif ($this->_rename_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
$result = $this->db->query(sprintf($this->_rename_table,
$this->db->escape_identifiers($this->db->dbprefix.$table_name),
$this->db->escape_identifiers($this->db->dbprefix.$new_table_name))
);
if ($result && ! empty($this->db->data_cache['table_names']))
{
$key = array_search(strtolower($this->db->dbprefix.$table_name), array_map('strtolower', $this->db->data_cache['table_names']), TRUE);
if ($key !== FALSE)
{
$this->db->data_cache['table_names'][$key] = $this->db->dbprefix.$new_table_name;
}
}
return $result;
}
// --------------------------------------------------------------------
/**
* Column Add
*
* @todo Remove deprecated $_after option in 3.1+
* @param string $table Table name
* @param array $field Column definition
* @param string $_after Column for AFTER clause (deprecated)
* @return bool
*/
public function add_column($table, $field, $_after = NULL)
{
// Work-around for literal column definitions
is_array($field) OR $field = array($field);
foreach (array_keys($field) as $k)
{
// Backwards-compatibility work-around for MySQL/CUBRID AFTER clause (remove in 3.1+)
if ($_after !== NULL && is_array($field[$k]) && ! isset($field[$k]['after']))
{
$field[$k]['after'] = $_after;
}
$this->add_field(array($k => $field[$k]));
}
$sqls = $this->_alter_table('ADD', $this->db->dbprefix.$table, $this->_process_fields());
$this->_reset();
if ($sqls === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
for ($i = 0, $c = count($sqls); $i < $c; $i++)
{
if ($this->db->query($sqls[$i]) === FALSE)
{
return FALSE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Column Drop
*
* @param string $table Table name
* @param string $column_name Column name
* @return bool
*/
public function drop_column($table, $column_name)
{
$sql = $this->_alter_table('DROP', $this->db->dbprefix.$table, $column_name);
if ($sql === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
return $this->db->query($sql);
}
// --------------------------------------------------------------------
/**
* Column Modify
*
* @param string $table Table name
* @param string $field Column definition
* @return bool
*/
public function modify_column($table, $field)
{
// Work-around for literal column definitions
is_array($field) OR $field = array($field);
foreach (array_keys($field) as $k)
{
$this->add_field(array($k => $field[$k]));
}
if (count($this->fields) === 0)
{
show_error('Field information is required.');
}
$sqls = $this->_alter_table('CHANGE', $this->db->dbprefix.$table, $this->_process_fields());
$this->_reset();
if ($sqls === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
for ($i = 0, $c = count($sqls); $i < $c; $i++)
{
if ($this->db->query($sqls[$i]) === FALSE)
{
return FALSE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* ALTER TABLE
*
* @param string $alter_type ALTER type
* @param string $table Table name
* @param mixed $field Column definition
* @return string|string[]
*/
protected function _alter_table($alter_type, $table, $field)
{
$sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ';
// DROP has everything it needs now.
if ($alter_type === 'DROP')
{
return $sql.'DROP COLUMN '.$this->db->escape_identifiers($field);
}
$sql .= ($alter_type === 'ADD')
? 'ADD '
: $alter_type.' COLUMN ';
$sqls = array();
for ($i = 0, $c = count($field); $i < $c; $i++)
{
$sqls[] = $sql
.($field[$i]['_literal'] !== FALSE ? $field[$i]['_literal'] : $this->_process_column($field[$i]));
}
return $sqls;
}
// --------------------------------------------------------------------
/**
* Process fields
*
* @param bool $create_table
* @return array
*/
protected function _process_fields($create_table = FALSE)
{
$fields = array();
foreach ($this->fields as $key => $attributes)
{
if (is_int($key) && ! is_array($attributes))
{
$fields[] = array('_literal' => $attributes);
continue;
}
$attributes = array_change_key_case($attributes, CASE_UPPER);
if ($create_table === TRUE && empty($attributes['TYPE']))
{
continue;
}
isset($attributes['TYPE']) && $this->_attr_type($attributes);
$field = array(
'name' => $key,
'new_name' => isset($attributes['NAME']) ? $attributes['NAME'] : NULL,
'type' => isset($attributes['TYPE']) ? $attributes['TYPE'] : NULL,
'length' => '',
'unsigned' => '',
'null' => '',
'unique' => '',
'default' => '',
'auto_increment' => '',
'_literal' => FALSE
);
isset($attributes['TYPE']) && $this->_attr_unsigned($attributes, $field);
if ($create_table === FALSE)
{
if (isset($attributes['AFTER']))
{
$field['after'] = $attributes['AFTER'];
}
elseif (isset($attributes['FIRST']))
{
$field['first'] = (bool) $attributes['FIRST'];
}
}
$this->_attr_default($attributes, $field);
if (isset($attributes['NULL']))
{
if ($attributes['NULL'] === TRUE)
{
$field['null'] = empty($this->_null) ? '' : ' '.$this->_null;
}
else
{
$field['null'] = ' NOT NULL';
}
}
elseif ($create_table === TRUE)
{
$field['null'] = ' NOT NULL';
}
$this->_attr_auto_increment($attributes, $field);
$this->_attr_unique($attributes, $field);
if (isset($attributes['COMMENT']))
{
$field['comment'] = $this->db->escape($attributes['COMMENT']);
}
if (isset($attributes['TYPE']) && ! empty($attributes['CONSTRAINT']))
{
switch (strtoupper($attributes['TYPE']))
{
case 'ENUM':
case 'SET':
$attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']);
default:
$field['length'] = is_array($attributes['CONSTRAINT'])
? '('.implode(',', $attributes['CONSTRAINT']).')'
: '('.$attributes['CONSTRAINT'].')';
break;
}
}
$fields[] = $field;
}
return $fields;
}
// --------------------------------------------------------------------
/**
* Process column
*
* @param array $field
* @return string
*/
protected function _process_column($field)
{
return $this->db->escape_identifiers($field['name'])
.' '.$field['type'].$field['length']
.$field['unsigned']
.$field['default']
.$field['null']
.$field['auto_increment']
.$field['unique'];
}
// --------------------------------------------------------------------
/**
* Field attribute TYPE
*
* Performs a data type mapping between different databases.
*
* @param array &$attributes
* @return void
*/
protected function _attr_type(&$attributes)
{
// Usually overridden by drivers
}
// --------------------------------------------------------------------
/**
* Field attribute UNSIGNED
*
* Depending on the _unsigned property value:
*
* - TRUE will always set $field['unsigned'] to 'UNSIGNED'
* - FALSE will always set $field['unsigned'] to ''
* - array(TYPE) will set $field['unsigned'] to 'UNSIGNED',
* if $attributes['TYPE'] is found in the array
* - array(TYPE => UTYPE) will change $field['type'],
* from TYPE to UTYPE in case of a match
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_unsigned(&$attributes, &$field)
{
if (empty($attributes['UNSIGNED']) OR $attributes['UNSIGNED'] !== TRUE)
{
return;
}
// Reset the attribute in order to avoid issues if we do type conversion
$attributes['UNSIGNED'] = FALSE;
if (is_array($this->_unsigned))
{
foreach (array_keys($this->_unsigned) as $key)
{
if (is_int($key) && strcasecmp($attributes['TYPE'], $this->_unsigned[$key]) === 0)
{
$field['unsigned'] = ' UNSIGNED';
return;
}
elseif (is_string($key) && strcasecmp($attributes['TYPE'], $key) === 0)
{
$field['type'] = $key;
return;
}
}
return;
}
$field['unsigned'] = ($this->_unsigned === TRUE) ? ' UNSIGNED' : '';
}
// --------------------------------------------------------------------
/**
* Field attribute DEFAULT
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_default(&$attributes, &$field)
{
if ($this->_default === FALSE)
{
return;
}
if (array_key_exists('DEFAULT', $attributes))
{
if ($attributes['DEFAULT'] === NULL)
{
$field['default'] = empty($this->_null) ? '' : $this->_default.$this->_null;
// Override the NULL attribute if that's our default
$attributes['NULL'] = TRUE;
$field['null'] = empty($this->_null) ? '' : ' '.$this->_null;
}
else
{
$field['default'] = $this->_default.$this->db->escape($attributes['DEFAULT']);
}
}
}
// --------------------------------------------------------------------
/**
* Field attribute UNIQUE
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_unique(&$attributes, &$field)
{
if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE)
{
$field['unique'] = ' UNIQUE';
}
}
// --------------------------------------------------------------------
/**
* Field attribute AUTO_INCREMENT
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_auto_increment(&$attributes, &$field)
{
if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE)
{
$field['auto_increment'] = ' AUTO_INCREMENT';
}
}
// --------------------------------------------------------------------
/**
* Process primary keys
*
* @param string $table Table name
* @return string
*/
protected function _process_primary_keys($table)
{
$sql = '';
for ($i = 0, $c = count($this->primary_keys); $i < $c; $i++)
{
if ( ! isset($this->fields[$this->primary_keys[$i]]))
{
unset($this->primary_keys[$i]);
}
}
if (count($this->primary_keys) > 0)
{
$sql .= ",\n\tCONSTRAINT ".$this->db->escape_identifiers('pk_'.$table)
.' PRIMARY KEY('.implode(', ', $this->db->escape_identifiers($this->primary_keys)).')';
}
return $sql;
}
// --------------------------------------------------------------------
/**
* Process indexes
*
* @param string $table
* @return string
*/
protected function _process_indexes($table)
{
$sqls = array();
for ($i = 0, $c = count($this->keys); $i < $c; $i++)
{
if (is_array($this->keys[$i]))
{
for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++)
{
if ( ! isset($this->fields[$this->keys[$i][$i2]]))
{
unset($this->keys[$i][$i2]);
continue;
}
}
}
elseif ( ! isset($this->fields[$this->keys[$i]]))
{
unset($this->keys[$i]);
continue;
}
is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]);
$sqls[] = 'CREATE INDEX '.$this->db->escape_identifiers($table.'_'.implode('_', $this->keys[$i]))
.' ON '.$this->db->escape_identifiers($table)
.' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).');';
}
return $sqls;
}
// --------------------------------------------------------------------
/**
* Reset
*
* Resets table creation vars
*
* @return void
*/
protected function _reset()
{
$this->fields = $this->keys = $this->primary_keys = array();
}
}
| wms-code/CodeIgniter-admin | system/database/DB_forge.php | PHP | mit | 23,953 |
"use strict";
// local import of the exported AngularPage class
var angularPage_1 = require('./angularPage');
// The jasmine typings are brought in via DefinitelyTyped ambient typings.
describe('angularjs homepage', function () {
it('should greet the named user', function () {
var angularHomepage = new angularPage_1.AngularHomepage();
angularHomepage.get();
angularHomepage.setName('Julie');
expect(angularHomepage.getGreeting()).toEqual('Hello Julie!');
});
});
| bhavateja/Developer-Test-Angular-JS-Web-App | node_modules/protractor/built/spec/install/node_modules/protractor/exampleTypescript/specPageObjects.js | JavaScript | mit | 505 |
/*
* Copyright (c) 2012, 2013, 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* 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 JSR-310 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.
*/
package java.time;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.ChronoUnit.CENTURIES;
import static java.time.temporal.ChronoUnit.DECADES;
import static java.time.temporal.ChronoUnit.ERAS;
import static java.time.temporal.ChronoUnit.MILLENNIA;
import static java.time.temporal.ChronoUnit.YEARS;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.chrono.Chronology;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.SignStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Objects;
/**
* A year in the ISO-8601 calendar system, such as {@code 2007}.
* <p>
* {@code Year} is an immutable date-time object that represents a year.
* Any field that can be derived from a year can be obtained.
* <p>
* <b>Note that years in the ISO chronology only align with years in the
* Gregorian-Julian system for modern years. Parts of Russia did not switch to the
* modern Gregorian/ISO rules until 1920.
* As such, historical years must be treated with caution.</b>
* <p>
* This class does not store or represent a month, day, time or time-zone.
* For example, the value "2007" can be stored in a {@code Year}.
* <p>
* Years represented by this class follow the ISO-8601 standard and use
* the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.
* <p>
* The ISO-8601 calendar system is the modern civil calendar system used today
* in most of the world. It is equivalent to the proleptic Gregorian calendar
* system, in which today's rules for leap years are applied for all time.
* For most applications written today, the ISO-8601 rules are entirely suitable.
* However, any application that makes use of historical dates, and requires them
* to be accurate will find the ISO-8601 approach unsuitable.
*
* <p>
* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Year} may have unpredictable results and should be avoided.
* The {@code equals} method should be used for comparisons.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class Year
implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {
/**
* The minimum supported year, '-999,999,999'.
*/
public static final int MIN_VALUE = -999_999_999;
/**
* The maximum supported year, '+999,999,999'.
*/
public static final int MAX_VALUE = 999_999_999;
/**
* Serialization version.
*/
private static final long serialVersionUID = -23038383694477807L;
/**
* Parser.
*/
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.toFormatter();
/**
* The year being represented.
*/
private final int year;
//-----------------------------------------------------------------------
/**
* Obtains the current year from the system clock in the default time-zone.
* <p>
* This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current year.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current year using the system clock and default time-zone, not null
*/
public static Year now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current year from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current year using the system clock, not null
*/
public static Year now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current year from the specified clock.
* <p>
* This will query the specified clock to obtain the current year.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current year, not null
*/
public static Year now(Clock clock) {
final LocalDate now = LocalDate.now(clock); // called once
return Year.of(now.getYear());
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year}.
* <p>
* This method accepts a year value from the proleptic ISO calendar system.
* <p>
* The year 2AD/CE is represented by 2.<br>
* The year 1AD/CE is represented by 1.<br>
* The year 1BC/BCE is represented by 0.<br>
* The year 2BC/BCE is represented by -1.<br>
*
* @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}
* @return the year, not null
* @throws DateTimeException if the field is invalid
*/
public static Year of(int isoYear) {
YEAR.checkValidValue(isoYear);
return new Year(isoYear);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year} from a temporal object.
* <p>
* This obtains a year based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code Year}.
* <p>
* The conversion extracts the {@link ChronoField#YEAR year} field.
* The extraction is only permitted if the temporal object has an ISO
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used in queries via method reference, {@code Year::from}.
*
* @param temporal the temporal object to convert, not null
* @return the year, not null
* @throws DateTimeException if unable to convert to a {@code Year}
*/
public static Year from(TemporalAccessor temporal) {
if (temporal instanceof Year) {
return (Year) temporal;
}
Objects.requireNonNull(temporal, "temporal");
try {
if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
temporal = LocalDate.from(temporal);
}
return of(temporal.get(YEAR));
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName(), ex);
}
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year} from a text string such as {@code 2007}.
* <p>
* The string must represent a valid year.
* Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
*
* @param text the text to parse such as "2007", not null
* @return the parsed year, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Year parse(CharSequence text) {
return parse(text, PARSER);
}
/**
* Obtains an instance of {@code Year} from a text string using a specific formatter.
* <p>
* The text is parsed using the formatter, returning a year.
*
* @param text the text to parse, not null
* @param formatter the formatter to use, not null
* @return the parsed year, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Year parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, Year::from);
}
//-------------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @param year the year to check
* @return true if the year is leap, false otherwise
*/
public static boolean isLeap(long year) {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
//-----------------------------------------------------------------------
/**
* Constructor.
*
* @param year the year to represent
*/
private Year(int year) {
this.year = year;
}
//-----------------------------------------------------------------------
/**
* Gets the year value.
* <p>
* The year returned by this method is proleptic as per {@code get(YEAR)}.
*
* @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}
*/
public int getValue() {
return year;
}
//-----------------------------------------------------------------------
/**
* Checks if the specified field is supported.
* <p>
* This checks if this year can be queried for the specified field.
* If false, then calling the {@link #range(TemporalField) range},
* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
* methods will throw an exception.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The supported fields are:
* <ul>
* <li>{@code YEAR_OF_ERA}
* <li>{@code YEAR}
* <li>{@code ERA}
* </ul>
* All other {@code ChronoField} instances will return false.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the field is supported is determined by the field.
*
* @param field the field to check, null returns false
* @return true if the field is supported on this year, false if not
*/
@Override
public boolean isSupported(TemporalField field) {
if (field instanceof ChronoField) {
return field == YEAR || field == YEAR_OF_ERA || field == ERA;
}
return field != null && field.isSupportedBy(this);
}
/**
* Checks if the specified unit is supported.
* <p>
* This checks if the specified unit can be added to, or subtracted from, this date-time.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
* If the unit is a {@link ChronoUnit} then the query is implemented here.
* The supported units are:
* <ul>
* <li>{@code YEARS}
* <li>{@code DECADES}
* <li>{@code CENTURIES}
* <li>{@code MILLENNIA}
* <li>{@code ERAS}
* </ul>
* All other {@code ChronoUnit} instances will return false.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
* passing {@code this} as the argument.
* Whether the unit is supported is determined by the unit.
*
* @param unit the unit to check, null returns false
* @return true if the unit can be added/subtracted, false if not
*/
@Override
public boolean isSupported(TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
}
return unit != null && unit.isSupportedBy(this);
}
//-----------------------------------------------------------------------
/**
* Gets the range of valid values for the specified field.
* <p>
* The range object expresses the minimum and maximum valid values for a field.
* This year is used to enhance the accuracy of the returned range.
* If it is not possible to return the range, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return
* appropriate range instances.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the range can be obtained is determined by the field.
*
* @param field the field to query the range for, not null
* @return the range of valid values for the field, not null
* @throws DateTimeException if the range for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
*/
@Override
public ValueRange range(TemporalField field) {
if (field == YEAR_OF_ERA) {
return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));
}
return Temporal.super.range(field);
}
/**
* Gets the value of the specified field from this year as an {@code int}.
* <p>
* This queries this year for the value for the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
* @return the value for the field
* @throws DateTimeException if a value for the field cannot be obtained or
* the value is outside the range of valid values for the field
* @throws UnsupportedTemporalTypeException if the field is not supported or
* the range of values exceeds an {@code int}
* @throws ArithmeticException if numeric overflow occurs
*/
@Override // override for Javadoc
public int get(TemporalField field) {
return range(field).checkValidIntValue(getLong(field), field);
}
/**
* Gets the value of the specified field from this year as a {@code long}.
* <p>
* This queries this year for the value for the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
* @return the value for the field
* @throws DateTimeException if a value for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);
case YEAR: return year;
case ERA: return (year < 1 ? 0 : 1);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}
//-----------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @return true if the year is leap, false otherwise
*/
public boolean isLeap() {
return Year.isLeap(year);
}
/**
* Checks if the month-day is valid for this year.
* <p>
* This method checks whether this year and the input month and day form
* a valid date.
*
* @param monthDay the month-day to validate, null returns false
* @return true if the month and day are valid for this year
*/
public boolean isValidMonthDay(MonthDay monthDay) {
return monthDay != null && monthDay.isValidYear(year);
}
/**
* Gets the length of this year in days.
*
* @return the length of this year in days, 365 or 366
*/
public int length() {
return isLeap() ? 366 : 365;
}
//-----------------------------------------------------------------------
/**
* Returns an adjusted copy of this year.
* <p>
* This returns a {@code Year}, based on this one, with the year adjusted.
* The adjustment takes place using the specified adjuster strategy object.
* Read the documentation of the adjuster to understand what adjustment will be made.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalAdjuster#adjustInto(Temporal)} method on the
* specified adjuster passing {@code this} as the argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param adjuster the adjuster to use, not null
* @return a {@code Year} based on {@code this} with the adjustment made, not null
* @throws DateTimeException if the adjustment cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year with(TemporalAdjuster adjuster) {
return (Year) adjuster.adjustInto(this);
}
/**
* Returns a copy of this year with the specified field set to a new value.
* <p>
* This returns a {@code Year}, based on this one, with the value
* for the specified field changed.
* If it is not possible to set the value, because the field is not supported or for
* some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the adjustment is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEAR_OF_ERA} -
* Returns a {@code Year} with the specified year-of-era
* The era will be unchanged.
* <li>{@code YEAR} -
* Returns a {@code Year} with the specified year.
* This completely replaces the date and is equivalent to {@link #of(int)}.
* <li>{@code ERA} -
* Returns a {@code Year} with the specified era.
* The year-of-era will be unchanged.
* </ul>
* <p>
* In all cases, if the new value is outside the valid range of values for the field
* then a {@code DateTimeException} will be thrown.
* <p>
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
* passing {@code this} as the argument. In this case, the field determines
* whether and how to adjust the instant.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param field the field to set in the result, not null
* @param newValue the new value of the field in the result
* @return a {@code Year} based on {@code this} with the specified field set, not null
* @throws DateTimeException if the field cannot be set
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year with(TemporalField field, long newValue) {
if (field instanceof ChronoField) {
ChronoField f = (ChronoField) field;
f.checkValidValue(newValue);
switch (f) {
case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue));
case YEAR: return Year.of((int) newValue);
case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year));
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.adjustInto(this, newValue);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount added.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
* to implement the addition in any way it wishes, however it typically
* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount to add, not null
* @return a {@code Year} based on this year with the addition made, not null
* @throws DateTimeException if the addition cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year plus(TemporalAmount amountToAdd) {
return (Year) amountToAdd.addTo(this);
}
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit added. If it is not possible to add the amount, because the
* unit is not supported or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoUnit} then the addition is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEARS} -
* Returns a {@code Year} with the specified number of years added.
* This is equivalent to {@link #plusYears(long)}.
* <li>{@code DECADES} -
* Returns a {@code Year} with the specified number of decades added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 10.
* <li>{@code CENTURIES} -
* Returns a {@code Year} with the specified number of centuries added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 100.
* <li>{@code MILLENNIA} -
* Returns a {@code Year} with the specified number of millennia added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 1,000.
* <li>{@code ERAS} -
* Returns a {@code Year} with the specified number of eras added.
* Only two eras are supported so the amount must be one, zero or minus one.
* If the amount is non-zero then the year is changed such that the year-of-era
* is unchanged.
* </ul>
* <p>
* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
* passing {@code this} as the argument. In this case, the unit determines
* whether and how to perform the addition.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount of the unit to add to the result, may be negative
* @param unit the unit of the amount to add, not null
* @return a {@code Year} based on this year with the specified amount added, not null
* @throws DateTimeException if the addition cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year plus(long amountToAdd, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case YEARS: return plusYears(amountToAdd);
case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.addTo(this, amountToAdd);
}
/**
* Returns a copy of this year with the specified number of years added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
* @return a {@code Year} based on this year with the period added, not null
* @throws DateTimeException if the result exceeds the supported year range
*/
public Year plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount subtracted.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
* to implement the subtraction in any way it wishes, however it typically
* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount to subtract, not null
* @return a {@code Year} based on this year with the subtraction made, not null
* @throws DateTimeException if the subtraction cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year minus(TemporalAmount amountToSubtract) {
return (Year) amountToSubtract.subtractFrom(this);
}
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit subtracted. If it is not possible to subtract the amount,
* because the unit is not supported or for some other reason, an exception is thrown.
* <p>
* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
* See that method for a full description of how addition, and thus subtraction, works.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount of the unit to subtract from the result, may be negative
* @param unit the unit of the amount to subtract, not null
* @return a {@code Year} based on this year with the specified amount subtracted, not null
* @throws DateTimeException if the subtraction cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year minus(long amountToSubtract, TemporalUnit unit) {
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
}
/**
* Returns a copy of this year with the specified number of years subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
* @return a {@code Year} based on this year with the period subtracted, not null
* @throws DateTimeException if the result exceeds the supported year range
*/
public Year minusYears(long yearsToSubtract) {
return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
}
//-----------------------------------------------------------------------
/**
* Queries this year using the specified query.
* <p>
* This queries this year using the specified query strategy object.
* The {@code TemporalQuery} object defines the logic to be used to
* obtain the result. Read the documentation of the query to understand
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
* @param query the query to invoke, not null
* @return the query result, null may be returned (defined by the query)
* @throws DateTimeException if unable to query (defined by the query)
* @throws ArithmeticException if numeric overflow occurs (defined by the query)
*/
@SuppressWarnings("unchecked")
@Override
public <R> R query(TemporalQuery<R> query) {
if (query == TemporalQueries.chronology()) {
return (R) IsoChronology.INSTANCE;
} else if (query == TemporalQueries.precision()) {
return (R) YEARS;
}
return Temporal.super.query(query);
}
/**
* Adjusts the specified temporal object to have this year.
* <p>
* This returns a temporal object of the same observable type as the input
* with the year changed to be the same as this.
* <p>
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#YEAR} as the field.
* If the specified temporal object does not use the ISO calendar system then
* a {@code DateTimeException} is thrown.
* <p>
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with(TemporalAdjuster)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisYear.adjustInto(temporal);
* temporal = temporal.with(thisYear);
* </pre>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param temporal the target object to be adjusted, not null
* @return the adjusted object, not null
* @throws DateTimeException if unable to make the adjustment
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Temporal adjustInto(Temporal temporal) {
if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
throw new DateTimeException("Adjustment only supported on ISO date-time");
}
return temporal.with(YEAR, year);
}
/**
* Calculates the amount of time until another year in terms of the specified unit.
* <p>
* This calculates the amount of time between two {@code Year}
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified year.
* The result will be negative if the end is before the start.
* The {@code Temporal} passed to this method is converted to a
* {@code Year} using {@link #from(TemporalAccessor)}.
* For example, the period in decades between two year can be calculated
* using {@code startYear.until(endYear, DECADES)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two years.
* For example, the period in decades between 2012 and 2031
* will only be one decade as it is one year short of two decades.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method.
* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
* <pre>
* // these two lines are equivalent
* amount = start.until(end, YEARS);
* amount = YEARS.between(start, end);
* </pre>
* The choice should be made based on which makes the code more readable.
* <p>
* The calculation is implemented in this method for {@link ChronoUnit}.
* The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},
* {@code MILLENNIA} and {@code ERAS} are supported.
* Other {@code ChronoUnit} values will throw an exception.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
* passing {@code this} as the first argument and the converted input temporal
* as the second argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null
* @param unit the unit to measure the amount in, not null
* @return the amount of time between this year and the end year
* @throws DateTimeException if the amount cannot be calculated, or the end
* temporal cannot be converted to a {@code Year}
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
Year end = Year.from(endExclusive);
if (unit instanceof ChronoUnit) {
long yearsUntil = ((long) end.year) - year; // no overflow
switch ((ChronoUnit) unit) {
case YEARS: return yearsUntil;
case DECADES: return yearsUntil / 10;
case CENTURIES: return yearsUntil / 100;
case MILLENNIA: return yearsUntil / 1000;
case ERAS: return end.getLong(ERA) - getLong(ERA);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.between(this, end);
}
/**
* Formats this year using the specified formatter.
* <p>
* This year will be passed to the formatter to produce a string.
*
* @param formatter the formatter to use, not null
* @return the formatted year string, not null
* @throws DateTimeException if an error occurs during printing
*/
public String format(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.format(this);
}
//-----------------------------------------------------------------------
/**
* Combines this year with a day-of-year to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified day-of-year.
* <p>
* The day-of-year value 366 is only valid in a leap year.
*
* @param dayOfYear the day-of-year to use, not null
* @return the local date formed from this year and the specified date of year, not null
* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
* to 366 and this is not a leap year
*/
public LocalDate atDay(int dayOfYear) {
return LocalDate.ofYearDay(year, dayOfYear);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, not null
* @return the year-month formed from this year and the specified month, not null
*/
public YearMonth atMonth(Month month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, from 1 (January) to 12 (December)
* @return the year-month formed from this year and the specified month, not null
* @throws DateTimeException if the month is invalid
*/
public YearMonth atMonth(int month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month-day to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified month-day.
* <p>
* A month-day of February 29th will be adjusted to February 28th in the resulting
* date if the year is not a leap year.
*
* @param monthDay the month-day to use, not null
* @return the local date formed from this year and the specified month-day, not null
*/
public LocalDate atMonthDay(MonthDay monthDay) {
return monthDay.atYear(year);
}
//-----------------------------------------------------------------------
/**
* Compares this year to another year.
* <p>
* The comparison is based on the value of the year.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @param other the other year to compare to, not null
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(Year other) {
return year - other.year;
}
/**
* Is this year after the specified year.
*
* @param other the other year to compare to, not null
* @return true if this is after the specified year
*/
public boolean isAfter(Year other) {
return year > other.year;
}
/**
* Is this year before the specified year.
*
* @param other the other year to compare to, not null
* @return true if this point is before the specified year
*/
public boolean isBefore(Year other) {
return year < other.year;
}
//-----------------------------------------------------------------------
/**
* Checks if this year is equal to another year.
* <p>
* The comparison is based on the time-line position of the years.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other year
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Year) {
return year == ((Year) obj).year;
}
return false;
}
/**
* A hash code for this year.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return year;
}
//-----------------------------------------------------------------------
/**
* Outputs this year as a {@code String}.
*
* @return a string representation of this year, not null
*/
@Override
public String toString() {
return Integer.toString(year);
}
//-----------------------------------------------------------------------
/**
* Writes the object using a
* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
* @serialData
* <pre>
* out.writeByte(11); // identifies a Year
* out.writeInt(year);
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
private Object writeReplace() {
return new Ser(Ser.YEAR_TYPE, this);
}
/**
* Defend against malicious streams.
*
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
void writeExternal(DataOutput out) throws IOException {
out.writeInt(year);
}
static Year readExternal(DataInput in) throws IOException {
return Year.of(in.readInt());
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/java/time/Year.java | Java | mit | 47,803 |
// ------------------------------------------------------------------------------
//The MIT License(MIT)
//Copyright(c) 2015 Office Developer
//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.
// ------------------------------------------------------------------------------
using System.Threading.Tasks;
using Microsoft.Online.Applications.Core.Authentication;
using Microsoft.Online.Applications.Core.Configuration;
namespace Microsoft.Online.Applications.Core
{
public class ServiceProvider : IServiceInfoProvider
{
public IAuthenticationProvider AuthenticationProvider { get; private set; }
public virtual Task<ServiceInformation> CreateServiceInfo(AppConfig appConfig, CredentialType credentialType)
{
var activeDirectoryServiceInfo = new AdalServiceInformation
{
ClientID = appConfig.ClientID,
ClientSecret = appConfig.ClientSecret,
Tenant = appConfig.TenantDomain,
ServiceResource = appConfig.ServiceResource
};
if (credentialType == CredentialType.Certificate)
{
activeDirectoryServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new AdalCertificateAuthenticationProvider(activeDirectoryServiceInfo);
}
else
{
activeDirectoryServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new AdalClientAuthenticationProvider(activeDirectoryServiceInfo);
}
return Task.FromResult<ServiceInformation>(activeDirectoryServiceInfo);
}
}
}
| jansenbe/PnP-Tools | Solutions/Tenant Information Portal/src/Microsoft.Online.Applications.Core/ServiceProvider.cs | C# | mit | 2,638 |
import answer from './answer';
var answer2 = answer;
export default answer2;
| lukeapage/rollup | test/function/statement-order/main.js | JavaScript | mit | 77 |
---
title: Structure
page_title: Structure | RadSocialShare for ASP.NET AJAX Documentation
description: Structure
slug: socialshare/getting-started/structure
tags: structure
published: True
position: 1
---
# Structure
The main elements of the **RadSocialShare** control are:
* **MainButtons** - these are the buttons that are always visible on the page
* **CompactButton** - this is an extra button that is not used for sharing, but to show the other available buttons
* **CompactButtons list** - these are the buttons that are not initially visible on the page, yet are easily reachable in a movable popup
* **SearchBox** - you can start typing a social network's name and the **CompactButtons** will be filtered accordingly
* **CompactButtons popup** - the **RadWindow** that holds the additional buttons
* **Send E-mail button** - a button that pops up a form in a **RadWindow** that allows you to send an e-mail via a dedicated server
* **Mailto button** - a button that triggers the system's default mail client to send an e-mail via the user machine
* **Label Text** - the text associated with the button. It can be set explicitly via a property. The CompactButtons have a predefined value which is used for the Search Box even if you do not set the label explicitly.
| anhquoc956/ajax-docs | controls/socialshare/getting-started/structure.md | Markdown | mit | 1,383 |
import { Quaternion } from '../math/Quaternion';
import { Vector3 } from '../math/Vector3';
import { Matrix4 } from '../math/Matrix4';
import { EventDispatcher } from './EventDispatcher';
import { Euler } from '../math/Euler';
import { Layers } from './Layers';
import { Matrix3 } from '../math/Matrix3';
import { _Math } from '../math/Math';
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author elephantatwork / www.elephantatwork.ch
*/
var object3DId = 0;
function Object3D() {
Object.defineProperty( this, 'id', { value: object3DId ++ } );
this.uuid = _Math.generateUUID();
this.name = '';
this.type = 'Object3D';
this.parent = null;
this.children = [];
this.up = Object3D.DefaultUp.clone();
var position = new Vector3();
var rotation = new Euler();
var quaternion = new Quaternion();
var scale = new Vector3( 1, 1, 1 );
function onRotationChange() {
quaternion.setFromEuler( rotation, false );
}
function onQuaternionChange() {
rotation.setFromQuaternion( quaternion, undefined, false );
}
rotation.onChange( onRotationChange );
quaternion.onChange( onQuaternionChange );
Object.defineProperties( this, {
position: {
enumerable: true,
value: position
},
rotation: {
enumerable: true,
value: rotation
},
quaternion: {
enumerable: true,
value: quaternion
},
scale: {
enumerable: true,
value: scale
},
modelViewMatrix: {
value: new Matrix4()
},
normalMatrix: {
value: new Matrix3()
}
} );
this.matrix = new Matrix4();
this.matrixWorld = new Matrix4();
this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
this.matrixWorldNeedsUpdate = false;
this.layers = new Layers();
this.visible = true;
this.castShadow = false;
this.receiveShadow = false;
this.frustumCulled = true;
this.renderOrder = 0;
this.userData = {};
}
Object3D.DefaultUp = new Vector3( 0, 1, 0 );
Object3D.DefaultMatrixAutoUpdate = true;
Object.assign( Object3D.prototype, EventDispatcher.prototype, {
isObject3D: true,
onBeforeRender: function () {},
onAfterRender: function () {},
applyMatrix: function ( matrix ) {
this.matrix.multiplyMatrices( matrix, this.matrix );
this.matrix.decompose( this.position, this.quaternion, this.scale );
},
applyQuaternion: function ( q ) {
this.quaternion.premultiply( q );
return this;
},
setRotationFromAxisAngle: function ( axis, angle ) {
// assumes axis is normalized
this.quaternion.setFromAxisAngle( axis, angle );
},
setRotationFromEuler: function ( euler ) {
this.quaternion.setFromEuler( euler, true );
},
setRotationFromMatrix: function ( m ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
this.quaternion.setFromRotationMatrix( m );
},
setRotationFromQuaternion: function ( q ) {
// assumes q is normalized
this.quaternion.copy( q );
},
rotateOnAxis: function () {
// rotate object on axis in object space
// axis is assumed to be normalized
var q1 = new Quaternion();
return function rotateOnAxis( axis, angle ) {
q1.setFromAxisAngle( axis, angle );
this.quaternion.multiply( q1 );
return this;
};
}(),
rotateX: function () {
var v1 = new Vector3( 1, 0, 0 );
return function rotateX( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
rotateY: function () {
var v1 = new Vector3( 0, 1, 0 );
return function rotateY( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
rotateZ: function () {
var v1 = new Vector3( 0, 0, 1 );
return function rotateZ( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
translateOnAxis: function () {
// translate object by distance along axis in object space
// axis is assumed to be normalized
var v1 = new Vector3();
return function translateOnAxis( axis, distance ) {
v1.copy( axis ).applyQuaternion( this.quaternion );
this.position.add( v1.multiplyScalar( distance ) );
return this;
};
}(),
translateX: function () {
var v1 = new Vector3( 1, 0, 0 );
return function translateX( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
translateY: function () {
var v1 = new Vector3( 0, 1, 0 );
return function translateY( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
translateZ: function () {
var v1 = new Vector3( 0, 0, 1 );
return function translateZ( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
localToWorld: function ( vector ) {
return vector.applyMatrix4( this.matrixWorld );
},
worldToLocal: function () {
var m1 = new Matrix4();
return function worldToLocal( vector ) {
return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
};
}(),
lookAt: function () {
// This method does not support objects with rotated and/or translated parent(s)
var m1 = new Matrix4();
return function lookAt( vector ) {
if ( this.isCamera ) {
m1.lookAt( this.position, vector, this.up );
} else {
m1.lookAt( vector, this.position, this.up );
}
this.quaternion.setFromRotationMatrix( m1 );
};
}(),
add: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.add( arguments[ i ] );
}
return this;
}
if ( object === this ) {
console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
return this;
}
if ( ( object && object.isObject3D ) ) {
if ( object.parent !== null ) {
object.parent.remove( object );
}
object.parent = this;
object.dispatchEvent( { type: 'added' } );
this.children.push( object );
} else {
console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
}
return this;
},
remove: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.remove( arguments[ i ] );
}
return this;
}
var index = this.children.indexOf( object );
if ( index !== - 1 ) {
object.parent = null;
object.dispatchEvent( { type: 'removed' } );
this.children.splice( index, 1 );
}
return this;
},
getObjectById: function ( id ) {
return this.getObjectByProperty( 'id', id );
},
getObjectByName: function ( name ) {
return this.getObjectByProperty( 'name', name );
},
getObjectByProperty: function ( name, value ) {
if ( this[ name ] === value ) return this;
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
var object = child.getObjectByProperty( name, value );
if ( object !== undefined ) {
return object;
}
}
return undefined;
},
getWorldPosition: function ( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.updateMatrixWorld( true );
return result.setFromMatrixPosition( this.matrixWorld );
},
getWorldQuaternion: function () {
var position = new Vector3();
var scale = new Vector3();
return function getWorldQuaternion( optionalTarget ) {
var result = optionalTarget || new Quaternion();
this.updateMatrixWorld( true );
this.matrixWorld.decompose( position, result, scale );
return result;
};
}(),
getWorldRotation: function () {
var quaternion = new Quaternion();
return function getWorldRotation( optionalTarget ) {
var result = optionalTarget || new Euler();
this.getWorldQuaternion( quaternion );
return result.setFromQuaternion( quaternion, this.rotation.order, false );
};
}(),
getWorldScale: function () {
var position = new Vector3();
var quaternion = new Quaternion();
return function getWorldScale( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.updateMatrixWorld( true );
this.matrixWorld.decompose( position, quaternion, result );
return result;
};
}(),
getWorldDirection: function () {
var quaternion = new Quaternion();
return function getWorldDirection( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.getWorldQuaternion( quaternion );
return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
};
}(),
raycast: function () {},
traverse: function ( callback ) {
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverse( callback );
}
},
traverseVisible: function ( callback ) {
if ( this.visible === false ) return;
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverseVisible( callback );
}
},
traverseAncestors: function ( callback ) {
var parent = this.parent;
if ( parent !== null ) {
callback( parent );
parent.traverseAncestors( callback );
}
},
updateMatrix: function () {
this.matrix.compose( this.position, this.quaternion, this.scale );
this.matrixWorldNeedsUpdate = true;
},
updateMatrixWorld: function ( force ) {
if ( this.matrixAutoUpdate ) this.updateMatrix();
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent === null ) {
this.matrixWorld.copy( this.matrix );
} else {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].updateMatrixWorld( force );
}
},
toJSON: function ( meta ) {
// meta is '' when called from JSON.stringify
var isRootObject = ( meta === undefined || meta === '' );
var output = {};
// meta is a hash used to collect geometries, materials.
// not providing it implies that this is the root object
// being serialized.
if ( isRootObject ) {
// initialize meta obj
meta = {
geometries: {},
materials: {},
textures: {},
images: {}
};
output.metadata = {
version: 4.5,
type: 'Object',
generator: 'Object3D.toJSON'
};
}
// standard Object3D serialization
var object = {};
object.uuid = this.uuid;
object.type = this.type;
if ( this.name !== '' ) object.name = this.name;
if ( this.castShadow === true ) object.castShadow = true;
if ( this.receiveShadow === true ) object.receiveShadow = true;
if ( this.visible === false ) object.visible = false;
if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
object.matrix = this.matrix.toArray();
//
function serialize( library, element ) {
if ( library[ element.uuid ] === undefined ) {
library[ element.uuid ] = element.toJSON( meta );
}
return element.uuid;
}
if ( this.geometry !== undefined ) {
object.geometry = serialize( meta.geometries, this.geometry );
}
if ( this.material !== undefined ) {
if ( Array.isArray( this.material ) ) {
var uuids = [];
for ( var i = 0, l = this.material.length; i < l; i ++ ) {
uuids.push( serialize( meta.materials, this.material[ i ] ) );
}
object.material = uuids;
} else {
object.material = serialize( meta.materials, this.material );
}
}
//
if ( this.children.length > 0 ) {
object.children = [];
for ( var i = 0; i < this.children.length; i ++ ) {
object.children.push( this.children[ i ].toJSON( meta ).object );
}
}
if ( isRootObject ) {
var geometries = extractFromCache( meta.geometries );
var materials = extractFromCache( meta.materials );
var textures = extractFromCache( meta.textures );
var images = extractFromCache( meta.images );
if ( geometries.length > 0 ) output.geometries = geometries;
if ( materials.length > 0 ) output.materials = materials;
if ( textures.length > 0 ) output.textures = textures;
if ( images.length > 0 ) output.images = images;
}
output.object = object;
return output;
// extract data from the cache hash
// remove metadata on each item
// and return as array
function extractFromCache( cache ) {
var values = [];
for ( var key in cache ) {
var data = cache[ key ];
delete data.metadata;
values.push( data );
}
return values;
}
},
clone: function ( recursive ) {
return new this.constructor().copy( this, recursive );
},
copy: function ( source, recursive ) {
if ( recursive === undefined ) recursive = true;
this.name = source.name;
this.up.copy( source.up );
this.position.copy( source.position );
this.quaternion.copy( source.quaternion );
this.scale.copy( source.scale );
this.matrix.copy( source.matrix );
this.matrixWorld.copy( source.matrixWorld );
this.matrixAutoUpdate = source.matrixAutoUpdate;
this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
this.layers.mask = source.layers.mask;
this.visible = source.visible;
this.castShadow = source.castShadow;
this.receiveShadow = source.receiveShadow;
this.frustumCulled = source.frustumCulled;
this.renderOrder = source.renderOrder;
this.userData = JSON.parse( JSON.stringify( source.userData ) );
if ( recursive === true ) {
for ( var i = 0; i < source.children.length; i ++ ) {
var child = source.children[ i ];
this.add( child.clone() );
}
}
return this;
}
} );
export { Object3D };
| carlosanunes/three.js | src/core/Object3D.js | JavaScript | mit | 13,558 |
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2001-2020 Intel Corporation
*/
/*
* 82542 Gigabit Ethernet Controller
*/
#include "e1000_api.h"
STATIC s32 e1000_init_phy_params_82542(struct e1000_hw *hw);
STATIC s32 e1000_init_nvm_params_82542(struct e1000_hw *hw);
STATIC s32 e1000_init_mac_params_82542(struct e1000_hw *hw);
STATIC s32 e1000_get_bus_info_82542(struct e1000_hw *hw);
STATIC s32 e1000_reset_hw_82542(struct e1000_hw *hw);
STATIC s32 e1000_init_hw_82542(struct e1000_hw *hw);
STATIC s32 e1000_setup_link_82542(struct e1000_hw *hw);
STATIC s32 e1000_led_on_82542(struct e1000_hw *hw);
STATIC s32 e1000_led_off_82542(struct e1000_hw *hw);
STATIC int e1000_rar_set_82542(struct e1000_hw *hw, u8 *addr, u32 index);
STATIC void e1000_clear_hw_cntrs_82542(struct e1000_hw *hw);
STATIC s32 e1000_read_mac_addr_82542(struct e1000_hw *hw);
/**
* e1000_init_phy_params_82542 - Init PHY func ptrs.
* @hw: pointer to the HW structure
**/
STATIC s32 e1000_init_phy_params_82542(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val = E1000_SUCCESS;
DEBUGFUNC("e1000_init_phy_params_82542");
phy->type = e1000_phy_none;
return ret_val;
}
/**
* e1000_init_nvm_params_82542 - Init NVM func ptrs.
* @hw: pointer to the HW structure
**/
STATIC s32 e1000_init_nvm_params_82542(struct e1000_hw *hw)
{
struct e1000_nvm_info *nvm = &hw->nvm;
DEBUGFUNC("e1000_init_nvm_params_82542");
nvm->address_bits = 6;
nvm->delay_usec = 50;
nvm->opcode_bits = 3;
nvm->type = e1000_nvm_eeprom_microwire;
nvm->word_size = 64;
/* Function Pointers */
nvm->ops.read = e1000_read_nvm_microwire;
nvm->ops.release = e1000_stop_nvm;
nvm->ops.write = e1000_write_nvm_microwire;
nvm->ops.update = e1000_update_nvm_checksum_generic;
nvm->ops.validate = e1000_validate_nvm_checksum_generic;
return E1000_SUCCESS;
}
/**
* e1000_init_mac_params_82542 - Init MAC func ptrs.
* @hw: pointer to the HW structure
**/
STATIC s32 e1000_init_mac_params_82542(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
DEBUGFUNC("e1000_init_mac_params_82542");
/* Set media type */
hw->phy.media_type = e1000_media_type_fiber;
/* Set mta register count */
mac->mta_reg_count = 128;
/* Set rar entry count */
mac->rar_entry_count = E1000_RAR_ENTRIES;
/* Function pointers */
/* bus type/speed/width */
mac->ops.get_bus_info = e1000_get_bus_info_82542;
/* function id */
mac->ops.set_lan_id = e1000_set_lan_id_multi_port_pci;
/* reset */
mac->ops.reset_hw = e1000_reset_hw_82542;
/* hw initialization */
mac->ops.init_hw = e1000_init_hw_82542;
/* link setup */
mac->ops.setup_link = e1000_setup_link_82542;
/* phy/fiber/serdes setup */
mac->ops.setup_physical_interface =
e1000_setup_fiber_serdes_link_generic;
/* check for link */
mac->ops.check_for_link = e1000_check_for_fiber_link_generic;
/* multicast address update */
mac->ops.update_mc_addr_list = e1000_update_mc_addr_list_generic;
/* writing VFTA */
mac->ops.write_vfta = e1000_write_vfta_generic;
/* clearing VFTA */
mac->ops.clear_vfta = e1000_clear_vfta_generic;
/* read mac address */
mac->ops.read_mac_addr = e1000_read_mac_addr_82542;
/* set RAR */
mac->ops.rar_set = e1000_rar_set_82542;
/* turn on/off LED */
mac->ops.led_on = e1000_led_on_82542;
mac->ops.led_off = e1000_led_off_82542;
/* clear hardware counters */
mac->ops.clear_hw_cntrs = e1000_clear_hw_cntrs_82542;
/* link info */
mac->ops.get_link_up_info =
e1000_get_speed_and_duplex_fiber_serdes_generic;
return E1000_SUCCESS;
}
/**
* e1000_init_function_pointers_82542 - Init func ptrs.
* @hw: pointer to the HW structure
*
* Called to initialize all function pointers and parameters.
**/
void e1000_init_function_pointers_82542(struct e1000_hw *hw)
{
DEBUGFUNC("e1000_init_function_pointers_82542");
hw->mac.ops.init_params = e1000_init_mac_params_82542;
hw->nvm.ops.init_params = e1000_init_nvm_params_82542;
hw->phy.ops.init_params = e1000_init_phy_params_82542;
}
/**
* e1000_get_bus_info_82542 - Obtain bus information for adapter
* @hw: pointer to the HW structure
*
* This will obtain information about the HW bus for which the
* adapter is attached and stores it in the hw structure.
**/
STATIC s32 e1000_get_bus_info_82542(struct e1000_hw *hw)
{
DEBUGFUNC("e1000_get_bus_info_82542");
hw->bus.type = e1000_bus_type_pci;
hw->bus.speed = e1000_bus_speed_unknown;
hw->bus.width = e1000_bus_width_unknown;
return E1000_SUCCESS;
}
/**
* e1000_reset_hw_82542 - Reset hardware
* @hw: pointer to the HW structure
*
* This resets the hardware into a known state.
**/
STATIC s32 e1000_reset_hw_82542(struct e1000_hw *hw)
{
struct e1000_bus_info *bus = &hw->bus;
s32 ret_val = E1000_SUCCESS;
u32 ctrl;
DEBUGFUNC("e1000_reset_hw_82542");
if (hw->revision_id == E1000_REVISION_2) {
DEBUGOUT("Disabling MWI on 82542 rev 2\n");
e1000_pci_clear_mwi(hw);
}
DEBUGOUT("Masking off all interrupts\n");
E1000_WRITE_REG(hw, E1000_IMC, 0xffffffff);
E1000_WRITE_REG(hw, E1000_RCTL, 0);
E1000_WRITE_REG(hw, E1000_TCTL, E1000_TCTL_PSP);
E1000_WRITE_FLUSH(hw);
/*
* Delay to allow any outstanding PCI transactions to complete before
* resetting the device
*/
msec_delay(10);
ctrl = E1000_READ_REG(hw, E1000_CTRL);
DEBUGOUT("Issuing a global reset to 82542/82543 MAC\n");
E1000_WRITE_REG(hw, E1000_CTRL, ctrl | E1000_CTRL_RST);
hw->nvm.ops.reload(hw);
msec_delay(2);
E1000_WRITE_REG(hw, E1000_IMC, 0xffffffff);
E1000_READ_REG(hw, E1000_ICR);
if (hw->revision_id == E1000_REVISION_2) {
if (bus->pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
e1000_pci_set_mwi(hw);
}
return ret_val;
}
/**
* e1000_init_hw_82542 - Initialize hardware
* @hw: pointer to the HW structure
*
* This inits the hardware readying it for operation.
**/
STATIC s32 e1000_init_hw_82542(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
struct e1000_dev_spec_82542 *dev_spec = &hw->dev_spec._82542;
s32 ret_val = E1000_SUCCESS;
u32 ctrl;
u16 i;
DEBUGFUNC("e1000_init_hw_82542");
/* Disabling VLAN filtering */
E1000_WRITE_REG(hw, E1000_VET, 0);
mac->ops.clear_vfta(hw);
/* For 82542 (rev 2.0), disable MWI and put the receiver into reset */
if (hw->revision_id == E1000_REVISION_2) {
DEBUGOUT("Disabling MWI on 82542 rev 2.0\n");
e1000_pci_clear_mwi(hw);
E1000_WRITE_REG(hw, E1000_RCTL, E1000_RCTL_RST);
E1000_WRITE_FLUSH(hw);
msec_delay(5);
}
/* Setup the receive address. */
e1000_init_rx_addrs_generic(hw, mac->rar_entry_count);
/* For 82542 (rev 2.0), take the receiver out of reset and enable MWI */
if (hw->revision_id == E1000_REVISION_2) {
E1000_WRITE_REG(hw, E1000_RCTL, 0);
E1000_WRITE_FLUSH(hw);
msec_delay(1);
if (hw->bus.pci_cmd_word & CMD_MEM_WRT_INVALIDATE)
e1000_pci_set_mwi(hw);
}
/* Zero out the Multicast HASH table */
DEBUGOUT("Zeroing the MTA\n");
for (i = 0; i < mac->mta_reg_count; i++)
E1000_WRITE_REG_ARRAY(hw, E1000_MTA, i, 0);
/*
* Set the PCI priority bit correctly in the CTRL register. This
* determines if the adapter gives priority to receives, or if it
* gives equal priority to transmits and receives.
*/
if (dev_spec->dma_fairness) {
ctrl = E1000_READ_REG(hw, E1000_CTRL);
E1000_WRITE_REG(hw, E1000_CTRL, ctrl | E1000_CTRL_PRIOR);
}
/* Setup link and flow control */
ret_val = e1000_setup_link_82542(hw);
/*
* Clear all of the statistics registers (clear on read). It is
* important that we do this after we have tried to establish link
* because the symbol error count will increment wildly if there
* is no link.
*/
e1000_clear_hw_cntrs_82542(hw);
return ret_val;
}
/**
* e1000_setup_link_82542 - Setup flow control and link settings
* @hw: pointer to the HW structure
*
* Determines which flow control settings to use, then configures flow
* control. Calls the appropriate media-specific link configuration
* function. Assuming the adapter has a valid link partner, a valid link
* should be established. Assumes the hardware has previously been reset
* and the transmitter and receiver are not enabled.
**/
STATIC s32 e1000_setup_link_82542(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
s32 ret_val;
DEBUGFUNC("e1000_setup_link_82542");
ret_val = e1000_set_default_fc_generic(hw);
if (ret_val)
goto out;
hw->fc.requested_mode &= ~e1000_fc_tx_pause;
if (mac->report_tx_early)
hw->fc.requested_mode &= ~e1000_fc_rx_pause;
/*
* Save off the requested flow control mode for use later. Depending
* on the link partner's capabilities, we may or may not use this mode.
*/
hw->fc.current_mode = hw->fc.requested_mode;
DEBUGOUT1("After fix-ups FlowControl is now = %x\n",
hw->fc.current_mode);
/* Call the necessary subroutine to configure the link. */
ret_val = mac->ops.setup_physical_interface(hw);
if (ret_val)
goto out;
/*
* Initialize the flow control address, type, and PAUSE timer
* registers to their default values. This is done even if flow
* control is disabled, because it does not hurt anything to
* initialize these registers.
*/
DEBUGOUT("Initializing Flow Control address, type and timer regs\n");
E1000_WRITE_REG(hw, E1000_FCAL, FLOW_CONTROL_ADDRESS_LOW);
E1000_WRITE_REG(hw, E1000_FCAH, FLOW_CONTROL_ADDRESS_HIGH);
E1000_WRITE_REG(hw, E1000_FCT, FLOW_CONTROL_TYPE);
E1000_WRITE_REG(hw, E1000_FCTTV, hw->fc.pause_time);
ret_val = e1000_set_fc_watermarks_generic(hw);
out:
return ret_val;
}
/**
* e1000_led_on_82542 - Turn on SW controllable LED
* @hw: pointer to the HW structure
*
* Turns the SW defined LED on.
**/
STATIC s32 e1000_led_on_82542(struct e1000_hw *hw)
{
u32 ctrl = E1000_READ_REG(hw, E1000_CTRL);
DEBUGFUNC("e1000_led_on_82542");
ctrl |= E1000_CTRL_SWDPIN0;
ctrl |= E1000_CTRL_SWDPIO0;
E1000_WRITE_REG(hw, E1000_CTRL, ctrl);
return E1000_SUCCESS;
}
/**
* e1000_led_off_82542 - Turn off SW controllable LED
* @hw: pointer to the HW structure
*
* Turns the SW defined LED off.
**/
STATIC s32 e1000_led_off_82542(struct e1000_hw *hw)
{
u32 ctrl = E1000_READ_REG(hw, E1000_CTRL);
DEBUGFUNC("e1000_led_off_82542");
ctrl &= ~E1000_CTRL_SWDPIN0;
ctrl |= E1000_CTRL_SWDPIO0;
E1000_WRITE_REG(hw, E1000_CTRL, ctrl);
return E1000_SUCCESS;
}
/**
* e1000_rar_set_82542 - Set receive address register
* @hw: pointer to the HW structure
* @addr: pointer to the receive address
* @index: receive address array register
*
* Sets the receive address array register at index to the address passed
* in by addr.
**/
STATIC int e1000_rar_set_82542(struct e1000_hw *hw, u8 *addr, u32 index)
{
u32 rar_low, rar_high;
DEBUGFUNC("e1000_rar_set_82542");
/*
* HW expects these in little endian so we reverse the byte order
* from network order (big endian) to little endian
*/
rar_low = ((u32) addr[0] | ((u32) addr[1] << 8) |
((u32) addr[2] << 16) | ((u32) addr[3] << 24));
rar_high = ((u32) addr[4] | ((u32) addr[5] << 8));
/* If MAC address zero, no need to set the AV bit */
if (rar_low || rar_high)
rar_high |= E1000_RAH_AV;
E1000_WRITE_REG_ARRAY(hw, E1000_RA, (index << 1), rar_low);
E1000_WRITE_REG_ARRAY(hw, E1000_RA, ((index << 1) + 1), rar_high);
return E1000_SUCCESS;
}
/**
* e1000_translate_register_82542 - Translate the proper register offset
* @reg: e1000 register to be read
*
* Registers in 82542 are located in different offsets than other adapters
* even though they function in the same manner. This function takes in
* the name of the register to read and returns the correct offset for
* 82542 silicon.
**/
u32 e1000_translate_register_82542(u32 reg)
{
/*
* Some of the 82542 registers are located at different
* offsets than they are in newer adapters.
* Despite the difference in location, the registers
* function in the same manner.
*/
switch (reg) {
case E1000_RA:
reg = 0x00040;
break;
case E1000_RDTR:
reg = 0x00108;
break;
case E1000_RDBAL(0):
reg = 0x00110;
break;
case E1000_RDBAH(0):
reg = 0x00114;
break;
case E1000_RDLEN(0):
reg = 0x00118;
break;
case E1000_RDH(0):
reg = 0x00120;
break;
case E1000_RDT(0):
reg = 0x00128;
break;
case E1000_RDBAL(1):
reg = 0x00138;
break;
case E1000_RDBAH(1):
reg = 0x0013C;
break;
case E1000_RDLEN(1):
reg = 0x00140;
break;
case E1000_RDH(1):
reg = 0x00148;
break;
case E1000_RDT(1):
reg = 0x00150;
break;
case E1000_FCRTH:
reg = 0x00160;
break;
case E1000_FCRTL:
reg = 0x00168;
break;
case E1000_MTA:
reg = 0x00200;
break;
case E1000_TDBAL(0):
reg = 0x00420;
break;
case E1000_TDBAH(0):
reg = 0x00424;
break;
case E1000_TDLEN(0):
reg = 0x00428;
break;
case E1000_TDH(0):
reg = 0x00430;
break;
case E1000_TDT(0):
reg = 0x00438;
break;
case E1000_TIDV:
reg = 0x00440;
break;
case E1000_VFTA:
reg = 0x00600;
break;
case E1000_TDFH:
reg = 0x08010;
break;
case E1000_TDFT:
reg = 0x08018;
break;
default:
break;
}
return reg;
}
/**
* e1000_clear_hw_cntrs_82542 - Clear device specific hardware counters
* @hw: pointer to the HW structure
*
* Clears the hardware counters by reading the counter registers.
**/
STATIC void e1000_clear_hw_cntrs_82542(struct e1000_hw *hw)
{
DEBUGFUNC("e1000_clear_hw_cntrs_82542");
e1000_clear_hw_cntrs_base_generic(hw);
E1000_READ_REG(hw, E1000_PRC64);
E1000_READ_REG(hw, E1000_PRC127);
E1000_READ_REG(hw, E1000_PRC255);
E1000_READ_REG(hw, E1000_PRC511);
E1000_READ_REG(hw, E1000_PRC1023);
E1000_READ_REG(hw, E1000_PRC1522);
E1000_READ_REG(hw, E1000_PTC64);
E1000_READ_REG(hw, E1000_PTC127);
E1000_READ_REG(hw, E1000_PTC255);
E1000_READ_REG(hw, E1000_PTC511);
E1000_READ_REG(hw, E1000_PTC1023);
E1000_READ_REG(hw, E1000_PTC1522);
}
/**
* e1000_read_mac_addr_82542 - Read device MAC address
* @hw: pointer to the HW structure
*
* Reads the device MAC address from the EEPROM and stores the value.
**/
s32 e1000_read_mac_addr_82542(struct e1000_hw *hw)
{
s32 ret_val = E1000_SUCCESS;
u16 offset, nvm_data, i;
DEBUGFUNC("e1000_read_mac_addr");
for (i = 0; i < ETH_ADDR_LEN; i += 2) {
offset = i >> 1;
ret_val = hw->nvm.ops.read(hw, offset, 1, &nvm_data);
if (ret_val) {
DEBUGOUT("NVM Read Error\n");
goto out;
}
hw->mac.perm_addr[i] = (u8)(nvm_data & 0xFF);
hw->mac.perm_addr[i+1] = (u8)(nvm_data >> 8);
}
for (i = 0; i < ETH_ADDR_LEN; i++)
hw->mac.addr[i] = hw->mac.perm_addr[i];
out:
return ret_val;
}
| john-mcnamara-intel/dpdk | drivers/net/e1000/base/e1000_82542.c | C | mit | 14,510 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ConnectivitySource(Model):
"""Parameters that define the source of the connection.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource from which a
connectivity check will be initiated.
:type resource_id: str
:param port: The source port from which a connectivity check will be
performed.
:type port: int
"""
_validation = {
'resource_id': {'required': True},
}
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None:
super(ConnectivitySource, self).__init__(**kwargs)
self.resource_id = resource_id
self.port = port
| lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/connectivity_source_py3.py | Python | mit | 1,352 |
export default window['%testCafeAutomation%'];
| AlexanderMoskovkin/testcafe | src/client/driver/deps/testcafe-automation.js | JavaScript | mit | 47 |
<div id="widgetinteract-{{widget.pk}}" rel="{{widget.pk}}" class="widgetinteractdialog" title="{{widget.name}} interaction" width="400" height="300">
<form>
<label for="class_name{{widget.pk}}">New class attribute name</label>
<input type="text" name="class_name{{widget.pk}}" value="{{class_name}}"/>
{% for class_val in class_values %}
<label for="class{{forloop.counter0}}{{widget.pk}}">Class label for set on signal #{{forloop.counter}}</label>
<input type="text" name="class{{forloop.counter0}}{{widget.pk}}" value="{{class_val}}"/>
{% endfor %}
<input type="checkbox" name="replace{{widget.pk}}" {% if replace %}checked{% endif %}/>
<label for="replace{{widget.pk}}">Replace existing class</label>
<input type="hidden" name="widget_id" value="{{widget.pk}}">
</form>
<script type="text/javascript">
</script>
</div> | xflows/clowdflows | workflows/subgroup_discovery/templates/interactions/table_from_sets.html | HTML | mit | 865 |
---
title: OnClientDropDownSelectedIndexChanging
page_title: OnClientDropDownSelectedIndexChanging | RadRibbonBar for ASP.NET AJAX Documentation
description: OnClientDropDownSelectedIndexChanging
slug: ribbonbar/client-side-programming/events/onclientdropdownselectedindexchanging
tags: onclientdropdownselectedindexchanging
published: True
position: 18
---
# OnClientDropDownSelectedIndexChanging
##
The **OnClientDropDownSelectedIndexChanging** client-side event occurs when the user is changing the selected item in the DropDown.
1. The instance of the **ribbonbar** firing the event
1. An **eventArgs** parameter containing the following methods:
* get_dropDown()
* get_index()
* get_cance()
* set_cancel()
| LanceMcCarthy/ajax-docs | controls/ribbonbar/client-side-programming/events/onclientdropdownselectedindexchanging.md | Markdown | mit | 756 |
---
layout: doc
title: Edição Avançada
permalink: /pt/josm/aerial-imagery/
lang: pt
category: josm
---
Edição Avançada
===============
Nos capítulos anteriores aprendeu a desenhar pontos, linhas, e formas
(shapes) no JOSM. como abrir os pontos de referência (waypoints) e
caminhos (tracks) do seu GPS, e como descarregar, editar, e carregar as
suas modificações no OpenStreetMap. Neste capítulo, descreveremos em
mais detalhe algumas das características do JOSM, de forma a poder ir
para lá das simples ferramentas de edição e ter uma melhor compreensão
do software. Note que embora este capítulo não seja extremamente
avançado, é um degrau acima dos capítulos anteriores. Se achar que não
entendeu plenamente as lições anteriores, talvez queira praticar um
pouco mais antes de continuar.
Uma visita ao JOSM
------------------

- JOSM tem muitos elementos diferentes. Já está familiarizado com a
janela principal do JOSM - Isto é a janela do mapa, e é onde a maior
parte da acção se desenrola. Aqui visualiza, edita, e adiciona dados
ao OpenStreetMap.
- Para a direita da janela do mapa existe uma série de painéis,
servindo cada um para uma coisa diferente.Tipicamente, quando
instala pela primeira vez o JOSM,vários painéis são mostrados por
omissão, tais como “Layers” (camadas), “Properties”
(características), e “Selection” (seleção). Quando selecciona um
ponto, linha, ou forma, na janela do mapa, isso será mostrado no
painel “Selection”. Informação acerca do objecto será mostrada no
painel “Properties” (características), e o nome de utilizador do
autor desse objecto será mostrado no painel “Authors” (autores).
- Do lado esquerdo do JOSM, existem várias barras de ferramentas, que
apresentam muitos botões. No topo desta barra estão diferentes
botões que mudam o que pode fazer com o rato. Já está familiarizado
com os dois primeiros, a ferramenta “Select” (selecionar) e a
ferramenta “Draw” (desenhar). As outras ferramentas tornam mais
fácil fazer “zoom” (aumentar e diminuir o mapa), apagar um objecto,
desenhar uma forma (shape), ou criar uma linha paralela a outra
linha.
- Por baixo destas ferramentas existem muitos mais botões. Estes
botões controlam o que vê do lado direito do JOSM. Utilizando estes
botões pode abrir e fechar as caixas à direita, como por exemplo,
características (properties), seleção (selection), e autor (author).
Camadas (Layers) do JOSM
------------------------
- Abra o ficheiro do seu GPS e descarregue dados do OpenStreetMap, se
ainda não o fez. Repare que quando abre um ficheiro, ou adiciona
“Walking Papers”, ou descarrega dados do OpenStreetMap, outro item é
adicionado ao painel “Layers” (camadas), no lado direito do JOSM. O
seu painel de camadas (Layers) deverá ter o seguinte aspecto::

- Cada item nesta lista representa uma fonte diferente de dados que
pode abrir na sua janela de mapa. No exemplo acima, “Data Layer 2”
são os dados do OpenStreetMap que queremos editar. “Markers”
(marcadores) são os pontos de referência (waypoints) do GPS, e “30
Juni 2011.gpx” é o caminho (track) do GPS. Finalmente, “Walking
Papers” é a camada ( layer) criada quando adicionei o meu “Walking
Paper” ao JOSM. Pode adicionar a camada de imagens do Bing,que
mostra imagens de satélite, clicando em “Imagery” no menu de topo do
JOSM e seleccionando “Bing Sat”.
- Para esconder uma destas camadas (layers), selecione uma delas com o
rato e clique o botão “Show/Hide” (Mostrar/Esconder) que tem o
seguinte aspecto:

- Deverá ver a camada que selecionou desaparecer na janela do mapa.
Clique no botão novamente, e ela deverá reaparecer.
- Pode fechar uma camada selecionando-a e utilizando o botão de apagar
(delete):

- Por último, é importante saber quesó pode editar a camada que é
considerada activa pelo JOSM. Se não conseguir editar o mapa que
está na janela do mapa, é provavelmente porque não tem a camada
correta activa. A maioria das camadas, como a dos pontos GPS, a do
“Walking Papers”, e as de imagens de satélite, não podem ser
editadas. As únicas camadas que podem ser editadas são as de dados
do OpenStreetMap, que são normalmente chamadas de “Data Layer”.
- Para tornar uma camada activa, selecione-a no painel “Layers”
(camadas), e clique no botão “Activate” (activar):

Gravando ficheiros OSM
----------------------
- Algumas vezes quando descarrega alguns dados OSM, pode querer
guardá-los de forma apoder editá-los “offline” (sem estar ligado à
Internet), e depois carregá-los mais tarde quando tiver o acesso à
Internet novamente activo.
- Para gravar um ficheiro OSM, certifique-se que é a camada activa no
painel “Layers” (camadas). Clique “File” (ficheiro) no menu do topo,
e clique “Save” (guardar), Escolha uma localização para o ficheiro e
escolha um nome para ele. Pode também guardar dados clicando no
seguinte botão

- Agora pode fechar o JOSM e os seus dados serão guardados, sem se
perderem. Quando quiser abrir o ficheiro novamente, abra
simplesmente o JOSM, vá ao menu “File” (ficheiro), e clique “Open”
(abrir).
Ferramentas de Desenho Adicionais
---------------------------------
- O JOSM tem algumas ferramentas adicionais para tornar mais fácil
desenhar linhas e formas. Estas ferramentas encontram-se no menu
“Tools” (ferramentas) no topo do JOSM.

- De forma a aplicar as funções deste menu, tem de primeiro selecionar
um ponto, linha, ou forma na janela do mapa. Algumas das funções
mais úteis são descritas de seguida:
- Split Way (separar via)- Isto permite-lhe dividir uma linha em duas
linhas separadas. Isto é útil se quiser adicionar atributos
diferentes a diferentes partes da estrada. Para utilizar esta
função, selecione um ponto no meio da linha a quebrar, selecione
“Split Way” (quebrar via) do menu “Tools” (ferramentas), e a sua
linha deverá ser quebrada em duas.
- Combine Way (combinar via) - Isto faz o oposto do anterior “Split
Way”. Para combinar duas linhas numa só, elas têm de partilhar um
ponto único. Para utilizar esta função, selecione ambas as linhas
que quer combinar. Pode selecionar mais de um objecto pressionando a
tecla “SHIFT” no seu teclado e clicando em cada linha. Quando tiver
selecionado ambas as linhas, escolha “Combine Way” do menu “Tools”
(ferramentas).
- Reverse Way (inverter via) - Isto mudará a direção da linha. Se a
sua linha representa uma estrada que tem um só sentido, pode querer
modificar a sua direção. Noutros casos, a direção não importa.
- Simplify Way (simplificar via) - Se a sua linha tiver demasiados
pontos e quiser torná-la mais simples, isto removerá alguns pontos
da linha.
- Align Nodes in Circle (alinhar pontos em círculo)- Se está a tentar
fazer uma forma circular, desenhe o círculo o melhor que conseguir e
depois selecione esta função. Ela ajudará a colocar os seus pontos
num círculo.
- Align Nodes in Line (alinhar pontos em linha)- Esta função alinhará
uma série de pontos numa linha reta.
- Orthogonalize Shape (ortogonalizar forma) - Esta função é muito útil
para desenhar edifícios. Depois de desenhar um edifício, esta função
irá ajustá-la de forma a ter cantos retos.
Etiquetas (Tags)
----------------
- Quando desenhar um ponto, linha, ou forma, ela é criada numa
localização, mas sem informação acerca do que é. Por outras
palavras, sabemos onde está, mas não o que é. Anteriormente,
estivemos a utilizar items do menu “Presets” (pré-configurações)
para definir o que é.
- A forma do OpenStreetMap saber o que é um objecto é pela utilização
de etiquetas (tags). Uma etiqueta (tag) é como um rótulo que pode
colocar em algo. Por exemplo, se desenhar um quadrado, é só um
quadrado. Mas então adiciono múltiplas etiquetas (tags) que
descrevem aquilo que é:
- este quadrado é um edifício (building)
- o nome do edifício é “Torre dos Clérigos”
- o edifício tem 16 andares de altura
- Pode adicionar tantas etiquetas (tags) a um objecto quantas quiser.
As “Tags” são guardadas como pares de texto, chamadas as
keys (chaves) e values (valores). No OpenStreetMap, as etiquetas
(tags) escritas acima seriam na realidade:
- building = yes
- name = Torre dos Clérigos
- building:levels = 16
- Se selecionar um objecto no JOSM, pode ver todas as etiquetas que
estão ligadas a ele no painel “Properties” (características) à
direita.

- Pode adicionar, editar, e apagar estas etiquetas (tags) a partir
deste painel. As etiquetas são tradicionalmente em inglês, pelo que
é normalmente melhor utilizar o menu “Presets” (pré-configurações)
para evitar erros de grafia. Este painel é útil para inserir
etiquetas que não estejam no menu “Presets” (pré-configurações) por
serem pouco utilizadas ou serem recentes (sendo um sistema aberto, o
OpenStreetMap permite ir criando novas etiquetas conforme a
comunidade vai achando útil ou pertinente).
Atalhos de Teclado
------------------
- Por vezes pode ser chato clicar repetidamente para selecionar opções
diferentes e menus no JOSM. Felizmente existem teclas de atalho no
teclado que lhe permitem executar muitas das tarefas comuns de forma
mais expedita. Aqui tem uma lista de algumas das teclas de atalho
vulgarmente mais utilizadas, juntamente com o que fazem:
- s - Escolher a ferramenta “Select” (selecionar)
- a - Escolher a ferramenta “Draw”
- z - Escolher a ferramenta “Zoom”
- + (mais) - “Zoom In” Aumentar o mapa
- - (menos) - “Zoom Out” Diminuir o mapa
- p - “Split Way” Quebrar caminho
- c - “Combine Way” Combinar caminho
- o - Alinhar em círculo
- l - Alinhar em linha
- q - Ortogonalizar (forçar cantos em ângulo reto)
Sumário
-------
Como pode ver existem muitas características adicionais que fazem o JOSM
uma ferramenta poderosa para criar mapas. Lembre-se de que quanto mais
praticar com estas ferramentas, melhor se irá tornar a adicionar
informação ao OpenStreetMap.
No último capítulo iremos nos afastar do JOSM, e dar uma olhada a outros
projectos interessantes que utilizam dados do OpenStreetMap, e aprender
como podemos continuar a aprender acerca do OSM.
| feyeandal/test | _posts/pt/josm/1900-04-15-aerial-imagery.md | Markdown | mit | 11,217 |
require 'gmail_xoauth'
module Gmail
module Client
class XOAuth < Base
attr_reader :token
attr_reader :secret
attr_reader :consumer_key
attr_reader :consumer_secret
def initialize(username, options={})
@token = options.delete(:token)
@secret = options.delete(:secret)
@consumer_key = options.delete(:consumer_key)
@consumer_secret = options.delete(:consumer_secret)
super(username, options)
end
def login(raise_errors=false)
@imap and @logged_in = (login = @imap.authenticate('XOAUTH', username,
:consumer_key => consumer_key,
:consumer_secret => consumer_secret,
:token => token,
:token_secret => secret
)) && login.name == 'OK'
rescue Net::IMAP::NoResponseError => e
if raise_errors
message = "Couldn't login to given GMail account: #{username}"
message += " (#{e.response.data.text.strip})"
raise(AuthorizationError.new(e.response), message, e.backtrace)
end
end
def smtp_settings
[:smtp, {
:address => GMAIL_SMTP_HOST,
:port => GMAIL_SMTP_PORT,
:domain => mail_domain,
:user_name => username,
:password => {
:consumer_key => consumer_key,
:consumer_secret => consumer_secret,
:token => token,
:token_secret => secret
},
:authentication => :xoauth,
:enable_starttls_auto => true
}]
end
end # XOAuth
register :xoauth, XOAuth
end # Client
end # Gmail
| jamescallmebrent/gmail | lib/gmail/client/xoauth.rb | Ruby | mit | 1,692 |
// sensible server which advertises itself via Bonjour
// NODE INCLUDES
var dgram = require ("dgram");
var fs = require ("fs");
var http = require ("http");
var os = require ("os");
var url = require ("url");
// REGULAR JS INCLUDES
// assume that sensible.js lives in the same directory as our mainline
var code = fs.readFileSync (require ("path").dirname (process.argv [1]) + "/sensible.js");
eval (code.toString ());
// MAINLINE
sensible.ApplicationFactory.createApplication
(
function (inError)
{
if (inError)
{
console.error ("error during sensible application startup");
console.error (inError);
}
else
{
console.log ("sensible application startup");
}
}
);
// called just before sensible.Application.start()
sensible.node.Application.prototype.onBeforeStart = function (inCallback)
{
console.log ("node.Application.onBeforeStart()");
inCallback ();
}
// called just after sensible.Application.start()
sensible.node.Application.prototype.onAfterStart = function (inCallback)
{
console.log ("node.Application.onAfterStart()");
inCallback ();
}
| gbraad/sensible | apps/node/waiter/sensible-app.js | JavaScript | mit | 1,089 |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Preview\Understand\Assistant;
use Twilio\InstanceContext;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;
/**
* PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
*/
class QueryContext extends InstanceContext {
/**
* Initialize the QueryContext
*
* @param \Twilio\Version $version Version that contains the resource
* @param string $assistantSid The assistant_sid
* @param string $sid The sid
* @return \Twilio\Rest\Preview\Understand\Assistant\QueryContext
*/
public function __construct(Version $version, $assistantSid, $sid) {
parent::__construct($version);
// Path Solution
$this->solution = array('assistantSid' => $assistantSid, 'sid' => $sid, );
$this->uri = '/Assistants/' . rawurlencode($assistantSid) . '/Queries/' . rawurlencode($sid) . '';
}
/**
* Fetch a QueryInstance
*
* @return QueryInstance Fetched QueryInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch() {
$params = Values::of(array());
$payload = $this->version->fetch(
'GET',
$this->uri,
$params
);
return new QueryInstance(
$this->version,
$payload,
$this->solution['assistantSid'],
$this->solution['sid']
);
}
/**
* Update the QueryInstance
*
* @param array|Options $options Optional Arguments
* @return QueryInstance Updated QueryInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update($options = array()) {
$options = new Values($options);
$data = Values::of(array('SampleSid' => $options['sampleSid'], 'Status' => $options['status'], ));
$payload = $this->version->update(
'POST',
$this->uri,
array(),
$data
);
return new QueryInstance(
$this->version,
$payload,
$this->solution['assistantSid'],
$this->solution['sid']
);
}
/**
* Deletes the QueryInstance
*
* @return boolean True if delete succeeds, false otherwise
* @throws TwilioException When an HTTP error occurs.
*/
public function delete() {
return $this->version->delete('delete', $this->uri);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Preview.Understand.QueryContext ' . implode(' ', $context) . ']';
}
} | camperjz/trident | upgrade/files/9.0.0.RC8-9.0.0.RC9/files/plugins/Twilio/Rest/Preview/Understand/Assistant/QueryContext.php | PHP | mit | 3,065 |
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use dixonsatit\agencyTheme\assets\AgencyAsset;
/* @var $this \yii\web\View */
/* @var $content string */
AgencyAsset::register($this);
$directoryAsset = Yii::$app->assetManager->getPublishedUrl('@dixonsatit/agencyTheme/dist');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body id="page-top" class="index">
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
| dixonsatit/yii2-agency-theme | views/layouts/_base.php | PHP | mit | 819 |
require 'test_helper'
class InteractionTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| InteractiveIntelligence/DynamicIVR | webservice/test/models/interaction_test.rb | Ruby | mit | 125 |
//===-- X86ELFObjectWriter.cpp - X86 ELF Writer ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/X86FixupKinds.h"
#include "MCTargetDesc/X86MCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
namespace {
class X86ELFObjectWriter : public MCELFObjectTargetWriter {
public:
X86ELFObjectWriter(bool IsELF64, uint8_t OSABI, uint16_t EMachine);
virtual ~X86ELFObjectWriter();
protected:
virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel, bool IsRelocWithSymbol,
int64_t Addend) const;
};
}
X86ELFObjectWriter::X86ELFObjectWriter(bool IsELF64, uint8_t OSABI,
uint16_t EMachine)
: MCELFObjectTargetWriter(IsELF64, OSABI, EMachine,
// Only i386 uses Rel instead of RelA.
/*HasRelocationAddend*/ EMachine != ELF::EM_386) {}
X86ELFObjectWriter::~X86ELFObjectWriter()
{}
unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel,
bool IsRelocWithSymbol,
int64_t Addend) const {
// determine the type of the relocation
MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
unsigned Type;
if (getEMachine() == ELF::EM_X86_64) {
if (IsPCRel) {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case FK_Data_8: Type = ELF::R_X86_64_PC64; break;
case FK_Data_4: Type = ELF::R_X86_64_PC32; break;
case FK_Data_2: Type = ELF::R_X86_64_PC16; break;
case FK_PCRel_8:
assert(Modifier == MCSymbolRefExpr::VK_None);
Type = ELF::R_X86_64_PC64;
break;
case X86::reloc_signed_4byte:
case X86::reloc_riprel_4byte_movq_load:
case X86::reloc_riprel_4byte:
case FK_PCRel_4:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_X86_64_PC32;
break;
case MCSymbolRefExpr::VK_PLT:
Type = ELF::R_X86_64_PLT32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_X86_64_GOTPCREL;
break;
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_X86_64_GOTTPOFF;
break;
case MCSymbolRefExpr::VK_TLSGD:
Type = ELF::R_X86_64_TLSGD;
break;
case MCSymbolRefExpr::VK_TLSLD:
Type = ELF::R_X86_64_TLSLD;
break;
}
break;
case FK_PCRel_2:
assert(Modifier == MCSymbolRefExpr::VK_None);
Type = ELF::R_X86_64_PC16;
break;
case FK_PCRel_1:
assert(Modifier == MCSymbolRefExpr::VK_None);
Type = ELF::R_X86_64_PC8;
break;
}
} else {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case FK_Data_8: Type = ELF::R_X86_64_64; break;
case X86::reloc_signed_4byte:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_X86_64_32S;
break;
case MCSymbolRefExpr::VK_GOT:
Type = ELF::R_X86_64_GOT32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_X86_64_GOTPCREL;
break;
case MCSymbolRefExpr::VK_TPOFF:
Type = ELF::R_X86_64_TPOFF32;
break;
case MCSymbolRefExpr::VK_DTPOFF:
Type = ELF::R_X86_64_DTPOFF32;
break;
}
break;
case FK_Data_4:
Type = ELF::R_X86_64_32;
break;
case FK_Data_2: Type = ELF::R_X86_64_16; break;
case FK_PCRel_1:
case FK_Data_1: Type = ELF::R_X86_64_8; break;
}
}
} else if (getEMachine() == ELF::EM_386) {
if (IsPCRel) {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case X86::reloc_global_offset_table:
Type = ELF::R_386_GOTPC;
break;
case X86::reloc_signed_4byte:
case FK_PCRel_4:
case FK_Data_4:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_386_PC32;
break;
case MCSymbolRefExpr::VK_PLT:
Type = ELF::R_386_PLT32;
break;
}
break;
}
} else {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case X86::reloc_global_offset_table:
Type = ELF::R_386_GOTPC;
break;
// FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
// instead?
case X86::reloc_signed_4byte:
case FK_PCRel_4:
case FK_Data_4:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_386_32;
break;
case MCSymbolRefExpr::VK_GOT:
Type = ELF::R_386_GOT32;
break;
case MCSymbolRefExpr::VK_GOTOFF:
Type = ELF::R_386_GOTOFF;
break;
case MCSymbolRefExpr::VK_TLSGD:
Type = ELF::R_386_TLS_GD;
break;
case MCSymbolRefExpr::VK_TPOFF:
Type = ELF::R_386_TLS_LE_32;
break;
case MCSymbolRefExpr::VK_INDNTPOFF:
Type = ELF::R_386_TLS_IE;
break;
case MCSymbolRefExpr::VK_NTPOFF:
Type = ELF::R_386_TLS_LE;
break;
case MCSymbolRefExpr::VK_GOTNTPOFF:
Type = ELF::R_386_TLS_GOTIE;
break;
case MCSymbolRefExpr::VK_TLSLDM:
Type = ELF::R_386_TLS_LDM;
break;
case MCSymbolRefExpr::VK_DTPOFF:
Type = ELF::R_386_TLS_LDO_32;
break;
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_386_TLS_IE_32;
break;
}
break;
case FK_Data_2: Type = ELF::R_386_16; break;
case FK_PCRel_1:
case FK_Data_1: Type = ELF::R_386_8; break;
}
}
} else
llvm_unreachable("Unsupported ELF machine type.");
return Type;
}
MCObjectWriter *llvm::createX86ELFObjectWriter(raw_ostream &OS,
bool IsELF64,
uint8_t OSABI,
uint16_t EMachine) {
MCELFObjectTargetWriter *MOTW =
new X86ELFObjectWriter(IsELF64, OSABI, EMachine);
return createELFObjectWriter(MOTW, OS, /*IsLittleEndian=*/true);
}
| dbrumley/recfi | llvm-3.3/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp | C++ | mit | 7,285 |
##
# = JavaScript Object Notation (JSON)
#
# JSON is a lightweight data-interchange format. It is easy for us
# humans to read and write. Plus, equally simple for machines to generate or parse.
# JSON is completely language agnostic, making it the ideal interchange format.
#
# Built on two universally available structures:
# 1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array.
# 2. An orderd list of values. More commonly named as an _array_, vector, sequence, or list.
#
# To read more about JSON visit: http://json.org
#
# == Parsing JSON
#
# To parse a JSON string received by another application, or generated within
# your existing application:
#
# require 'json'
#
# my_hash = JSON.parse('{"hello": "goodbye"}')
# puts my_hash["hello"] => "goodbye"
#
# Notice the extra quotes <tt>''</tt> around the hash notation. Ruby expects
# the argument to be a string and can't convert objects like a hash or array.
#
# Ruby converts your string into a hash
#
# == Generating JSON
#
# Creating a JSON string for communication or serialization is
# just as simple.
#
# require 'json'
#
# my_hash = {:hello => "goodbye"}
# puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
#
# Or an alternative way:
#
# require 'json'
# puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
#
# <tt>JSON.generate</tt> only allows objects or arrays to be converted
# to JSON syntax. While <tt>to_json</tt> accepts many Ruby classes
# even though it only acts a method for serialization:
#
# require 'json'
#
# 1.to_json => "1"
#
require 'json/common'
module JSON
require 'json/version'
begin
require 'json/ext'
rescue LoadError
require 'json/pure'
end
end
| smgt/alfred-workflow-rubygems | vendor/json_pure/json.rb | Ruby | mit | 1,783 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../../libc/constant.POSIX_FADV_WILLNEED.html">
</head>
<body>
<p>Redirecting to <a href="../../../libc/constant.POSIX_FADV_WILLNEED.html">../../../libc/constant.POSIX_FADV_WILLNEED.html</a>...</p>
<script>location.replace("../../../libc/constant.POSIX_FADV_WILLNEED.html" + location.search + location.hash);</script>
</body>
</html> | malept/guardhaus | main/libc/unix/linux_like/constant.POSIX_FADV_WILLNEED.html | HTML | mit | 429 |
# Flixel Community #
[Flixel Community](http://flixelcommunity.github.com) is an open source game-making library that is completely free for personal or commercial use. Written entirely in ActionScript 3, and designed to be used with free development tools, it's easy to learn, extend and customize.
## Features ##
**Basic**
* Display thousands of moving objects
* Basic collisions between objects
* Group objects together for simplicity
* Easily generate and emit particles
* Create game levels using tilemaps
* Text display, save games, scrolling
* Mouse & keyboard input
* Math & color utilities
**Advanced**
* Record and play back replays
* Powerful interactive debugger
* Camera system for split screen
* Pathfinding and following
* Easy object recycling
##Quick start##
Check [Flixel Community](http://flixelcommunity.github.com) website for tutorials.
##Contributing##
If you want to contribute with Flixel Community, be welcome! You can help us with code, testing, tutorials and much more. Take a look at the [CONTRIBUTING](https://github.com/FlixelCommunity/flixel/blob/master/CONTRIBUTING.md) file for more.
## License ##
Flixel Community is licensed under the [MIT](http://opensource.org/licenses/MIT) license.
## About Flixel and Flixel Community##
[Flixel](http://flixel.org) is a well known open source and free game engine created by [Adam “Atomic” Saltsman](https://github.com/AdamAtomic/flixel). Flixel has been used in hundreds of games, including IGF nominees, Adult Swim games, and avant-garde experiments. Many Flixel users make their first game ever in Flixel.
Flixel Community was born as a healthy fork of Flixel. It is not supposed to replace Flixel or to compete with it, but to co-exist. [Adam](http://twitter.com/AdamAtomic) (Flixel's author) encouraged us to grow a community version and maintain it to our heart's content, even offering it as an alternative to Flixel.
| SestrenExsis/LD28_Warmup | bin-release/README.md | Markdown | mit | 1,921 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef MICROPY_INCLUDED_STM32_SOFTTIMER_H
#define MICROPY_INCLUDED_STM32_SOFTTIMER_H
#include "py/pairheap.h"
#define SOFT_TIMER_MODE_ONE_SHOT (1)
#define SOFT_TIMER_MODE_PERIODIC (2)
typedef struct _soft_timer_entry_t {
mp_pairheap_t pairheap;
uint32_t mode;
uint32_t expiry_ms;
uint32_t delta_ms; // for periodic mode
mp_obj_t callback;
} soft_timer_entry_t;
extern volatile uint32_t soft_timer_next;
void soft_timer_deinit(void);
void soft_timer_handler(void);
void soft_timer_insert(soft_timer_entry_t *entry);
void soft_timer_remove(soft_timer_entry_t *entry);
#endif // MICROPY_INCLUDED_STM32_SOFTTIMER_H
| tobbad/micropython | ports/stm32/softtimer.h | C | mit | 1,863 |
/**
* @fileoverview Restrict usage of duplicate imports.
* @author Simen Bekkhus
* @copyright 2016 Simen Bekkhus. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/**
* Returns the name of the module imported or re-exported.
*
* @param {ASTNode} node - A node to get.
* @returns {string} the name of the module, or empty string if no name.
*/
function getValue(node) {
if (node && node.source && node.source.value) {
return node.source.value.trim();
}
return "";
}
/**
* Checks if the name of the import or export exists in the given array, and reports if so.
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {ASTNode} node - A node to get.
* @param {string} value - The name of the imported or exported module.
* @param {string[]} array - The array containing other imports or exports in the file.
* @param {string} message - A message to be reported after the name of the module
*
* @returns {void} No return value
*/
function checkAndReport(context, node, value, array, message) {
if (array.indexOf(value) !== -1) {
context.report({
node: node,
message: "'{{module}}' " + message,
data: {module: value}
});
}
}
/**
* @callback nodeCallback
* @param {ASTNode} node - A node to handle.
*/
/**
* Returns a function handling the imports of a given file
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {boolean} includeExports - Whether or not to check for exports in addition to imports.
* @param {string[]} importsInFile - The array containing other imports in the file.
* @param {string[]} exportsInFile - The array containing other exports in the file.
*
* @returns {nodeCallback} A function passed to ESLint to handle the statement.
*/
function handleImports(context, includeExports, importsInFile, exportsInFile) {
return function(node) {
var value = getValue(node);
if (value) {
checkAndReport(context, node, value, importsInFile, "import is duplicated.");
if (includeExports) {
checkAndReport(context, node, value, exportsInFile, "import is duplicated as export.");
}
importsInFile.push(value);
}
};
}
/**
* Returns a function handling the exports of a given file
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {string[]} importsInFile - The array containing other imports in the file.
* @param {string[]} exportsInFile - The array containing other exports in the file.
*
* @returns {nodeCallback} A function passed to ESLint to handle the statement.
*/
function handleExports(context, importsInFile, exportsInFile) {
return function(node) {
var value = getValue(node);
if (value) {
checkAndReport(context, node, value, exportsInFile, "export is duplicated.");
checkAndReport(context, node, value, importsInFile, "export is duplicated as import.");
exportsInFile.push(value);
}
};
}
module.exports = function(context) {
var includeExports = (context.options[0] || {}).includeExports,
importsInFile = [],
exportsInFile = [];
var handlers = {
"ImportDeclaration": handleImports(context, includeExports, importsInFile, exportsInFile)
};
if (includeExports) {
handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile);
handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile);
}
return handlers;
};
module.exports.schema = [{
"type": "object",
"properties": {
"includeExports": {
"type": "boolean"
}
},
"additionalProperties": false
}];
| sauceSquatch/we_are_razorfish_experience | node_modules/eslint/lib/rules/no-duplicate-imports.js | JavaScript | mit | 4,014 |
<fieldset>
<legend>Δικαιώματα στις φωτογραφίες</legend>
<p>Κάθε φωτογραφία έχει ένα <strong>επίπεδο προστασίας</strong> (ένα κλείδωμα). Κάθε χρήστης έχει επίσης ένα επίπεδο προστασίας (βασικό). There are 5 privacy levels:</p>
<ol>
<li>Κανένας</li>
<li><em>Επαφές</em></li>
<li><em>Φίλοι (η οποία είναι υψηλότερη από μια Eπαφή)</em></li>
<li><em>Οικογένεια (η οποία είναι υψηλότερη από ένα Φίλο)</em></li>
<li><em>Διαχειριστές (το οποίο είναι υψηλότερο από ό, τι οποιοδήποτε άλλο επίπεδο)</em></li>
</ol>
<p>Τα υψηλότερα επίπεδα έχουν δικαιώματα σε χαμηλότερα επίπεδα. Για ένα συγκεκριμένο χρήστη, όσο υψηλότερο είναι το επίπεδο προστασίας της ιδιωτικότητας, τόσο περισσότερες φωτογραφίες μπορεί να δει.</p>
<p>Για παράδειγμα, εάν η φωτογραφία "peter_wedding-0024.jpg" έχει δικαιώματα <em>"Οικογένεια"</em>, Τότε:</p>
<ul>
<li>Πέτερ (που είναι <em>"Διαχειριστής"</em>) Θα δεί τη φωτογραφία γιατί <em>"Διαχειριστές"</em> μπορούν να δουν όλες τις φωτογραφίες</li>
<li>Μπεθ (που είναι μέλος στο <em>"Οικογένεια"</em> ) επίσης θα δει τις φωτογραφίες</li>
<li>Μαίρη(που είναι μια <em>"Φίλη"</em>) δεν θα δει τις φωτογραφίες</li>
</ul>
<p>Ένας χρήστης που δεν έχει άδεια για να δεί το περιεχόμενο του λευκώματος δεν θα δεί το ίδιο το λεύκωμα, ούτε καν τον τίτλο του. Η ίδια αρχή ισχύει και για μια ετικέτα.</p>
<p>Μπορείτε να ρυθμίσετε το επίπεδο προστασίας της ιδιωτικότητας του χρήστη πάτε στην οθόνη <span class="pwgScreen">Διαχείριση » Χρήστες » Διαχειριστείτε </span>.</p>
</fieldset>
<fieldset>
<legend>Δικαιώματα για τα Λευκώματα</legend>
<p>Αν τα επίπεδα της ιδιωτικότητας δεν ταιριάζει στις ανάγκες σας, μπορείτε επίσης να διαχειριστείτε δικαιώματα στα λευκώματα για ένα χρήστη ή μια ομάδα. Μπορείτε να διαχειρίζεστε δικαιώματα για τις φωτογραφίες και τα λευκώματα ταυτόχρονα, χωρίς διενέξεις.</p>
<p>Μπορείτε να απαγορεύσετε την πρόσβαση στα λευκώματα. Ενεργοποιήστε τον τύπο πρόσβασης στο λεύκωμα
σε "ιδιωτικό" αν θέλετε να διαχειριστείτε δικαιώματα.</p>
<p>Μπορείτε να ορίσετε ένα λεύκωμα ως ιδιωτικό με επεξεργασία κάποιου λευκώματος
(<span class="pwgScreen">Διαχείριση » Λευκώματα » Διαχειριστείτε
» Επεξεργαστείτε </span>) ή με τη ρύθμιση των επιλογών για όλο το δέντρο του λευκώματός σας
(<span class="pwgScreen">Διαχείριση » Λευκώματα »
Ιδιότητες » Δημόσιο / Ιδιωτικό</span>).</p>
<p>Έτσι και το άλμπουμ είναι ιδιωτικό, μπορείτε να διαχειριστείτε δικαιώματα για τις ομάδες και
τους χρήστες με 3 οθόνες:</p>
<ul>
<li><span class="pwgScreen">Διαχείριση » Χρήστες » Διαχειριστείτε »
δράση δικαιωμάτων </span> (μία σύνδεση ανά χρήστη)</li>
<li><span class="pwgScreen">Διαχείριση » Χρήστες » Ομάδες »
δράση δικαιωμάτων</span> (μία σύνδεση ανά χρήστη)</li>
<li><span class="pwgScreen">Διαχείριση » Λευκώματα » Διαχειριστείτε » επεξεργαστείτε
δράση δικαιωμάτων λευκώματος</span> (μία σύνδεση ανά χρήστη)</li>
</ul>
</fieldset> | ale252/theatre | web/piwigo/language/el_GR/help/help_permissions.html | HTML | mit | 4,837 |
import{generateUtilityClass,generateUtilityClasses}from"@material-ui/unstyled";export function getCardActionAreaUtilityClass(t){return generateUtilityClass("MuiCardActionArea",t)};var cardActionAreaClasses=generateUtilityClasses("MuiCardActionArea",["root","focusVisible","focusHighlight"]);export default cardActionAreaClasses; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.31/legacy/CardActionArea/cardActionAreaClasses.min.js | JavaScript | mit | 328 |
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var strings={prefixAgo:null,prefixFromNow:null,suffixAgo:"",suffixFromNow:"",seconds:"1m",minute:"1m",minutes:"%dm",hour:"1h",hours:"%dh",day:"1g",days:"%dg",month:"1me",months:"%dme",year:"1a",years:"%da",wordSeparator:" "},_default=strings;exports.default=_default; | cdnjs/cdnjs | ajax/libs/react-timeago/6.2.1/language-strings/it-short.min.js | JavaScript | mit | 358 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Process manager for *nix like system.
*
* @author andrew00x
*/
class UnixProcessManager extends ProcessManager {
/*
At the moment tested on linux only.
*/
private static final Logger LOG = LoggerFactory.getLogger(UnixProcessManager.class);
private static final CLibrary C_LIBRARY;
private static final Field PID_FIELD;
static {
CLibrary lib = null;
Field pidField = null;
if (SystemInfo.isUnix()) {
try {
lib = ((CLibrary)Native.loadLibrary("c", CLibrary.class));
} catch (Exception e) {
LOG.error("Cannot load native library", e);
}
try {
pidField = Thread.currentThread().getContextClassLoader().loadClass("java.lang.UNIXProcess").getDeclaredField("pid");
pidField.setAccessible(true);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
C_LIBRARY = lib;
PID_FIELD = pidField;
}
private static interface CLibrary extends Library {
// kill -l
int SIGKILL = 9;
int SIGTERM = 15;
int kill(int pid, int signal);
String strerror(int errno);
int system(String cmd);
}
private static final Pattern UNIX_PS_TABLE_PATTERN = Pattern.compile("\\s+");
@Override
public void kill(Process process) {
if (C_LIBRARY != null) {
killTree(getPid(process));
} else {
throw new IllegalStateException("Can't kill process. Not unix system?");
}
}
private void killTree(int pid) {
final int[] children = getChildProcesses(pid);
LOG.debug("PID: {}, child PIDs: {}", pid, children);
if (children.length > 0) {
for (int cpid : children) {
killTree(cpid); // kill process tree recursively
}
}
int r = C_LIBRARY.kill(pid, CLibrary.SIGKILL); // kill origin process
LOG.debug("kill {}", pid);
if (r != 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("kill for {} returns {}, strerror '{}'", pid, r, C_LIBRARY.strerror(r));
}
}
}
private int[] getChildProcesses(final int myPid) {
final String ps = "ps -e -o ppid,pid,comm"; /* PPID, PID, COMMAND */
final List<Integer> children = new ArrayList<>();
final StringBuilder error = new StringBuilder();
final LineConsumer stdout = new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (line != null && !line.isEmpty()) {
final String[] tokens = UNIX_PS_TABLE_PATTERN.split(line.trim());
if (tokens.length == 3 /* PPID, PID, COMMAND */) {
int ppid;
try {
ppid = Integer.parseInt(tokens[0]);
} catch (NumberFormatException e) {
// May be first line from process table: 'PPID PID COMMAND'. Skip it.
return;
}
if (ppid == myPid) {
int pid = Integer.parseInt(tokens[1]);
children.add(pid);
}
}
}
}
@Override
public void close() throws IOException {
}
};
final LineConsumer stderr = new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (error.length() > 0) {
error.append('\n');
}
error.append(line);
}
@Override
public void close() throws IOException {
}
};
try {
ProcessUtil.process(Runtime.getRuntime().exec(ps), stdout, stderr);
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (error.length() > 0) {
throw new IllegalStateException("can't get child processes: " + error.toString());
}
final int size = children.size();
final int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = children.get(i);
}
return result;
}
@Override
public boolean isAlive(Process process) {
return process.isAlive();
}
int getPid(Process process) {
if (PID_FIELD != null) {
try {
return ((Number)PID_FIELD.get(process)).intValue();
} catch (IllegalAccessException e) {
throw new IllegalStateException("Can't get process' pid. Not unix system?", e);
}
} else {
throw new IllegalStateException("Can't get process' pid. Not unix system?");
}
}
@Override
int system(String command) {
return C_LIBRARY.system(command);
}
}
| gazarenkov/che-sketch | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/UnixProcessManager.java | Java | epl-1.0 | 5,909 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ui.toolbar;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* This Lock Layer for Popup Menu uses as root for for Popup Menus and uses for closing all visible popups when user clicked outside one of
* them.
*
* @author Vitaliy Guliy
*/
public class MenuLockLayer extends AbsolutePanel {
/** Lock Layer uses for locking of screen. Uses for hiding popups. */
private class LockLayer extends AbsolutePanel {
public LockLayer() {
sinkEvents(Event.ONMOUSEDOWN);
}
@Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
close();
break;
}
}
}
/** Callback which is uses for closing Popup menu. */
private CloseMenuHandler closeMenuCallback;
private int topOffset = 20;
/** Create Menu Lock Layer. */
public MenuLockLayer() {
this(null, 0);
}
/**
* Create Menu Lock Layer.
*
* @param closeMenuCallback
* - callback which is uses for
*/
public MenuLockLayer(CloseMenuHandler closeMenuCallback) {
this(closeMenuCallback, 0);
}
public MenuLockLayer(CloseMenuHandler closeMenuCallback, int topOffset) {
this.closeMenuCallback = closeMenuCallback;
this.topOffset = topOffset;
getElement().setId("menu-lock-layer-id");
RootPanel.get().add(this, 0, topOffset);
getElement().getStyle().setProperty("right", "0px");
getElement().getStyle().setProperty("bottom", "0px");
getElement().getStyle().setProperty("zIndex", (Integer.MAX_VALUE - 5) + "");
AbsolutePanel blockMouseEventsPanel = new LockLayer();
blockMouseEventsPanel.setStyleName("exo-lockLayer");
blockMouseEventsPanel.getElement().getStyle().setProperty("position", "absolute");
blockMouseEventsPanel.getElement().getStyle().setProperty("left", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("top", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("right", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("bottom", "0px");
add(blockMouseEventsPanel);
}
public void close() {
removeFromParent();
if (closeMenuCallback != null) {
closeMenuCallback.onCloseMenu();
}
}
public int getTopOffset() {
return topOffset;
}
}
| gazarenkov/che-sketch | ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/toolbar/MenuLockLayer.java | Java | epl-1.0 | 3,234 |
package backtype.storm.state;
import java.util.List;
public interface ISynchronizeOutputCollector {
void add(int streamId, Object id, List<Object> tuple);
}
| revans2/storm | storm-core/src/jvm/backtype/storm/state/ISynchronizeOutputCollector.java | Java | epl-1.0 | 167 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.rest;
import javax.ws.rs.core.UriBuilder;
/**
* Helps to deliver context of RESTful request to components.
*
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
*/
public interface ServiceContext {
/**
* Get UriBuilder which already contains base URI of RESTful application and URL pattern of RESTful service that produces this
* instance.
*/
UriBuilder getServiceUriBuilder();
/** Get UriBuilder which already contains base URI of RESTful application. */
UriBuilder getBaseUriBuilder();
}
| gazarenkov/che-sketch | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ServiceContext.java | Java | epl-1.0 | 1,098 |
/*
* Copyright (C) 2010 ENAC
*
* This file is part of paparazzi.
*
* paparazzi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* paparazzi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with paparazzi; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*/
/** @file modules/ins/xsens700.h
* Parser for the Xsens protocol.
*/
#ifndef XSENS700_H
#define XSENS700_H
#include "std.h"
#include "math/pprz_algebra_float.h"
#include "math/pprz_geodetic_float.h"
#include "math/pprz_geodetic_int.h"
#include "xsens_parser.h"
#if USE_GPS_XSENS
#include "subsystems/gps.h"
#endif
struct XsensTime {
int8_t hour;
int8_t min;
int8_t sec;
int32_t nanosec;
int16_t year;
int8_t month;
int8_t day;
};
struct Xsens {
struct XsensTime time;
uint16_t time_stamp;
struct FloatRates gyro;
struct FloatVect3 accel;
struct FloatVect3 mag;
struct LlaCoor_f lla_f;
struct FloatVect3 vel; ///< NED velocity in m/s
struct FloatQuat quat;
struct FloatEulers euler;
struct XsensParser parser;
volatile bool new_attitude;
bool gyro_available;
bool accel_available;
bool mag_available;
#if USE_GPS_XSENS
struct GpsState gps;
bool gps_available;
#endif
};
extern struct Xsens xsens700;
extern void xsens700_init(void);
extern void xsens700_periodic(void);
extern void parse_xsens700_msg(void);
#endif /* XSENS700_H */
| HWal/paparazzi | sw/airborne/modules/ins/xsens700.h | C | gpl-2.0 | 1,884 |
/*
* Intel MID (Langwell/Penwell) USB OTG Transceiver driver
* Copyright (C) 2008 - 2010, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#ifndef __INTEL_MID_OTG_H
#define __INTEL_MID_OTG_H
#include <linux/pm.h>
#include <linux/usb/otg.h>
#include <linux/notifier.h>
#include <linux/wakelock.h>
struct intel_mid_otg_xceiv;
/* This is a common data structure for Intel MID platform to
* save values of the OTG state machine */
struct otg_hsm {
/* Input */
int a_bus_resume;
int a_bus_suspend;
int a_conn;
int a_sess_vld;
int a_srp_det;
int a_vbus_vld;
int b_bus_resume;
int b_bus_suspend;
int b_conn;
int b_se0_srp;
int b_ssend_srp;
int b_sess_end;
int b_sess_vld;
int id;
/* id values */
#define ID_B 0x05
#define ID_A 0x04
#define ID_ACA_C 0x03
#define ID_ACA_B 0x02
#define ID_ACA_A 0x01
int power_up;
int adp_change;
int test_device;
/* Internal variables */
int a_set_b_hnp_en;
int b_srp_done;
int b_hnp_enable;
int hnp_poll_enable;
/* Timeout indicator for timers */
int a_wait_vrise_tmout;
int a_wait_bcon_tmout;
int a_aidl_bdis_tmout;
int a_bidl_adis_tmout;
int a_bidl_adis_tmr;
int a_wait_vfall_tmout;
int b_ase0_brst_tmout;
int b_bus_suspend_tmout;
int b_srp_init_tmout;
int b_srp_fail_tmout;
int b_srp_fail_tmr;
int b_adp_sense_tmout;
int tst_maint_tmout;
int tst_noadp_tmout;
/* Informative variables */
int a_bus_drop;
int a_bus_req;
int a_clr_err;
int b_bus_req;
int a_suspend_req;
int b_bus_suspend_vld;
/* Output */
int drv_vbus;
int loc_conn;
int loc_sof;
/* Others */
int vbus_srp_up;
int ulpi_error;
int ulpi_polling;
/* Test Mode */
int otg_srp_reqd;
int otg_hnp_reqd;
int otg_vbus_off;
int in_test_mode;
};
/* must provide ULPI access function to read/write registers implemented in
* ULPI address space */
struct iotg_ulpi_access_ops {
int (*read)(struct intel_mid_otg_xceiv *iotg, u8 reg, u8 *val);
int (*write)(struct intel_mid_otg_xceiv *iotg, u8 reg, u8 val);
};
#define OTG_A_DEVICE 0x0
#define OTG_B_DEVICE 0x1
/*
* the Intel MID (Langwell/Penwell) otg transceiver driver needs to interact
* with device and host drivers to implement the USB OTG related feature. More
* function members are added based on usb_phy data structure for this
* purpose.
*/
struct intel_mid_otg_xceiv {
struct usb_phy otg;
struct otg_hsm hsm;
/* base address */
void __iomem *base;
/* ops to access ulpi */
struct iotg_ulpi_access_ops ulpi_ops;
/* atomic notifier for interrupt context */
struct atomic_notifier_head iotg_notifier;
/* hnp poll lock */
spinlock_t hnp_poll_lock;
#ifdef CONFIG_USB_SUSPEND
struct wake_lock wake_lock;
#endif
/* start/stop USB Host function */
int (*start_host)(struct intel_mid_otg_xceiv *iotg);
int (*stop_host)(struct intel_mid_otg_xceiv *iotg);
/* start/stop USB Peripheral function */
int (*start_peripheral)(struct intel_mid_otg_xceiv *iotg);
int (*stop_peripheral)(struct intel_mid_otg_xceiv *iotg);
/* start/stop ADP sense/probe function */
int (*set_adp_probe)(struct intel_mid_otg_xceiv *iotg,
bool enabled, int dev);
int (*set_adp_sense)(struct intel_mid_otg_xceiv *iotg,
bool enabled);
/* start/stop HNP Polling function */
int (*start_hnp_poll)(struct intel_mid_otg_xceiv *iotg);
int (*stop_hnp_poll)(struct intel_mid_otg_xceiv *iotg);
#ifdef CONFIG_PM
/* suspend/resume USB host function */
int (*suspend_host)(struct intel_mid_otg_xceiv *iotg);
int (*suspend_noirq_host)(struct intel_mid_otg_xceiv *iotg);
int (*resume_host)(struct intel_mid_otg_xceiv *iotg);
int (*resume_noirq_host)(struct intel_mid_otg_xceiv *iotg);
int (*suspend_peripheral)(struct intel_mid_otg_xceiv *iotg,
pm_message_t message);
int (*resume_peripheral)(struct intel_mid_otg_xceiv *iotg);
/* runtime suspend/resume */
int (*runtime_suspend_host)(struct intel_mid_otg_xceiv *iotg);
int (*runtime_resume_host)(struct intel_mid_otg_xceiv *iotg);
int (*runtime_suspend_peripheral)(struct intel_mid_otg_xceiv *iotg);
int (*runtime_resume_peripheral)(struct intel_mid_otg_xceiv *iotg);
#endif
};
static inline
struct intel_mid_otg_xceiv *otg_to_mid_xceiv(struct usb_phy *otg)
{
return container_of(otg, struct intel_mid_otg_xceiv, otg);
}
#define MID_OTG_NOTIFY_CONNECT 0x0001
#define MID_OTG_NOTIFY_DISCONN 0x0002
#define MID_OTG_NOTIFY_HSUSPEND 0x0003
#define MID_OTG_NOTIFY_HRESUME 0x0004
#define MID_OTG_NOTIFY_CSUSPEND 0x0005
#define MID_OTG_NOTIFY_CRESUME 0x0006
#define MID_OTG_NOTIFY_HOSTADD 0x0007
#define MID_OTG_NOTIFY_HOSTREMOVE 0x0008
#define MID_OTG_NOTIFY_CLIENTADD 0x0009
#define MID_OTG_NOTIFY_CLIENTREMOVE 0x000a
#define MID_OTG_NOTIFY_CRESET 0x000b
#define MID_OTG_NOTIFY_TEST_SRP_REQD 0x0101
#define MID_OTG_NOTIFY_TEST_VBUS_OFF 0x0102
#define MID_OTG_NOTIFY_TEST 0x0103
#define MID_OTG_NOTIFY_TEST_MODE_START 0x0104
#define MID_OTG_NOTIFY_TEST_MODE_STOP 0x0105
static inline int
intel_mid_otg_register_notifier(struct intel_mid_otg_xceiv *iotg,
struct notifier_block *nb)
{
return atomic_notifier_chain_register(&iotg->iotg_notifier, nb);
}
static inline void
intel_mid_otg_unregister_notifier(struct intel_mid_otg_xceiv *iotg,
struct notifier_block *nb)
{
atomic_notifier_chain_unregister(&iotg->iotg_notifier, nb);
}
#endif /* __INTEL_MID_OTG_H */
| trevd/android_kernel_samsung_santos10 | include/linux/usb/intel_mid_otg.h | C | gpl-2.0 | 5,910 |
/*
* linux/kernel/printk.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Modified to make sys_syslog() more flexible: added commands to
* return the last 4k of kernel messages, regardless of whether
* they've been read or not. Added option to suppress kernel printk's
* to the console. Added hook for sending the console messages
* elsewhere, in preparation for a serial line console (someday).
* Ted Ts'o, 2/11/93.
* Modified for sysctl support, 1/8/97, Chris Horn.
* Fixed SMP synchronization, 08/08/99, Manfred Spraul
* manfred@colorfullife.com
* Rewrote bits to get rid of console_lock
* 01Mar01 Andrew Morton
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/console.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/nmi.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/interrupt.h> /* For in_interrupt() */
#include <linux/delay.h>
#include <linux/smp.h>
#include <linux/security.h>
#include <linux/bootmem.h>
#include <linux/syscalls.h>
#include <asm/uaccess.h>
/*
* Architectures can override it:
*/
void asmlinkage __attribute__((weak)) early_printk(const char *fmt, ...)
{
}
#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)
/* printk's without a loglevel use this.. */
#define DEFAULT_MESSAGE_LOGLEVEL 4 /* KERN_WARNING */
/* We show everything that is MORE important than this.. */
#define MINIMUM_CONSOLE_LOGLEVEL 1 /* Minimum loglevel we let people use */
#define DEFAULT_CONSOLE_LOGLEVEL 7 /* anything MORE serious than KERN_DEBUG */
DECLARE_WAIT_QUEUE_HEAD(log_wait);
int console_printk[4] = {
DEFAULT_CONSOLE_LOGLEVEL, /* console_loglevel */
DEFAULT_MESSAGE_LOGLEVEL, /* default_message_loglevel */
MINIMUM_CONSOLE_LOGLEVEL, /* minimum_console_loglevel */
DEFAULT_CONSOLE_LOGLEVEL, /* default_console_loglevel */
};
/*
* Low level drivers may need that to know if they can schedule in
* their unblank() callback or not. So let's export it.
*/
int oops_in_progress;
EXPORT_SYMBOL(oops_in_progress);
/*
* console_sem protects the console_drivers list, and also
* provides serialisation for access to the entire console
* driver system.
*/
static DECLARE_MUTEX(console_sem);
struct console *console_drivers;
EXPORT_SYMBOL_GPL(console_drivers);
/*
* This is used for debugging the mess that is the VT code by
* keeping track if we have the console semaphore held. It's
* definitely not the perfect debug tool (we don't know if _WE_
* hold it are racing, but it helps tracking those weird code
* path in the console code where we end up in places I want
* locked without the console sempahore held
*/
static int console_locked, console_suspended;
/*
* logbuf_lock protects log_buf, log_start, log_end, con_start and logged_chars
* It is also used in interesting ways to provide interlocking in
* release_console_sem().
*/
static DEFINE_SPINLOCK(logbuf_lock);
#define LOG_BUF_MASK (log_buf_len-1)
#define LOG_BUF(idx) (log_buf[(idx) & LOG_BUF_MASK])
/*
* The indices into log_buf are not constrained to log_buf_len - they
* must be masked before subscripting
*/
static unsigned log_start; /* Index into log_buf: next char to be read by syslog() */
static unsigned con_start; /* Index into log_buf: next char to be sent to consoles */
static unsigned log_end; /* Index into log_buf: most-recently-written-char + 1 */
/*
* Array of consoles built from command line options (console=)
*/
struct console_cmdline
{
char name[8]; /* Name of the driver */
int index; /* Minor dev. to use */
char *options; /* Options for the driver */
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
char *brl_options; /* Options for braille driver */
#endif
};
#define MAX_CMDLINECONSOLES 8
static struct console_cmdline console_cmdline[MAX_CMDLINECONSOLES];
static int selected_console = -1;
static int preferred_console = -1;
int console_set_on_cmdline;
EXPORT_SYMBOL(console_set_on_cmdline);
/* Flag: console code may call schedule() */
static int console_may_schedule;
#ifdef CONFIG_PRINTK
static char __log_buf[__LOG_BUF_LEN];
static char *log_buf = __log_buf;
static int log_buf_len = __LOG_BUF_LEN;
static unsigned logged_chars; /* Number of chars produced since last read+clear operation */
static int __init log_buf_len_setup(char *str)
{
unsigned size = memparse(str, &str);
unsigned long flags;
if (size)
size = roundup_pow_of_two(size);
if (size > log_buf_len) {
unsigned start, dest_idx, offset;
char *new_log_buf;
new_log_buf = alloc_bootmem(size);
if (!new_log_buf) {
printk(KERN_WARNING "log_buf_len: allocation failed\n");
goto out;
}
spin_lock_irqsave(&logbuf_lock, flags);
log_buf_len = size;
log_buf = new_log_buf;
offset = start = min(con_start, log_start);
dest_idx = 0;
while (start != log_end) {
log_buf[dest_idx] = __log_buf[start & (__LOG_BUF_LEN - 1)];
start++;
dest_idx++;
}
log_start -= offset;
con_start -= offset;
log_end -= offset;
spin_unlock_irqrestore(&logbuf_lock, flags);
printk(KERN_NOTICE "log_buf_len: %d\n", log_buf_len);
}
out:
return 1;
}
__setup("log_buf_len=", log_buf_len_setup);
#ifdef CONFIG_BOOT_PRINTK_DELAY
static unsigned int boot_delay; /* msecs delay after each printk during bootup */
static unsigned long long printk_delay_msec; /* per msec, based on boot_delay */
static int __init boot_delay_setup(char *str)
{
unsigned long lpj;
unsigned long long loops_per_msec;
lpj = preset_lpj ? preset_lpj : 1000000; /* some guess */
loops_per_msec = (unsigned long long)lpj / 1000 * HZ;
get_option(&str, &boot_delay);
if (boot_delay > 10 * 1000)
boot_delay = 0;
printk_delay_msec = loops_per_msec;
printk(KERN_DEBUG "boot_delay: %u, preset_lpj: %ld, lpj: %lu, "
"HZ: %d, printk_delay_msec: %llu\n",
boot_delay, preset_lpj, lpj, HZ, printk_delay_msec);
return 1;
}
__setup("boot_delay=", boot_delay_setup);
static void boot_delay_msec(void)
{
unsigned long long k;
unsigned long timeout;
if (boot_delay == 0 || system_state != SYSTEM_BOOTING)
return;
k = (unsigned long long)printk_delay_msec * boot_delay;
timeout = jiffies + msecs_to_jiffies(boot_delay);
while (k) {
k--;
cpu_relax();
/*
* use (volatile) jiffies to prevent
* compiler reduction; loop termination via jiffies
* is secondary and may or may not happen.
*/
if (time_after(jiffies, timeout))
break;
touch_nmi_watchdog();
}
}
#else
static inline void boot_delay_msec(void)
{
}
#endif
/*
* Commands to do_syslog:
*
* 0 -- Close the log. Currently a NOP.
* 1 -- Open the log. Currently a NOP.
* 2 -- Read from the log.
* 3 -- Read all messages remaining in the ring buffer.
* 4 -- Read and clear all messages remaining in the ring buffer
* 5 -- Clear ring buffer.
* 6 -- Disable printk's to console
* 7 -- Enable printk's to console
* 8 -- Set level of messages printed to console
* 9 -- Return number of unread characters in the log buffer
* 10 -- Return size of the log buffer
*/
int do_syslog(int type, char __user *buf, int len)
{
unsigned i, j, limit, count;
int do_clear = 0;
char c;
int error = 0;
error = security_syslog(type);
if (error)
return error;
switch (type) {
case 0: /* Close log */
break;
case 1: /* Open log */
break;
case 2: /* Read from log */
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
error = wait_event_interruptible(log_wait,
(log_start - log_end));
if (error)
goto out;
i = 0;
spin_lock_irq(&logbuf_lock);
while (!error && (log_start != log_end) && i < len) {
c = LOG_BUF(log_start);
log_start++;
spin_unlock_irq(&logbuf_lock);
error = __put_user(c,buf);
buf++;
i++;
cond_resched();
spin_lock_irq(&logbuf_lock);
}
spin_unlock_irq(&logbuf_lock);
if (!error)
error = i;
break;
case 4: /* Read/clear last kernel messages */
do_clear = 1;
/* FALL THRU */
case 3: /* Read last kernel messages */
error = -EINVAL;
if (!buf || len < 0)
goto out;
error = 0;
if (!len)
goto out;
if (!access_ok(VERIFY_WRITE, buf, len)) {
error = -EFAULT;
goto out;
}
count = len;
if (count > log_buf_len)
count = log_buf_len;
spin_lock_irq(&logbuf_lock);
if (count > logged_chars)
count = logged_chars;
if (do_clear)
logged_chars = 0;
limit = log_end;
/*
* __put_user() could sleep, and while we sleep
* printk() could overwrite the messages
* we try to copy to user space. Therefore
* the messages are copied in reverse. <manfreds>
*/
for (i = 0; i < count && !error; i++) {
j = limit-1-i;
if (j + log_buf_len < log_end)
break;
c = LOG_BUF(j);
spin_unlock_irq(&logbuf_lock);
error = __put_user(c,&buf[count-1-i]);
cond_resched();
spin_lock_irq(&logbuf_lock);
}
spin_unlock_irq(&logbuf_lock);
if (error)
break;
error = i;
if (i != count) {
int offset = count-error;
/* buffer overflow during copy, correct user buffer. */
for (i = 0; i < error; i++) {
if (__get_user(c,&buf[i+offset]) ||
__put_user(c,&buf[i])) {
error = -EFAULT;
break;
}
cond_resched();
}
}
break;
case 5: /* Clear ring buffer */
logged_chars = 0;
break;
case 6: /* Disable logging to console */
console_loglevel = minimum_console_loglevel;
break;
case 7: /* Enable logging to console */
console_loglevel = default_console_loglevel;
break;
case 8: /* Set level of messages printed to console */
error = -EINVAL;
if (len < 1 || len > 8)
goto out;
if (len < minimum_console_loglevel)
len = minimum_console_loglevel;
console_loglevel = len;
error = 0;
break;
case 9: /* Number of chars in the log buffer */
error = log_end - log_start;
break;
case 10: /* Size of the log buffer */
error = log_buf_len;
break;
default:
error = -EINVAL;
break;
}
out:
return error;
}
SYSCALL_DEFINE3(syslog, int, type, char __user *, buf, int, len)
{
return do_syslog(type, buf, len);
}
/*
* Call the console drivers on a range of log_buf
*/
static void __call_console_drivers(unsigned start, unsigned end)
{
struct console *con;
for (con = console_drivers; con; con = con->next) {
if ((con->flags & CON_ENABLED) && con->write &&
(cpu_online(smp_processor_id()) ||
(con->flags & CON_ANYTIME)))
con->write(con, &LOG_BUF(start), end - start);
}
}
static int __read_mostly ignore_loglevel;
static int __init ignore_loglevel_setup(char *str)
{
ignore_loglevel = 1;
printk(KERN_INFO "debug: ignoring loglevel setting.\n");
return 0;
}
early_param("ignore_loglevel", ignore_loglevel_setup);
/*
* Write out chars from start to end - 1 inclusive
*/
static void _call_console_drivers(unsigned start,
unsigned end, int msg_log_level)
{
if ((msg_log_level < console_loglevel || ignore_loglevel) &&
console_drivers && start != end) {
if ((start & LOG_BUF_MASK) > (end & LOG_BUF_MASK)) {
/* wrapped write */
__call_console_drivers(start & LOG_BUF_MASK,
log_buf_len);
__call_console_drivers(0, end & LOG_BUF_MASK);
} else {
__call_console_drivers(start, end);
}
}
}
/*
* Call the console drivers, asking them to write out
* log_buf[start] to log_buf[end - 1].
* The console_sem must be held.
*/
static void call_console_drivers(unsigned start, unsigned end)
{
unsigned cur_index, start_print;
static int msg_level = -1;
BUG_ON(((int)(start - end)) > 0);
cur_index = start;
start_print = start;
while (cur_index != end) {
if (msg_level < 0 && ((end - cur_index) > 2) &&
LOG_BUF(cur_index + 0) == '<' &&
LOG_BUF(cur_index + 1) >= '0' &&
LOG_BUF(cur_index + 1) <= '7' &&
LOG_BUF(cur_index + 2) == '>') {
msg_level = LOG_BUF(cur_index + 1) - '0';
cur_index += 3;
start_print = cur_index;
}
while (cur_index != end) {
char c = LOG_BUF(cur_index);
cur_index++;
if (c == '\n') {
if (msg_level < 0) {
/*
* printk() has already given us loglevel tags in
* the buffer. This code is here in case the
* log buffer has wrapped right round and scribbled
* on those tags
*/
msg_level = default_message_loglevel;
}
_call_console_drivers(start_print, cur_index, msg_level);
msg_level = -1;
start_print = cur_index;
break;
}
}
}
_call_console_drivers(start_print, end, msg_level);
}
static void emit_log_char(char c)
{
LOG_BUF(log_end) = c;
log_end++;
if (log_end - log_start > log_buf_len)
log_start = log_end - log_buf_len;
if (log_end - con_start > log_buf_len)
con_start = log_end - log_buf_len;
if (logged_chars < log_buf_len)
logged_chars++;
}
/*
* Zap console related locks when oopsing. Only zap at most once
* every 10 seconds, to leave time for slow consoles to print a
* full oops.
*/
static void zap_locks(void)
{
static unsigned long oops_timestamp;
if (time_after_eq(jiffies, oops_timestamp) &&
!time_after(jiffies, oops_timestamp + 30 * HZ))
return;
oops_timestamp = jiffies;
/* If a crash is occurring, make sure we can't deadlock */
spin_lock_init(&logbuf_lock);
/* And make sure that we print immediately */
init_MUTEX(&console_sem);
}
#if defined(CONFIG_PRINTK_TIME)
static int printk_time = 1;
#else
static int printk_time = 0;
#endif
module_param_named(time, printk_time, bool, S_IRUGO | S_IWUSR);
/* Check if we have any console registered that can be called early in boot. */
static int have_callable_console(void)
{
struct console *con;
for (con = console_drivers; con; con = con->next)
if (con->flags & CON_ANYTIME)
return 1;
return 0;
}
/**
* printk - print a kernel message
* @fmt: format string
*
* This is printk(). It can be called from any context. We want it to work.
*
* We try to grab the console_sem. If we succeed, it's easy - we log the output and
* call the console drivers. If we fail to get the semaphore we place the output
* into the log buffer and return. The current holder of the console_sem will
* notice the new output in release_console_sem() and will send it to the
* consoles before releasing the semaphore.
*
* One effect of this deferred printing is that code which calls printk() and
* then changes console_loglevel may break. This is because console_loglevel
* is inspected when the actual printing occurs.
*
* See also:
* printf(3)
*
* See the vsnprintf() documentation for format string extensions over C99.
*/
asmlinkage int printk(const char *fmt, ...)
{
va_list args;
int r;
va_start(args, fmt);
r = vprintk(fmt, args);
va_end(args);
return r;
}
/* cpu currently holding logbuf_lock */
static volatile unsigned int printk_cpu = UINT_MAX;
/*
* Can we actually use the console at this time on this cpu?
*
* Console drivers may assume that per-cpu resources have
* been allocated. So unless they're explicitly marked as
* being able to cope (CON_ANYTIME) don't call them until
* this CPU is officially up.
*/
static inline int can_use_console(unsigned int cpu)
{
return cpu_online(cpu) || have_callable_console();
}
/*
* Try to get console ownership to actually show the kernel
* messages from a 'printk'. Return true (and with the
* console_semaphore held, and 'console_locked' set) if it
* is successful, false otherwise.
*
* This gets called with the 'logbuf_lock' spinlock held and
* interrupts disabled. It should return with 'lockbuf_lock'
* released but interrupts still disabled.
*/
static int acquire_console_semaphore_for_printk(unsigned int cpu)
{
int retval = 0;
if (!try_acquire_console_sem()) {
retval = 1;
/*
* If we can't use the console, we need to release
* the console semaphore by hand to avoid flushing
* the buffer. We need to hold the console semaphore
* in order to do this test safely.
*/
if (!can_use_console(cpu)) {
console_locked = 0;
up(&console_sem);
retval = 0;
}
}
printk_cpu = UINT_MAX;
spin_unlock(&logbuf_lock);
return retval;
}
static const char recursion_bug_msg [] =
KERN_CRIT "BUG: recent printk recursion!\n";
static int recursion_bug;
static int new_text_line = 1;
static char printk_buf[1024];
asmlinkage int vprintk(const char *fmt, va_list args)
{
int printed_len = 0;
int current_log_level = default_message_loglevel;
unsigned long flags;
int this_cpu;
char *p;
boot_delay_msec();
preempt_disable();
/* This stops the holder of console_sem just where we want him */
raw_local_irq_save(flags);
this_cpu = smp_processor_id();
/*
* Ouch, printk recursed into itself!
*/
if (unlikely(printk_cpu == this_cpu)) {
/*
* If a crash is occurring during printk() on this CPU,
* then try to get the crash message out but make sure
* we can't deadlock. Otherwise just return to avoid the
* recursion and return - but flag the recursion so that
* it can be printed at the next appropriate moment:
*/
if (!oops_in_progress) {
recursion_bug = 1;
goto out_restore_irqs;
}
zap_locks();
}
lockdep_off();
spin_lock(&logbuf_lock);
printk_cpu = this_cpu;
if (recursion_bug) {
recursion_bug = 0;
strcpy(printk_buf, recursion_bug_msg);
printed_len = strlen(recursion_bug_msg);
}
/* Emit the output into the temporary buffer */
printed_len += vscnprintf(printk_buf + printed_len,
sizeof(printk_buf) - printed_len, fmt, args);
/*
* Copy the output into log_buf. If the caller didn't provide
* appropriate log level tags, we insert them here
*/
for (p = printk_buf; *p; p++) {
if (new_text_line) {
/* If a token, set current_log_level and skip over */
if (p[0] == '<' && p[1] >= '0' && p[1] <= '7' &&
p[2] == '>') {
current_log_level = p[1] - '0';
p += 3;
printed_len -= 3;
}
/* Always output the token */
emit_log_char('<');
emit_log_char(current_log_level + '0');
emit_log_char('>');
printed_len += 3;
new_text_line = 0;
if (printk_time) {
/* Follow the token with the time */
char tbuf[50], *tp;
unsigned tlen;
unsigned long long t;
unsigned long nanosec_rem;
t = cpu_clock(printk_cpu);
nanosec_rem = do_div(t, 1000000000);
tlen = sprintf(tbuf, "[%5lu.%06lu] ",
(unsigned long) t,
nanosec_rem / 1000);
for (tp = tbuf; tp < tbuf + tlen; tp++)
emit_log_char(*tp);
printed_len += tlen;
}
if (!*p)
break;
}
emit_log_char(*p);
if (*p == '\n')
new_text_line = 1;
}
/*
* Try to acquire and then immediately release the
* console semaphore. The release will do all the
* actual magic (print out buffers, wake up klogd,
* etc).
*
* The acquire_console_semaphore_for_printk() function
* will release 'logbuf_lock' regardless of whether it
* actually gets the semaphore or not.
*/
if (acquire_console_semaphore_for_printk(this_cpu))
release_console_sem();
lockdep_on();
out_restore_irqs:
raw_local_irq_restore(flags);
preempt_enable();
return printed_len;
}
EXPORT_SYMBOL(printk);
EXPORT_SYMBOL(vprintk);
#else
static void call_console_drivers(unsigned start, unsigned end)
{
}
#endif
static int __add_preferred_console(char *name, int idx, char *options,
char *brl_options)
{
struct console_cmdline *c;
int i;
/*
* See if this tty is not yet registered, and
* if we have a slot free.
*/
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
if (strcmp(console_cmdline[i].name, name) == 0 &&
console_cmdline[i].index == idx) {
if (!brl_options)
selected_console = i;
return 0;
}
if (i == MAX_CMDLINECONSOLES)
return -E2BIG;
if (!brl_options)
selected_console = i;
c = &console_cmdline[i];
strlcpy(c->name, name, sizeof(c->name));
c->options = options;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
c->brl_options = brl_options;
#endif
c->index = idx;
return 0;
}
/*
* Set up a list of consoles. Called from init/main.c
*/
static int __init console_setup(char *str)
{
char buf[sizeof(console_cmdline[0].name) + 4]; /* 4 for index */
char *s, *options, *brl_options = NULL;
int idx;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (!memcmp(str, "brl,", 4)) {
brl_options = "";
str += 4;
} else if (!memcmp(str, "brl=", 4)) {
brl_options = str + 4;
str = strchr(brl_options, ',');
if (!str) {
printk(KERN_ERR "need port name after brl=\n");
return 1;
}
*(str++) = 0;
}
#endif
/*
* Decode str into name, index, options.
*/
if (str[0] >= '0' && str[0] <= '9') {
strcpy(buf, "ttyS");
strncpy(buf + 4, str, sizeof(buf) - 5);
} else {
strncpy(buf, str, sizeof(buf) - 1);
}
buf[sizeof(buf) - 1] = 0;
if ((options = strchr(str, ',')) != NULL)
*(options++) = 0;
#ifdef __sparc__
if (!strcmp(str, "ttya"))
strcpy(buf, "ttyS0");
if (!strcmp(str, "ttyb"))
strcpy(buf, "ttyS1");
#endif
for (s = buf; *s; s++)
if ((*s >= '0' && *s <= '9') || *s == ',')
break;
idx = simple_strtoul(s, NULL, 10);
*s = 0;
__add_preferred_console(buf, idx, options, brl_options);
console_set_on_cmdline = 1;
return 1;
}
__setup("console=", console_setup);
/**
* add_preferred_console - add a device to the list of preferred consoles.
* @name: device name
* @idx: device index
* @options: options for this console
*
* The last preferred console added will be used for kernel messages
* and stdin/out/err for init. Normally this is used by console_setup
* above to handle user-supplied console arguments; however it can also
* be used by arch-specific code either to override the user or more
* commonly to provide a default console (ie from PROM variables) when
* the user has not supplied one.
*/
int add_preferred_console(char *name, int idx, char *options)
{
return __add_preferred_console(name, idx, options, NULL);
}
int update_console_cmdline(char *name, int idx, char *name_new, int idx_new, char *options)
{
struct console_cmdline *c;
int i;
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0]; i++)
if (strcmp(console_cmdline[i].name, name) == 0 &&
console_cmdline[i].index == idx) {
c = &console_cmdline[i];
strlcpy(c->name, name_new, sizeof(c->name));
c->name[sizeof(c->name) - 1] = 0;
c->options = options;
c->index = idx_new;
return i;
}
/* not found */
return -1;
}
int console_suspend_enabled = 1;
EXPORT_SYMBOL(console_suspend_enabled);
static int __init console_suspend_disable(char *str)
{
console_suspend_enabled = 0;
return 1;
}
__setup("no_console_suspend", console_suspend_disable);
/**
* suspend_console - suspend the console subsystem
*
* This disables printk() while we go into suspend states
*/
void suspend_console(void)
{
if (!console_suspend_enabled)
return;
printk("Suspending console(s) (use no_console_suspend to debug)\n");
acquire_console_sem();
console_suspended = 1;
up(&console_sem);
}
void resume_console(void)
{
if (!console_suspend_enabled)
return;
down(&console_sem);
console_suspended = 0;
release_console_sem();
}
/**
* acquire_console_sem - lock the console system for exclusive use.
*
* Acquires a semaphore which guarantees that the caller has
* exclusive access to the console system and the console_drivers list.
*
* Can sleep, returns nothing.
*/
void acquire_console_sem(void)
{
BUG_ON(in_interrupt());
down(&console_sem);
if (console_suspended)
return;
console_locked = 1;
console_may_schedule = 1;
}
EXPORT_SYMBOL(acquire_console_sem);
int try_acquire_console_sem(void)
{
if (down_trylock(&console_sem))
return -1;
if (console_suspended) {
up(&console_sem);
return -1;
}
console_locked = 1;
console_may_schedule = 0;
return 0;
}
EXPORT_SYMBOL(try_acquire_console_sem);
int is_console_locked(void)
{
return console_locked;
}
static DEFINE_PER_CPU(int, printk_pending);
void printk_tick(void)
{
if (__get_cpu_var(printk_pending)) {
__get_cpu_var(printk_pending) = 0;
wake_up_interruptible(&log_wait);
}
}
int printk_needs_cpu(int cpu)
{
return per_cpu(printk_pending, cpu);
}
void wake_up_klogd(void)
{
if (waitqueue_active(&log_wait))
__raw_get_cpu_var(printk_pending) = 1;
}
/**
* release_console_sem - unlock the console system
*
* Releases the semaphore which the caller holds on the console system
* and the console driver list.
*
* While the semaphore was held, console output may have been buffered
* by printk(). If this is the case, release_console_sem() emits
* the output prior to releasing the semaphore.
*
* If there is output waiting for klogd, we wake it up.
*
* release_console_sem() may be called from any context.
*/
void release_console_sem(void)
{
unsigned long flags;
unsigned _con_start, _log_end;
unsigned wake_klogd = 0;
if (console_suspended) {
up(&console_sem);
return;
}
console_may_schedule = 0;
for ( ; ; ) {
spin_lock_irqsave(&logbuf_lock, flags);
wake_klogd |= log_start - log_end;
if (con_start == log_end)
break; /* Nothing to print */
_con_start = con_start;
_log_end = log_end;
con_start = log_end; /* Flush */
spin_unlock(&logbuf_lock);
stop_critical_timings(); /* don't trace print latency */
call_console_drivers(_con_start, _log_end);
start_critical_timings();
local_irq_restore(flags);
}
console_locked = 0;
up(&console_sem);
spin_unlock_irqrestore(&logbuf_lock, flags);
if (wake_klogd)
wake_up_klogd();
}
EXPORT_SYMBOL(release_console_sem);
/**
* console_conditional_schedule - yield the CPU if required
*
* If the console code is currently allowed to sleep, and
* if this CPU should yield the CPU to another task, do
* so here.
*
* Must be called within acquire_console_sem().
*/
void __sched console_conditional_schedule(void)
{
if (console_may_schedule)
cond_resched();
}
EXPORT_SYMBOL(console_conditional_schedule);
void console_print(const char *s)
{
printk(KERN_EMERG "%s", s);
}
EXPORT_SYMBOL(console_print);
void console_unblank(void)
{
struct console *c;
/*
* console_unblank can no longer be called in interrupt context unless
* oops_in_progress is set to 1..
*/
if (oops_in_progress) {
if (down_trylock(&console_sem) != 0)
return;
} else
acquire_console_sem();
console_locked = 1;
console_may_schedule = 0;
for (c = console_drivers; c != NULL; c = c->next)
if ((c->flags & CON_ENABLED) && c->unblank)
c->unblank();
release_console_sem();
}
/*
* Return the console tty driver structure and its associated index
*/
struct tty_driver *console_device(int *index)
{
struct console *c;
struct tty_driver *driver = NULL;
acquire_console_sem();
for (c = console_drivers; c != NULL; c = c->next) {
if (!c->device)
continue;
driver = c->device(c, index);
if (driver)
break;
}
release_console_sem();
return driver;
}
/*
* Prevent further output on the passed console device so that (for example)
* serial drivers can disable console output before suspending a port, and can
* re-enable output afterwards.
*/
void console_stop(struct console *console)
{
acquire_console_sem();
console->flags &= ~CON_ENABLED;
release_console_sem();
}
EXPORT_SYMBOL(console_stop);
void console_start(struct console *console)
{
acquire_console_sem();
console->flags |= CON_ENABLED;
release_console_sem();
}
EXPORT_SYMBOL(console_start);
/*
* The console driver calls this routine during kernel initialization
* to register the console printing procedure with printk() and to
* print any messages that were printed by the kernel before the
* console driver was initialized.
*/
void register_console(struct console *console)
{
int i;
unsigned long flags;
struct console *bootconsole = NULL;
if (console_drivers) {
if (console->flags & CON_BOOT)
return;
if (console_drivers->flags & CON_BOOT)
bootconsole = console_drivers;
}
if (preferred_console < 0 || bootconsole || !console_drivers)
preferred_console = selected_console;
if (console->early_setup)
console->early_setup();
/*
* See if we want to use this console driver. If we
* didn't select a console we take the first one
* that registers here.
*/
if (preferred_console < 0) {
if (console->index < 0)
console->index = 0;
if (console->setup == NULL ||
console->setup(console, NULL) == 0) {
console->flags |= CON_ENABLED;
if (console->device) {
console->flags |= CON_CONSDEV;
preferred_console = 0;
}
}
}
/*
* See if this console matches one we selected on
* the command line.
*/
for (i = 0; i < MAX_CMDLINECONSOLES && console_cmdline[i].name[0];
i++) {
if (strcmp(console_cmdline[i].name, console->name) != 0)
continue;
if (console->index >= 0 &&
console->index != console_cmdline[i].index)
continue;
if (console->index < 0)
console->index = console_cmdline[i].index;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (console_cmdline[i].brl_options) {
console->flags |= CON_BRL;
braille_register_console(console,
console_cmdline[i].index,
console_cmdline[i].options,
console_cmdline[i].brl_options);
return;
}
#endif
if (console->setup &&
console->setup(console, console_cmdline[i].options) != 0)
break;
console->flags |= CON_ENABLED;
console->index = console_cmdline[i].index;
if (i == selected_console) {
console->flags |= CON_CONSDEV;
preferred_console = selected_console;
}
break;
}
if (!(console->flags & CON_ENABLED))
return;
if (bootconsole && (console->flags & CON_CONSDEV)) {
printk(KERN_INFO "console handover: boot [%s%d] -> real [%s%d]\n",
bootconsole->name, bootconsole->index,
console->name, console->index);
unregister_console(bootconsole);
console->flags &= ~CON_PRINTBUFFER;
} else {
printk(KERN_INFO "console [%s%d] enabled\n",
console->name, console->index);
}
/*
* Put this console in the list - keep the
* preferred driver at the head of the list.
*/
acquire_console_sem();
if ((console->flags & CON_CONSDEV) || console_drivers == NULL) {
console->next = console_drivers;
console_drivers = console;
if (console->next)
console->next->flags &= ~CON_CONSDEV;
} else {
console->next = console_drivers->next;
console_drivers->next = console;
}
if (console->flags & CON_PRINTBUFFER) {
/*
* release_console_sem() will print out the buffered messages
* for us.
*/
spin_lock_irqsave(&logbuf_lock, flags);
con_start = log_start;
spin_unlock_irqrestore(&logbuf_lock, flags);
}
release_console_sem();
}
EXPORT_SYMBOL(register_console);
int unregister_console(struct console *console)
{
struct console *a, *b;
int res = 1;
#ifdef CONFIG_A11Y_BRAILLE_CONSOLE
if (console->flags & CON_BRL)
return braille_unregister_console(console);
#endif
acquire_console_sem();
if (console_drivers == console) {
console_drivers=console->next;
res = 0;
} else if (console_drivers) {
for (a=console_drivers->next, b=console_drivers ;
a; b=a, a=b->next) {
if (a == console) {
b->next = a->next;
res = 0;
break;
}
}
}
/*
* If this isn't the last console and it has CON_CONSDEV set, we
* need to set it on the next preferred console.
*/
if (console_drivers != NULL && console->flags & CON_CONSDEV)
console_drivers->flags |= CON_CONSDEV;
release_console_sem();
return res;
}
EXPORT_SYMBOL(unregister_console);
static int __init disable_boot_consoles(void)
{
if (console_drivers != NULL) {
if (console_drivers->flags & CON_BOOT) {
printk(KERN_INFO "turn off boot console %s%d\n",
console_drivers->name, console_drivers->index);
return unregister_console(console_drivers);
}
}
return 0;
}
late_initcall(disable_boot_consoles);
#if defined CONFIG_PRINTK
/*
* printk rate limiting, lifted from the networking subsystem.
*
* This enforces a rate limit: not more than 10 kernel messages
* every 5s to make a denial-of-service attack impossible.
*/
DEFINE_RATELIMIT_STATE(printk_ratelimit_state, 5 * HZ, 10);
int printk_ratelimit(void)
{
return __ratelimit(&printk_ratelimit_state);
}
EXPORT_SYMBOL(printk_ratelimit);
/**
* printk_timed_ratelimit - caller-controlled printk ratelimiting
* @caller_jiffies: pointer to caller's state
* @interval_msecs: minimum interval between prints
*
* printk_timed_ratelimit() returns true if more than @interval_msecs
* milliseconds have elapsed since the last time printk_timed_ratelimit()
* returned true.
*/
bool printk_timed_ratelimit(unsigned long *caller_jiffies,
unsigned int interval_msecs)
{
if (*caller_jiffies == 0 || time_after(jiffies, *caller_jiffies)) {
*caller_jiffies = jiffies + msecs_to_jiffies(interval_msecs);
return true;
}
return false;
}
EXPORT_SYMBOL(printk_timed_ratelimit);
#endif
| glfernando/linux-kernel-ipc | kernel/printk.c | C | gpl-2.0 | 32,592 |
module.exports={A:{A:{"1":"K C G E A B","16":"CB"},B:{"1":"D v Z I M H"},C:{"1":"0 1 2 3 5 6 7 y F J K C G E A B D v Z I M H N O P Q R S T U V W X Y x a b c d e f L h i j k l m n o p q r s t u z w TB SB","16":"VB"},D:{"1":"0 1 2 3 5 6 7 I M H N O P Q R S T U V W X Y x a b c d e f L h i j k l m n o p q r s t u z w HB g DB XB EB FB","16":"F J K C G E A B D v Z"},E:{"1":"J K C G E A B IB JB KB LB MB NB","16":"F GB AB"},F:{"1":"8 9 B D I M H N O P Q R S T U V W X Y x a b c d e f L h i j k l m n o p q r s t u UB BB","16":"E OB PB QB RB"},G:{"1":"4 G WB YB ZB aB bB cB dB eB fB gB","16":"AB"},H:{"1":"hB"},I:{"1":"4 y F g kB lB mB nB","16":"iB jB"},J:{"1":"C A"},K:{"1":"D L BB","16":"8 9 A B"},L:{"1":"g"},M:{"1":"w"},N:{"1":"A B"},O:{"1":"oB"},P:{"1":"F J pB"},Q:{"1":"qB"},R:{"1":"rB"}},B:5,C:"document.elementFromPoint()"};
| parkerjgit/openarch-d8 | themes/open_scratch/node_modules/caniuse-lite/data/features/element-from-point.js | JavaScript | gpl-2.0 | 828 |
/*
This file is part of VK/KittenPHP-DB-Engine.
VK/KittenPHP-DB-Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
VK/KittenPHP-DB-Engine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with VK/KittenPHP-DB-Engine. If not, see <http://www.gnu.org/licenses/>.
This program is released under the GPL with the additional exemption
that compiling, linking, and/or using OpenSSL is allowed.
You are free to remove this exemption from derived works.
Copyright 2013 Vkontakte Ltd
2013 Vitaliy Valtman
*/
#ifndef __SEARCH_TL_H__
#define __SEARCH_TL_H__
#include "TL/constants.h"
#define FLAG_SORT (1 << 1)
#define FLAG_SORT_DESC (1 << 2)
#define FLAG_RESTR (1 << 3)
#define FLAG_EXACT_HASH (1 << 4)
#define FLAG_GROUP_HASH (1 << 5)
#define FLAG_HASH_CHANGE (1 << 6)
#define FLAG_RELEVANCE (1 << 7)
#define FLAG_TITLE (1 << 8)
#define FLAG_OPTTAG (1 << 9)
#define FLAG_CUSTOM_RATE_WEIGHT (1 << 10)
#define FLAG_CUSTOM_PRIORITY_WEIGHT (1 << 11)
#define FLAG_DECAY (1 << 12)
#define FLAG_EXTENDED_MODE (1 << 13)
#define FLAG_OCCURANCE_COUNT (1 << 14)
#define FLAG_RAND (1 << 15)
#define FLAG_WEAK_SEARCH (1 << 16)
#define FLAG_SEARCHX (1 << 17)
#define FLAG_RETRY_SEARCH (1 << 30)
#endif
| vk-com/kphp-kdb | search/search-tl.h | C | gpl-2.0 | 1,689 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Ouro
SD%Complete: 85
SDComment: No model for submerging. Currently just invisible.
SDCategory: Temple of Ahn'Qiraj
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "temple_of_ahnqiraj.h"
enum Spells
{
SPELL_SWEEP = 26103,
SPELL_SANDBLAST = 26102,
SPELL_GROUND_RUPTURE = 26100,
SPELL_BIRTH = 26262, // The Birth Animation
SPELL_DIRTMOUND_PASSIVE = 26092
};
class boss_ouro : public CreatureScript
{
public:
boss_ouro() : CreatureScript("boss_ouro") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_ouroAI (creature);
}
struct boss_ouroAI : public ScriptedAI
{
boss_ouroAI(Creature* creature) : ScriptedAI(creature) {}
uint32 Sweep_Timer;
uint32 SandBlast_Timer;
uint32 Submerge_Timer;
uint32 Back_Timer;
uint32 ChangeTarget_Timer;
uint32 Spawn_Timer;
bool Enrage;
bool Submerged;
void Reset()
{
Sweep_Timer = urand(5000, 10000);
SandBlast_Timer = urand(20000, 35000);
Submerge_Timer = urand(90000, 150000);
Back_Timer = urand(30000, 45000);
ChangeTarget_Timer = urand(5000, 8000);
Spawn_Timer = urand(10000, 20000);
Enrage = false;
Submerged = false;
}
void EnterCombat(Unit* /*who*/)
{
DoCast(me->GetVictim(), SPELL_BIRTH);
}
void UpdateAI(uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
//Sweep_Timer
if (!Submerged && Sweep_Timer <= diff)
{
DoCast(me->GetVictim(), SPELL_SWEEP);
Sweep_Timer = urand(15000, 30000);
} else Sweep_Timer -= diff;
//SandBlast_Timer
if (!Submerged && SandBlast_Timer <= diff)
{
DoCast(me->GetVictim(), SPELL_SANDBLAST);
SandBlast_Timer = urand(20000, 35000);
} else SandBlast_Timer -= diff;
//Submerge_Timer
if (!Submerged && Submerge_Timer <= diff)
{
//Cast
me->HandleEmoteCommand(EMOTE_ONESHOT_SUBMERGE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->setFaction(35);
DoCast(me, SPELL_DIRTMOUND_PASSIVE);
Submerged = true;
Back_Timer = urand(30000, 45000);
} else Submerge_Timer -= diff;
//ChangeTarget_Timer
if (Submerged && ChangeTarget_Timer <= diff)
{
Unit* target = NULL;
target = SelectTarget(SELECT_TARGET_RANDOM, 0);
if (target)
DoTeleportTo(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ());
ChangeTarget_Timer = urand(10000, 20000);
} else ChangeTarget_Timer -= diff;
//Back_Timer
if (Submerged && Back_Timer <= diff)
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->setFaction(14);
DoCast(me->GetVictim(), SPELL_GROUND_RUPTURE);
Submerged = false;
Submerge_Timer = urand(60000, 120000);
} else Back_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_ouro()
{
new boss_ouro();
}
| Sakratus/TC-Cata | src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp | C++ | gpl-2.0 | 4,415 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\TestFramework\Isolation;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\App\DeploymentConfig\Reader;
/**
* A listener that watches for integrity of deployment configuration
*/
class DeploymentConfig
{
/**
* Deployment configuration reader
*
* @var Reader
*/
private $reader;
/**
* Initial value of deployment configuration
*
* @var mixed
*/
private $config;
/**
* Memorizes the initial value of configuration reader and the configuration value
*
* Assumption: this is done once right before executing very first test suite.
* It is assumed that deployment configuration is valid at this point
*
* @return void
*/
public function startTestSuite()
{
if (null === $this->reader) {
$this->reader = Bootstrap::getObjectManager()->get('Magento\Framework\App\DeploymentConfig\Reader');
$this->config = $this->reader->load();
}
}
/**
* Checks if deployment configuration has been changed by a test
*
* Changing deployment configuration violates isolation between tests, so further tests may become broken.
* To fix this issue, find out why this test changes deployment configuration.
* If this is intentional, then it must be reverted to the previous state within the test.
* After that, the application needs to be wiped out and reinstalled.
*
* @param \PHPUnit_Framework_TestCase $test
* @return void
*/
public function endTest(\PHPUnit_Framework_TestCase $test)
{
$config = $this->reader->load();
if ($this->config != $config) {
$error = "\n\nERROR: deployment configuration is corrupted. The application state is no longer valid.\n"
. 'Further tests may fail.'
. " This test failure may be misleading, if you are re-running it on a corrupted application.\n"
. $test->toString() . "\n";
$test->fail($error);
}
}
}
| FPLD/project0 | vendor/magento/magento2-base/dev/tests/integration/framework/Magento/TestFramework/Isolation/DeploymentConfig.php | PHP | gpl-2.0 | 2,168 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Downloadable\Test\Handler\DownloadableProduct;
use Magento\Catalog\Test\Handler\CatalogProductSimple\Curl as ProductCurl;
use Magento\Downloadable\Test\Fixture\DownloadableProduct;
use Magento\Mtf\Fixture\FixtureInterface;
use Magento\Mtf\Config\DataInterface;
use Magento\Mtf\System\Event\EventManagerInterface;
use Magento\Mtf\Util\Protocol\CurlTransport;
use Magento\Mtf\Util\Protocol\CurlTransport\BackendDecorator;
/**
* Class Curl
* Create new downloadable product via curl
*/
class Curl extends ProductCurl implements DownloadableProductInterface
{
/**
* Constructor
*
* @param DataInterface $configuration
* @param EventManagerInterface $eventManager
*/
public function __construct(DataInterface $configuration, EventManagerInterface $eventManager)
{
parent::__construct($configuration, $eventManager);
$this->mappingData += [
'links_purchased_separately' => [
'Yes' => 1,
'No' => 0,
],
'is_shareable' => [
'Yes' => 1,
'No' => 0,
'Use config' => 2,
],
];
}
/**
* Prepare POST data for creating product request
*
* @param FixtureInterface $fixture
* @param string|null $prefix [optional]
* @return array
*/
protected function prepareData(FixtureInterface $fixture, $prefix = null)
{
/** @var DownloadableProduct $fixture */
$fixtureData = parent::prepareData($fixture, $prefix);
$downloadableData = [
'downloadable_sample' => $fixture->getDownloadableSample(),
'downloadable_links' => $fixture->getDownloadableLinks()
];
$data = [];
if (!empty($downloadableData['downloadable_sample'])) {
foreach ($downloadableData['downloadable_sample']['downloadable']['sample'] as $key => $sample) {
$data['downloadable']['sample'][$key]['title'] = $sample['title'];
// only url type
$data['downloadable']['sample'][$key]['type'] = 'url';
$data['downloadable']['sample'][$key]['sample_url'] = $sample['sample_url'];
$data['downloadable']['sample'][$key]['sort_order'] = $sample['sort_order'];
}
$sampleTitle = $downloadableData['downloadable_sample']['title'];
$data['samples_title'] = $prefix ? [$prefix => $sampleTitle] : $sampleTitle;
unset($data['downloadable_sample']);
}
if (!empty($downloadableData['downloadable_links'])) {
foreach ($downloadableData['downloadable_links']['downloadable']['link'] as $key => $link) {
$data['downloadable']['link'][$key]['title'] = $link['title'];
// only url type
$data['downloadable']['link'][$key]['type'] = 'url';
$data['downloadable']['link'][$key]['link_url'] = $link['file_link_url'];
$data['downloadable']['link'][$key]['price'] = $link['price'];
$data['downloadable']['link'][$key]['number_of_downloads'] = $link['number_of_downloads'];
$data['downloadable']['link'][$key]['is_shareable'] = $link['is_shareable'];
$data['downloadable']['link'][$key]['sample']['type'] = 'url';
$data['downloadable']['link'][$key]['sample']['url'] = $link['sample']['sample_url'];
}
$links = [
'links_title' => $downloadableData['downloadable_links']['title'],
'links_purchased_separately' => $downloadableData['downloadable_links']['links_purchased_separately']
];
$data = array_merge($data, $prefix ? [$prefix => $links] : $links);
unset($downloadableData['downloadable_links']);
}
$data = array_merge_recursive($fixtureData, $data);
return $this->replaceMappingData($data);
}
/**
* Create product via curl
*
* @param array $data
* @param array $config
* @return array
* @throws \Exception
*/
protected function createProduct(array $data, array $config)
{
$url = $this->getUrl($config);
$curl = new BackendDecorator(new CurlTransport(), $this->_configuration);
$curl->addOption(CURLOPT_HEADER, 1);
$curl->write($url, $data);
$response = $curl->read();
$curl->close();
if (!strpos($response, 'data-ui-id="messages-message-success"')) {
throw new \Exception("Product creation by curl handler was not successful! Response: $response");
}
preg_match("~Location: [^\s]*\/id\/(\d+)~", $response, $matches);
$checkoutData = isset($data['product']['checkout_data']) ? $data['product']['checkout_data'] : null;
if (isset($data['downloadable']['link'])) {
foreach ($data['downloadable']['link'] as $key => $link) {
preg_match('`"link_id":"(\d*?)","title":"' . $link['title'] . '"`', $response, $linkId);
if (isset($checkoutData['options']['links'][$key]['label'])) {
$checkoutData['options']['links'][$key]['id'] = $linkId[1];
}
}
}
return ['id' => $matches[1], 'checkout_data' => $checkoutData];
}
}
| FPLD/project0 | vendor/magento/magento2-base/dev/tests/functional/tests/app/Magento/Downloadable/Test/Handler/DownloadableProduct/Curl.php | PHP | gpl-2.0 | 5,457 |
/*
* Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License version 2.
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/completion.h>
#include <linux/buffer_head.h>
#include <linux/pagemap.h>
#include <linux/pagevec.h>
#include <linux/mpage.h>
#include <linux/fs.h>
#include <linux/writeback.h>
#include <linux/swap.h>
#include <linux/gfs2_ondisk.h>
#include <linux/backing-dev.h>
#include "gfs2.h"
#include "incore.h"
#include "bmap.h"
#include "glock.h"
#include "inode.h"
#include "log.h"
#include "meta_io.h"
#include "quota.h"
#include "trans.h"
#include "rgrp.h"
#include "super.h"
#include "util.h"
#include "glops.h"
void gfs2_page_add_databufs(struct gfs2_inode *ip, struct page *page,
unsigned int from, unsigned int to)
{
struct buffer_head *head = page_buffers(page);
unsigned int bsize = head->b_size;
struct buffer_head *bh;
unsigned int start, end;
for (bh = head, start = 0; bh != head || !start;
bh = bh->b_this_page, start = end) {
end = start + bsize;
if (end <= from || start >= to)
continue;
if (gfs2_is_jdata(ip))
set_buffer_uptodate(bh);
gfs2_trans_add_bh(ip->i_gl, bh, 0);
}
}
/**
* gfs2_get_block_noalloc - Fills in a buffer head with details about a block
* @inode: The inode
* @lblock: The block number to look up
* @bh_result: The buffer head to return the result in
* @create: Non-zero if we may add block to the file
*
* Returns: errno
*/
static int gfs2_get_block_noalloc(struct inode *inode, sector_t lblock,
struct buffer_head *bh_result, int create)
{
int error;
error = gfs2_block_map(inode, lblock, bh_result, 0);
if (error)
return error;
if (!buffer_mapped(bh_result))
return -EIO;
return 0;
}
static int gfs2_get_block_direct(struct inode *inode, sector_t lblock,
struct buffer_head *bh_result, int create)
{
return gfs2_block_map(inode, lblock, bh_result, 0);
}
/**
* gfs2_writepage_common - Common bits of writepage
* @page: The page to be written
* @wbc: The writeback control
*
* Returns: 1 if writepage is ok, otherwise an error code or zero if no error.
*/
static int gfs2_writepage_common(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
loff_t i_size = i_size_read(inode);
pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
unsigned offset;
if (gfs2_assert_withdraw(sdp, gfs2_glock_is_held_excl(ip->i_gl)))
goto out;
if (current->journal_info)
goto redirty;
/* Is the page fully outside i_size? (truncate in progress) */
offset = i_size & (PAGE_CACHE_SIZE-1);
if (page->index > end_index || (page->index == end_index && !offset)) {
page->mapping->a_ops->invalidatepage(page, 0);
goto out;
}
return 1;
redirty:
redirty_page_for_writepage(wbc, page);
out:
unlock_page(page);
return 0;
}
/**
* gfs2_writeback_writepage - Write page for writeback mappings
* @page: The page
* @wbc: The writeback control
*
*/
static int gfs2_writeback_writepage(struct page *page,
struct writeback_control *wbc)
{
int ret;
ret = gfs2_writepage_common(page, wbc);
if (ret <= 0)
return ret;
return nobh_writepage(page, gfs2_get_block_noalloc, wbc);
}
/**
* gfs2_ordered_writepage - Write page for ordered data files
* @page: The page to write
* @wbc: The writeback control
*
*/
static int gfs2_ordered_writepage(struct page *page,
struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
int ret;
ret = gfs2_writepage_common(page, wbc);
if (ret <= 0)
return ret;
if (!page_has_buffers(page)) {
create_empty_buffers(page, inode->i_sb->s_blocksize,
(1 << BH_Dirty)|(1 << BH_Uptodate));
}
gfs2_page_add_databufs(ip, page, 0, inode->i_sb->s_blocksize-1);
return block_write_full_page(page, gfs2_get_block_noalloc, wbc);
}
/**
* __gfs2_jdata_writepage - The core of jdata writepage
* @page: The page to write
* @wbc: The writeback control
*
* This is shared between writepage and writepages and implements the
* core of the writepage operation. If a transaction is required then
* PageChecked will have been set and the transaction will have
* already been started before this is called.
*/
static int __gfs2_jdata_writepage(struct page *page, struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
if (PageChecked(page)) {
ClearPageChecked(page);
if (!page_has_buffers(page)) {
create_empty_buffers(page, inode->i_sb->s_blocksize,
(1 << BH_Dirty)|(1 << BH_Uptodate));
}
gfs2_page_add_databufs(ip, page, 0, sdp->sd_vfs->s_blocksize-1);
}
return block_write_full_page(page, gfs2_get_block_noalloc, wbc);
}
/**
* gfs2_jdata_writepage - Write complete page
* @page: Page to write
*
* Returns: errno
*
*/
static int gfs2_jdata_writepage(struct page *page, struct writeback_control *wbc)
{
struct inode *inode = page->mapping->host;
struct gfs2_sbd *sdp = GFS2_SB(inode);
int ret;
int done_trans = 0;
if (PageChecked(page)) {
if (wbc->sync_mode != WB_SYNC_ALL)
goto out_ignore;
ret = gfs2_trans_begin(sdp, RES_DINODE + 1, 0);
if (ret)
goto out_ignore;
done_trans = 1;
}
ret = gfs2_writepage_common(page, wbc);
if (ret > 0)
ret = __gfs2_jdata_writepage(page, wbc);
if (done_trans)
gfs2_trans_end(sdp);
return ret;
out_ignore:
redirty_page_for_writepage(wbc, page);
unlock_page(page);
return 0;
}
/**
* gfs2_writeback_writepages - Write a bunch of dirty pages back to disk
* @mapping: The mapping to write
* @wbc: Write-back control
*
* For the data=writeback case we can already ignore buffer heads
* and write whole extents at once. This is a big reduction in the
* number of I/O requests we send and the bmap calls we make in this case.
*/
static int gfs2_writeback_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
return mpage_writepages(mapping, wbc, gfs2_get_block_noalloc);
}
/**
* gfs2_write_jdata_pagevec - Write back a pagevec's worth of pages
* @mapping: The mapping
* @wbc: The writeback control
* @writepage: The writepage function to call for each page
* @pvec: The vector of pages
* @nr_pages: The number of pages to write
*
* Returns: non-zero if loop should terminate, zero otherwise
*/
static int gfs2_write_jdata_pagevec(struct address_space *mapping,
struct writeback_control *wbc,
struct pagevec *pvec,
int nr_pages, pgoff_t end)
{
struct inode *inode = mapping->host;
struct gfs2_sbd *sdp = GFS2_SB(inode);
loff_t i_size = i_size_read(inode);
pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
unsigned offset = i_size & (PAGE_CACHE_SIZE-1);
unsigned nrblocks = nr_pages * (PAGE_CACHE_SIZE/inode->i_sb->s_blocksize);
int i;
int ret;
ret = gfs2_trans_begin(sdp, nrblocks, nrblocks);
if (ret < 0)
return ret;
for(i = 0; i < nr_pages; i++) {
struct page *page = pvec->pages[i];
lock_page(page);
if (unlikely(page->mapping != mapping)) {
unlock_page(page);
continue;
}
if (!wbc->range_cyclic && page->index > end) {
ret = 1;
unlock_page(page);
continue;
}
if (wbc->sync_mode != WB_SYNC_NONE)
wait_on_page_writeback(page);
if (PageWriteback(page) ||
!clear_page_dirty_for_io(page)) {
unlock_page(page);
continue;
}
/* Is the page fully outside i_size? (truncate in progress) */
if (page->index > end_index || (page->index == end_index && !offset)) {
page->mapping->a_ops->invalidatepage(page, 0);
unlock_page(page);
continue;
}
ret = __gfs2_jdata_writepage(page, wbc);
if (ret || (--(wbc->nr_to_write) <= 0))
ret = 1;
}
gfs2_trans_end(sdp);
return ret;
}
/**
* gfs2_write_cache_jdata - Like write_cache_pages but different
* @mapping: The mapping to write
* @wbc: The writeback control
* @writepage: The writepage function to call
* @data: The data to pass to writepage
*
* The reason that we use our own function here is that we need to
* start transactions before we grab page locks. This allows us
* to get the ordering right.
*/
static int gfs2_write_cache_jdata(struct address_space *mapping,
struct writeback_control *wbc)
{
int ret = 0;
int done = 0;
struct pagevec pvec;
int nr_pages;
pgoff_t index;
pgoff_t end;
int scanned = 0;
int range_whole = 0;
pagevec_init(&pvec, 0);
if (wbc->range_cyclic) {
index = mapping->writeback_index; /* Start from prev offset */
end = -1;
} else {
index = wbc->range_start >> PAGE_CACHE_SHIFT;
end = wbc->range_end >> PAGE_CACHE_SHIFT;
if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
range_whole = 1;
scanned = 1;
}
retry:
while (!done && (index <= end) &&
(nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
PAGECACHE_TAG_DIRTY,
min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1))) {
scanned = 1;
ret = gfs2_write_jdata_pagevec(mapping, wbc, &pvec, nr_pages, end);
if (ret)
done = 1;
if (ret > 0)
ret = 0;
pagevec_release(&pvec);
cond_resched();
}
if (!scanned && !done) {
/*
* We hit the last page and there is more work to be done: wrap
* back to the start of the file
*/
scanned = 1;
index = 0;
goto retry;
}
if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
mapping->writeback_index = index;
return ret;
}
/**
* gfs2_jdata_writepages - Write a bunch of dirty pages back to disk
* @mapping: The mapping to write
* @wbc: The writeback control
*
*/
static int gfs2_jdata_writepages(struct address_space *mapping,
struct writeback_control *wbc)
{
struct gfs2_inode *ip = GFS2_I(mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(mapping->host);
int ret;
ret = gfs2_write_cache_jdata(mapping, wbc);
if (ret == 0 && wbc->sync_mode == WB_SYNC_ALL) {
gfs2_log_flush(sdp, ip->i_gl);
ret = gfs2_write_cache_jdata(mapping, wbc);
}
return ret;
}
/**
* stuffed_readpage - Fill in a Linux page with stuffed file data
* @ip: the inode
* @page: the page
*
* Returns: errno
*/
static int stuffed_readpage(struct gfs2_inode *ip, struct page *page)
{
struct buffer_head *dibh;
u64 dsize = i_size_read(&ip->i_inode);
void *kaddr;
int error;
/*
* Due to the order of unstuffing files and ->fault(), we can be
* asked for a zero page in the case of a stuffed file being extended,
* so we need to supply one here. It doesn't happen often.
*/
if (unlikely(page->index)) {
zero_user(page, 0, PAGE_CACHE_SIZE);
SetPageUptodate(page);
return 0;
}
error = gfs2_meta_inode_buffer(ip, &dibh);
if (error)
return error;
kaddr = kmap_atomic(page, KM_USER0);
if (dsize > (dibh->b_size - sizeof(struct gfs2_dinode)))
dsize = (dibh->b_size - sizeof(struct gfs2_dinode));
memcpy(kaddr, dibh->b_data + sizeof(struct gfs2_dinode), dsize);
memset(kaddr + dsize, 0, PAGE_CACHE_SIZE - dsize);
kunmap_atomic(kaddr, KM_USER0);
flush_dcache_page(page);
brelse(dibh);
SetPageUptodate(page);
return 0;
}
/**
* __gfs2_readpage - readpage
* @file: The file to read a page for
* @page: The page to read
*
* This is the core of gfs2's readpage. Its used by the internal file
* reading code as in that case we already hold the glock. Also its
* called by gfs2_readpage() once the required lock has been granted.
*
*/
static int __gfs2_readpage(void *file, struct page *page)
{
struct gfs2_inode *ip = GFS2_I(page->mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(page->mapping->host);
int error;
if (gfs2_is_stuffed(ip)) {
error = stuffed_readpage(ip, page);
unlock_page(page);
} else {
error = mpage_readpage(page, gfs2_block_map);
}
if (unlikely(test_bit(SDF_SHUTDOWN, &sdp->sd_flags)))
return -EIO;
return error;
}
/**
* gfs2_readpage - read a page of a file
* @file: The file to read
* @page: The page of the file
*
* This deals with the locking required. We have to unlock and
* relock the page in order to get the locking in the right
* order.
*/
static int gfs2_readpage(struct file *file, struct page *page)
{
struct address_space *mapping = page->mapping;
struct gfs2_inode *ip = GFS2_I(mapping->host);
struct gfs2_holder gh;
int error;
unlock_page(page);
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
error = gfs2_glock_nq(&gh);
if (unlikely(error))
goto out;
error = AOP_TRUNCATED_PAGE;
lock_page(page);
if (page->mapping == mapping && !PageUptodate(page))
error = __gfs2_readpage(file, page);
else
unlock_page(page);
gfs2_glock_dq(&gh);
out:
gfs2_holder_uninit(&gh);
if (error && error != AOP_TRUNCATED_PAGE)
lock_page(page);
return error;
}
/**
* gfs2_internal_read - read an internal file
* @ip: The gfs2 inode
* @ra_state: The readahead state (or NULL for no readahead)
* @buf: The buffer to fill
* @pos: The file position
* @size: The amount to read
*
*/
int gfs2_internal_read(struct gfs2_inode *ip, struct file_ra_state *ra_state,
char *buf, loff_t *pos, unsigned size)
{
struct address_space *mapping = ip->i_inode.i_mapping;
unsigned long index = *pos / PAGE_CACHE_SIZE;
unsigned offset = *pos & (PAGE_CACHE_SIZE - 1);
unsigned copied = 0;
unsigned amt;
struct page *page;
void *p;
do {
amt = size - copied;
if (offset + size > PAGE_CACHE_SIZE)
amt = PAGE_CACHE_SIZE - offset;
page = read_cache_page(mapping, index, __gfs2_readpage, NULL);
if (IS_ERR(page))
return PTR_ERR(page);
p = kmap_atomic(page, KM_USER0);
memcpy(buf + copied, p + offset, amt);
kunmap_atomic(p, KM_USER0);
mark_page_accessed(page);
page_cache_release(page);
copied += amt;
index++;
offset = 0;
} while(copied < size);
(*pos) += size;
return size;
}
/**
* gfs2_readpages - Read a bunch of pages at once
*
* Some notes:
* 1. This is only for readahead, so we can simply ignore any things
* which are slightly inconvenient (such as locking conflicts between
* the page lock and the glock) and return having done no I/O. Its
* obviously not something we'd want to do on too regular a basis.
* Any I/O we ignore at this time will be done via readpage later.
* 2. We don't handle stuffed files here we let readpage do the honours.
* 3. mpage_readpages() does most of the heavy lifting in the common case.
* 4. gfs2_block_map() is relied upon to set BH_Boundary in the right places.
*/
static int gfs2_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
struct inode *inode = mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_holder gh;
int ret;
gfs2_holder_init(ip->i_gl, LM_ST_SHARED, 0, &gh);
ret = gfs2_glock_nq(&gh);
if (unlikely(ret))
goto out_uninit;
if (!gfs2_is_stuffed(ip))
ret = mpage_readpages(mapping, pages, nr_pages, gfs2_block_map);
gfs2_glock_dq(&gh);
out_uninit:
gfs2_holder_uninit(&gh);
if (unlikely(test_bit(SDF_SHUTDOWN, &sdp->sd_flags)))
ret = -EIO;
return ret;
}
/**
* gfs2_write_begin - Begin to write to a file
* @file: The file to write to
* @mapping: The mapping in which to write
* @pos: The file offset at which to start writing
* @len: Length of the write
* @flags: Various flags
* @pagep: Pointer to return the page
* @fsdata: Pointer to return fs data (unused by GFS2)
*
* Returns: errno
*/
static int gfs2_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
struct gfs2_inode *ip = GFS2_I(mapping->host);
struct gfs2_sbd *sdp = GFS2_SB(mapping->host);
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
unsigned int data_blocks = 0, ind_blocks = 0, rblocks;
int alloc_required;
int error = 0;
struct gfs2_alloc *al = NULL;
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
unsigned from = pos & (PAGE_CACHE_SIZE - 1);
struct page *page;
gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh);
error = gfs2_glock_nq(&ip->i_gh);
if (unlikely(error))
goto out_uninit;
if (&ip->i_inode == sdp->sd_rindex) {
error = gfs2_glock_nq_init(m_ip->i_gl, LM_ST_EXCLUSIVE,
GL_NOCACHE, &m_ip->i_gh);
if (unlikely(error)) {
gfs2_glock_dq(&ip->i_gh);
goto out_uninit;
}
}
alloc_required = gfs2_write_alloc_required(ip, pos, len);
if (alloc_required || gfs2_is_jdata(ip))
gfs2_write_calc_reserv(ip, len, &data_blocks, &ind_blocks);
if (alloc_required) {
al = gfs2_alloc_get(ip);
if (!al) {
error = -ENOMEM;
goto out_unlock;
}
error = gfs2_quota_lock_check(ip);
if (error)
goto out_alloc_put;
al->al_requested = data_blocks + ind_blocks;
error = gfs2_inplace_reserve(ip);
if (error)
goto out_qunlock;
}
rblocks = RES_DINODE + ind_blocks;
if (gfs2_is_jdata(ip))
rblocks += data_blocks ? data_blocks : 1;
if (ind_blocks || data_blocks)
rblocks += RES_STATFS + RES_QUOTA;
if (&ip->i_inode == sdp->sd_rindex)
rblocks += 2 * RES_STATFS;
if (alloc_required)
rblocks += gfs2_rg_blocks(al);
error = gfs2_trans_begin(sdp, rblocks,
PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize);
if (error)
goto out_trans_fail;
error = -ENOMEM;
flags |= AOP_FLAG_NOFS;
page = grab_cache_page_write_begin(mapping, index, flags);
*pagep = page;
if (unlikely(!page))
goto out_endtrans;
if (gfs2_is_stuffed(ip)) {
error = 0;
if (pos + len > sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode)) {
error = gfs2_unstuff_dinode(ip, page);
if (error == 0)
goto prepare_write;
} else if (!PageUptodate(page)) {
error = stuffed_readpage(ip, page);
}
goto out;
}
prepare_write:
error = __block_write_begin(page, from, len, gfs2_block_map);
out:
if (error == 0)
return 0;
unlock_page(page);
page_cache_release(page);
gfs2_trans_end(sdp);
if (pos + len > ip->i_inode.i_size)
gfs2_trim_blocks(&ip->i_inode);
goto out_trans_fail;
out_endtrans:
gfs2_trans_end(sdp);
out_trans_fail:
if (alloc_required) {
gfs2_inplace_release(ip);
out_qunlock:
gfs2_quota_unlock(ip);
out_alloc_put:
gfs2_alloc_put(ip);
}
out_unlock:
if (&ip->i_inode == sdp->sd_rindex) {
gfs2_glock_dq(&m_ip->i_gh);
gfs2_holder_uninit(&m_ip->i_gh);
}
gfs2_glock_dq(&ip->i_gh);
out_uninit:
gfs2_holder_uninit(&ip->i_gh);
return error;
}
/**
* adjust_fs_space - Adjusts the free space available due to gfs2_grow
* @inode: the rindex inode
*/
static void adjust_fs_space(struct inode *inode)
{
struct gfs2_sbd *sdp = inode->i_sb->s_fs_info;
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
struct gfs2_inode *l_ip = GFS2_I(sdp->sd_sc_inode);
struct gfs2_statfs_change_host *m_sc = &sdp->sd_statfs_master;
struct gfs2_statfs_change_host *l_sc = &sdp->sd_statfs_local;
struct buffer_head *m_bh, *l_bh;
u64 fs_total, new_free;
/* Total up the file system space, according to the latest rindex. */
fs_total = gfs2_ri_total(sdp);
if (gfs2_meta_inode_buffer(m_ip, &m_bh) != 0)
return;
spin_lock(&sdp->sd_statfs_spin);
gfs2_statfs_change_in(m_sc, m_bh->b_data +
sizeof(struct gfs2_dinode));
if (fs_total > (m_sc->sc_total + l_sc->sc_total))
new_free = fs_total - (m_sc->sc_total + l_sc->sc_total);
else
new_free = 0;
spin_unlock(&sdp->sd_statfs_spin);
fs_warn(sdp, "File system extended by %llu blocks.\n",
(unsigned long long)new_free);
gfs2_statfs_change(sdp, new_free, new_free, 0);
if (gfs2_meta_inode_buffer(l_ip, &l_bh) != 0)
goto out;
update_statfs(sdp, m_bh, l_bh);
brelse(l_bh);
out:
brelse(m_bh);
}
/**
* gfs2_stuffed_write_end - Write end for stuffed files
* @inode: The inode
* @dibh: The buffer_head containing the on-disk inode
* @pos: The file position
* @len: The length of the write
* @copied: How much was actually copied by the VFS
* @page: The page
*
* This copies the data from the page into the inode block after
* the inode data structure itself.
*
* Returns: errno
*/
static int gfs2_stuffed_write_end(struct inode *inode, struct buffer_head *dibh,
loff_t pos, unsigned len, unsigned copied,
struct page *page)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
u64 to = pos + copied;
void *kaddr;
unsigned char *buf = dibh->b_data + sizeof(struct gfs2_dinode);
struct gfs2_dinode *di = (struct gfs2_dinode *)dibh->b_data;
BUG_ON((pos + len) > (dibh->b_size - sizeof(struct gfs2_dinode)));
kaddr = kmap_atomic(page, KM_USER0);
memcpy(buf + pos, kaddr + pos, copied);
memset(kaddr + pos + copied, 0, len - copied);
flush_dcache_page(page);
kunmap_atomic(kaddr, KM_USER0);
if (!PageUptodate(page))
SetPageUptodate(page);
unlock_page(page);
page_cache_release(page);
if (copied) {
if (inode->i_size < to)
i_size_write(inode, to);
gfs2_dinode_out(ip, di);
mark_inode_dirty(inode);
}
if (inode == sdp->sd_rindex) {
adjust_fs_space(inode);
ip->i_gh.gh_flags |= GL_NOCACHE;
}
brelse(dibh);
gfs2_trans_end(sdp);
if (inode == sdp->sd_rindex) {
gfs2_glock_dq(&m_ip->i_gh);
gfs2_holder_uninit(&m_ip->i_gh);
}
gfs2_glock_dq(&ip->i_gh);
gfs2_holder_uninit(&ip->i_gh);
return copied;
}
/**
* gfs2_write_end
* @file: The file to write to
* @mapping: The address space to write to
* @pos: The file position
* @len: The length of the data
* @copied:
* @page: The page that has been written
* @fsdata: The fsdata (unused in GFS2)
*
* The main write_end function for GFS2. We have a separate one for
* stuffed files as they are slightly different, otherwise we just
* put our locking around the VFS provided functions.
*
* Returns: errno
*/
static int gfs2_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
struct inode *inode = page->mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_sbd *sdp = GFS2_SB(inode);
struct gfs2_inode *m_ip = GFS2_I(sdp->sd_statfs_inode);
struct buffer_head *dibh;
struct gfs2_alloc *al = ip->i_alloc;
unsigned int from = pos & (PAGE_CACHE_SIZE - 1);
unsigned int to = from + len;
int ret;
BUG_ON(gfs2_glock_is_locked_by_me(ip->i_gl) == NULL);
ret = gfs2_meta_inode_buffer(ip, &dibh);
if (unlikely(ret)) {
unlock_page(page);
page_cache_release(page);
goto failed;
}
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (gfs2_is_stuffed(ip))
return gfs2_stuffed_write_end(inode, dibh, pos, len, copied, page);
if (!gfs2_is_writeback(ip))
gfs2_page_add_databufs(ip, page, from, to);
ret = generic_write_end(file, mapping, pos, len, copied, page, fsdata);
if (ret > 0) {
gfs2_dinode_out(ip, dibh->b_data);
mark_inode_dirty(inode);
}
if (inode == sdp->sd_rindex) {
adjust_fs_space(inode);
ip->i_gh.gh_flags |= GL_NOCACHE;
}
brelse(dibh);
failed:
gfs2_trans_end(sdp);
if (al) {
gfs2_inplace_release(ip);
gfs2_quota_unlock(ip);
gfs2_alloc_put(ip);
}
if (inode == sdp->sd_rindex) {
gfs2_glock_dq(&m_ip->i_gh);
gfs2_holder_uninit(&m_ip->i_gh);
}
gfs2_glock_dq(&ip->i_gh);
gfs2_holder_uninit(&ip->i_gh);
return ret;
}
/**
* gfs2_set_page_dirty - Page dirtying function
* @page: The page to dirty
*
* Returns: 1 if it dirtyed the page, or 0 otherwise
*/
static int gfs2_set_page_dirty(struct page *page)
{
SetPageChecked(page);
return __set_page_dirty_buffers(page);
}
/**
* gfs2_bmap - Block map function
* @mapping: Address space info
* @lblock: The block to map
*
* Returns: The disk address for the block or 0 on hole or error
*/
static sector_t gfs2_bmap(struct address_space *mapping, sector_t lblock)
{
struct gfs2_inode *ip = GFS2_I(mapping->host);
struct gfs2_holder i_gh;
sector_t dblock = 0;
int error;
error = gfs2_glock_nq_init(ip->i_gl, LM_ST_SHARED, LM_FLAG_ANY, &i_gh);
if (error)
return 0;
if (!gfs2_is_stuffed(ip))
dblock = generic_block_bmap(mapping, lblock, gfs2_block_map);
gfs2_glock_dq_uninit(&i_gh);
return dblock;
}
static void gfs2_discard(struct gfs2_sbd *sdp, struct buffer_head *bh)
{
struct gfs2_bufdata *bd;
lock_buffer(bh);
gfs2_log_lock(sdp);
clear_buffer_dirty(bh);
bd = bh->b_private;
if (bd) {
if (!list_empty(&bd->bd_le.le_list) && !buffer_pinned(bh))
list_del_init(&bd->bd_le.le_list);
else
gfs2_remove_from_journal(bh, current->journal_info, 0);
}
bh->b_bdev = NULL;
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
gfs2_log_unlock(sdp);
unlock_buffer(bh);
}
static void gfs2_invalidatepage(struct page *page, unsigned long offset)
{
struct gfs2_sbd *sdp = GFS2_SB(page->mapping->host);
struct buffer_head *bh, *head;
unsigned long pos = 0;
BUG_ON(!PageLocked(page));
if (offset == 0)
ClearPageChecked(page);
if (!page_has_buffers(page))
goto out;
bh = head = page_buffers(page);
do {
if (offset <= pos)
gfs2_discard(sdp, bh);
pos += bh->b_size;
bh = bh->b_this_page;
} while (bh != head);
out:
if (offset == 0)
try_to_release_page(page, 0);
}
/**
* gfs2_ok_for_dio - check that dio is valid on this file
* @ip: The inode
* @rw: READ or WRITE
* @offset: The offset at which we are reading or writing
*
* Returns: 0 (to ignore the i/o request and thus fall back to buffered i/o)
* 1 (to accept the i/o request)
*/
static int gfs2_ok_for_dio(struct gfs2_inode *ip, int rw, loff_t offset)
{
/*
* Should we return an error here? I can't see that O_DIRECT for
* a stuffed file makes any sense. For now we'll silently fall
* back to buffered I/O
*/
if (gfs2_is_stuffed(ip))
return 0;
if (offset >= i_size_read(&ip->i_inode))
return 0;
return 1;
}
static ssize_t gfs2_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct inode *inode = file->f_mapping->host;
struct gfs2_inode *ip = GFS2_I(inode);
struct gfs2_holder gh;
int rv;
/*
* Deferred lock, even if its a write, since we do no allocation
* on this path. All we need change is atime, and this lock mode
* ensures that other nodes have flushed their buffered read caches
* (i.e. their page cache entries for this inode). We do not,
* unfortunately have the option of only flushing a range like
* the VFS does.
*/
gfs2_holder_init(ip->i_gl, LM_ST_DEFERRED, 0, &gh);
rv = gfs2_glock_nq(&gh);
if (rv)
return rv;
rv = gfs2_ok_for_dio(ip, rw, offset);
if (rv != 1)
goto out; /* dio not valid, fall back to buffered i/o */
rv = __blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
offset, nr_segs, gfs2_get_block_direct,
NULL, NULL, 0);
out:
gfs2_glock_dq_m(1, &gh);
gfs2_holder_uninit(&gh);
return rv;
}
/**
* gfs2_releasepage - free the metadata associated with a page
* @page: the page that's being released
* @gfp_mask: passed from Linux VFS, ignored by us
*
* Call try_to_free_buffers() if the buffers in this page can be
* released.
*
* Returns: 0
*/
int gfs2_releasepage(struct page *page, gfp_t gfp_mask)
{
struct address_space *mapping = page->mapping;
struct gfs2_sbd *sdp = gfs2_mapping2sbd(mapping);
struct buffer_head *bh, *head;
struct gfs2_bufdata *bd;
if (!page_has_buffers(page))
return 0;
gfs2_log_lock(sdp);
head = bh = page_buffers(page);
do {
if (atomic_read(&bh->b_count))
goto cannot_release;
bd = bh->b_private;
if (bd && bd->bd_ail)
goto cannot_release;
if (buffer_pinned(bh) || buffer_dirty(bh))
goto not_possible;
bh = bh->b_this_page;
} while(bh != head);
gfs2_log_unlock(sdp);
head = bh = page_buffers(page);
do {
gfs2_log_lock(sdp);
bd = bh->b_private;
if (bd) {
gfs2_assert_warn(sdp, bd->bd_bh == bh);
gfs2_assert_warn(sdp, list_empty(&bd->bd_list_tr));
if (!list_empty(&bd->bd_le.le_list)) {
if (!buffer_pinned(bh))
list_del_init(&bd->bd_le.le_list);
else
bd = NULL;
}
if (bd)
bd->bd_bh = NULL;
bh->b_private = NULL;
}
gfs2_log_unlock(sdp);
if (bd)
kmem_cache_free(gfs2_bufdata_cachep, bd);
bh = bh->b_this_page;
} while (bh != head);
return try_to_free_buffers(page);
not_possible: /* Should never happen */
WARN_ON(buffer_dirty(bh));
WARN_ON(buffer_pinned(bh));
cannot_release:
gfs2_log_unlock(sdp);
return 0;
}
static const struct address_space_operations gfs2_writeback_aops = {
.writepage = gfs2_writeback_writepage,
.writepages = gfs2_writeback_writepages,
.readpage = gfs2_readpage,
.readpages = gfs2_readpages,
.write_begin = gfs2_write_begin,
.write_end = gfs2_write_end,
.bmap = gfs2_bmap,
.invalidatepage = gfs2_invalidatepage,
.releasepage = gfs2_releasepage,
.direct_IO = gfs2_direct_IO,
.migratepage = buffer_migrate_page,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations gfs2_ordered_aops = {
.writepage = gfs2_ordered_writepage,
.readpage = gfs2_readpage,
.readpages = gfs2_readpages,
.write_begin = gfs2_write_begin,
.write_end = gfs2_write_end,
.set_page_dirty = gfs2_set_page_dirty,
.bmap = gfs2_bmap,
.invalidatepage = gfs2_invalidatepage,
.releasepage = gfs2_releasepage,
.direct_IO = gfs2_direct_IO,
.migratepage = buffer_migrate_page,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
static const struct address_space_operations gfs2_jdata_aops = {
.writepage = gfs2_jdata_writepage,
.writepages = gfs2_jdata_writepages,
.readpage = gfs2_readpage,
.readpages = gfs2_readpages,
.write_begin = gfs2_write_begin,
.write_end = gfs2_write_end,
.set_page_dirty = gfs2_set_page_dirty,
.bmap = gfs2_bmap,
.invalidatepage = gfs2_invalidatepage,
.releasepage = gfs2_releasepage,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
void gfs2_set_aops(struct inode *inode)
{
struct gfs2_inode *ip = GFS2_I(inode);
if (gfs2_is_writeback(ip))
inode->i_mapping->a_ops = &gfs2_writeback_aops;
else if (gfs2_is_ordered(ip))
inode->i_mapping->a_ops = &gfs2_ordered_aops;
else if (gfs2_is_jdata(ip))
inode->i_mapping->a_ops = &gfs2_jdata_aops;
else
BUG();
}
| bcnice20/android-kernel-common | fs/gfs2/aops.c | C | gpl-2.0 | 30,429 |
/* -*- c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Copyright(C) 2010 Tetsuro IKEDA
Copyright(C) 2010-2013 Kentoku SHIBA
Copyright(C) 2011-2017 Kouhei Sutou <kou@clear-code.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*/
#include <mrn_mysql.h>
#include <mrn_windows.hpp>
#include <mrn_table.hpp>
#include <mrn_macro.hpp>
#include <mrn_current_thread.hpp>
MRN_BEGIN_DECLS
MRN_API my_bool last_insert_grn_id_init(UDF_INIT *init, UDF_ARGS *args, char *message)
{
if (args->arg_count != 0) {
strcpy(message, "last_insert_grn_id must not have arguments");
return 1;
}
init->maybe_null = 0;
return 0;
}
MRN_API longlong last_insert_grn_id(UDF_INIT *init, UDF_ARGS *args, char *is_null, char *error)
{
THD *thd = current_thd;
st_mrn_slot_data *slot_data = mrn_get_slot_data(thd, false);
if (slot_data == NULL) {
return 0;
}
longlong last_insert_record_id = slot_data->last_insert_record_id;
return last_insert_record_id;
}
MRN_API void last_insert_grn_id_deinit(UDF_INIT *init)
{
}
MRN_END_DECLS
| MariaDB/server | storage/mroonga/udf/mrn_udf_last_insert_grn_id.cpp | C++ | gpl-2.0 | 1,726 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var $cacheTypeList \Magento\Framework\App\Cache\TypeListInterface */
$cacheTypeList = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
'Magento\Framework\App\Cache\TypeListInterface'
);
$cacheTypeList->invalidate(array_keys($cacheTypeList->getTypes()));
| FPLD/project0 | vendor/magento/magento2-base/dev/tests/integration/testsuite/Magento/Backend/controllers/_files/cache/all_types_invalidated.php | PHP | gpl-2.0 | 389 |
<?php
/**
* @version $Id$
* @package JSNExtension
* @subpackage TPLFramework
* @author JoomlaShine Team <support@joomlashine.com>
* @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
* @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.joomlashine.com
* Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$utils = JSNTplUtils::getInstance();
// Get all fieldset in XML
$fieldSets = $adminFormXml->fields->fieldset;
// Set appropriate wrapper class
$wrapperClass = 'jsn-joomla' . JSNTplHelper::getJoomlaVersion(1, false);
// Get template details
$template = JSNTplTemplateRecognization::detect($this->data->template);
// Prepare template name for link generation
$templateName = 'jsn-' . strtolower($template->name);
// Generate template introduction link
$templateLink = "http://www.joomlashine.com/joomla-templates/{$templateName}.html";
// Process template edition
$edition = $this->templateEdition->getEdition();
if ($edition == 'FREE')
{
$editionClass = 'jsn-free-edition';
}
else
{
$editionClass = 'jsn-pro-edition';
}
// Get next template edition
$nextEdition = str_replace('PRO ', '', $this->templateEdition->getNextEdition());
// Get installed template version
$version = JSNTplHelper::getTemplateVersion($this->data->template);
// Get list of JoomlaShine template for cross promotion
$promotion = $nextEdition == 'STANDARD' ? true : false;
if ($promotion)
{
$config = JFactory::getConfig();
$cache = $config->get('tmp_path') . '/jsn_templates.json';
if ( ! @is_file($cache) || ! @is_readable($cache) || time() - filemtime($cache) > 86400)
{
try
{
$jsn_templates = JSNTplHttpRequest::get(
'http://demo.joomlashine.com/products-intro/assets/json/showlist-templates-' . ($nextEdition == 'STANDARD' ? 'free' : 'pro') . '.json',
$cache
);
$jsn_templates = $jsn_templates['body'];
}
catch (Exception $e)
{
// Disable cross promotion
$promotion = false;
}
}
else
{
$jsn_templates = JFile::read($cache);
}
if ($jsn_templates = json_decode($jsn_templates))
{
$jsn_templates = $jsn_templates->showlist->images->image;
}
else
{
$promotion = false;
}
}
$jversion = new JVersion();
$megamenu = (string) $this->templateXml->megamenu;
// Migrate megamenu data
if ($megamenu == 'yes')
{
if (version_compare($jversion->getShortVersion(), '3.0', ">="))
{
include_once JSN_PATH_TPLFRAMEWORK_MEGAMENU_LIBRARIES . '/helpers/megamenu.php';
JSNTplMMHelperMegamenu::migrate();
}
}
$plgTplBrand = $utils->checkPlgJSNBrand();
$showUpgradeButton = 1;
$showChangelog = 1;
$showThumbnailLink = 1;
$showCopyrightContent = 1;
$replaceFooterContent = 0;
$replaceGettingStartedContent = 0;
$replacedGettingStartedContent = '';
$replacedFooterContent = '';
if ($plgTplBrand)
{
$dispatcher = JEventDispatcher::getInstance();
$rload = JPluginHelper::importPlugin('system', 'jsnbrand');
if ($rload === true)
{
$showUpgradeButton = $dispatcher->trigger('showTplUpgradeButton');
$showUpgradeButton = (int) $showUpgradeButton[0];
$showChangelog = $dispatcher->trigger('showTplChangelog');
$showChangelog = (int) $showChangelog[0];
$showThumbnailLink = $dispatcher->trigger('showTplThumbnailLink');
$showThumbnailLink = (int) $showThumbnailLink[0];
$showCopyrightContent = $dispatcher->trigger('showTplCopyrightContent');
$showCopyrightContent = (int) $showCopyrightContent[0];
$replaceFooterContent = $dispatcher->trigger('replaceTplFooterContent');
$replaceFooterContent = (int) $replaceFooterContent[0];
$replacedFooterContent = $dispatcher->trigger('getTplFooterContent');
$replacedFooterContent = (string) $replacedFooterContent[0];
$replaceGettingStartedContent = $dispatcher->trigger('replaceTplGettingStartedContent');
$replaceGettingStartedContent = (int) $replaceGettingStartedContent[0];
$replacedGettingStartedContent = $dispatcher->trigger('getTplGettingStartedContent');
$replacedGettingStartedContent = (string) $replacedGettingStartedContent[0];
}
}
if (!$showThumbnailLink)
{
$templateLink = '#';
}
?>
<div class="jsn-master"><div id="jsn-template-config" class="jsn-bootstrap <?php echo $wrapperClass ?> <?php echo $editionClass ?>">
<form action="" method="POST" name="adminForm" id="style-form">
<input type="hidden" name="task" />
<input type="hidden" id="jsn-tpl-style-id" value="<?php echo JFactory::getApplication()->input->getInt('id', 0); ?>" />
<input type="hidden" id="jsn-tpl-edition" value="<?php echo strtolower(trim($edition)); ?>" />
<input type="hidden" id="jsn-tpl-name" value="<?php echo strtolower(trim($this->data->template)); ?>" />
<input type="hidden" id="jsn-tpl-token" value="<?php echo JSession::getFormToken(); ?>" />
<input type="hidden" name="customized" value="<?php echo @count($this->data->params) ? 'yes' : 'no'; ?>" />
<?php echo JHtml::_('form.token'); ?>
<div id="jsn-template-toolbar">
<label for="jform_title pull-left"><?php echo JText::_('JSN_TPLFW_FIELD_TITLE_LABEL') ?></label>
<?php echo $this->templateForm->getInput('title') ?>
<label for="jform_template pull-left"><?php echo JText::_('COM_TEMPLATES_FIELD_TEMPLATE_LABEL') ?></label>
<?php echo $this->templateForm->getInput('template') ?>
<label for="jform_home pull-left"><?php echo JText::_('COM_TEMPLATES_FIELD_HOME_LABEL') ?></label>
<?php echo $this->templateForm->getInput('home') ?>
<?php echo $this->templateForm->getInput('client_id') ?>
<div class="clearfix"></div>
</div>
<div id="jsn-template-config-tabs" class="jsn-hide form-horizontal">
<ul id="jsn-main-nav">
<li>
<a href="#getting-started">
<i class="icon-home icon-black"></i>
<?php echo JText::_('JSN_TPLFW_GETTING_STARTED') ?>
</a>
</li>
<?php foreach ($fieldSets as $fieldSet): ?>
<?php
$valid = false;
if (isset($fieldSet['joomlaVersion']))
{
if (version_compare($jversion->getShortVersion(), (string) $fieldSet['joomlaVersion'], ">="))
{
$valid = true;
}
}
else
{
$valid = true;
}
?>
<?php if ($valid) : ?>
<?php
if ((string) $fieldSet['name'] == 'jsn-megamenu' && $megamenu != 'yes')
{
continue;
}
?>
<?php $class = isset($fieldSet['pro']) && $fieldSet['pro'] == 'true' ? 'jsn-pro-tab' : '' ?>
<li class="<?php echo $class ?>">
<a href="#<?php echo $fieldSet['name'] ?>">
<?php if (isset($fieldSet['icon'])): ?>
<i class="<?php echo $fieldSet['icon'] ?>"></i>
<?php endif ?>
<?php echo JText::_($fieldSet['label']) ?>
<?php if (isset($fieldSet['pro']) && $fieldSet['pro'] == 'true'): ?>
<span class="label label-important label-pro">PRO</span>
<?php endif ?>
</a>
</li>
<?php endif ?>
<?php endforeach ?>
<li><a href="#menu-assignment"><i class="icon-checkbox"></i> <?php echo JText::_('JSN_TPLFW_MENU_ASSIGNMENT') ?></a></li>
</ul>
<div id="jsn-template-maintenance" class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<?php echo JText::_('JSN_TPLFW_MAINTENANCE'); ?>
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a id="jsn-template-maintenance-backup-params" href="<?php echo JRoute::_('index.php?widget=maintenance&action=backup&template=' . $this->data->template) . '&styleId=' . $this->data->id; ?>"><?php echo JText::_('JSN_TPLFW_MAINTENANCE_BACKUP'); ?></a></li>
<li><a id="jsn-template-maintenance-restore-params" href="<?php echo JRoute::_('index.php?widget=maintenance&action=restore&template=' . $this->data->template) . '&styleId=' . $this->data->id; ?>"><?php echo JText::_('JSN_TPLFW_MAINTENANCE_RESTORE'); ?></a></li>
</ul>
</div>
<div class="row-fluid" id="getting-started">
<?php include JSN_PATH_TPLFRAMEWORK_LIBRARIES . '/template/tmpl/default_home.php' ?>
</div>
<?php foreach ($fieldSets as $xmlFieldSet): ?>
<?php
$valid = false;
if (isset($xmlFieldSet['joomlaVersion']))
{
if (version_compare($jversion->getShortVersion(), (string) $xmlFieldSet['joomlaVersion'], ">="))
{
$valid = true;
}
}
else
{
$valid = true;
}
?>
<?php if ($valid) : ?>
<?php
if ((string) $xmlFieldSet['name'] == 'jsn-megamenu' && $megamenu != 'yes')
{
continue;
}
?>
<div id="<?php echo $xmlFieldSet['name'] ?>">
<?php if (isset($xmlFieldSet['pro']) && $xmlFieldSet['pro'] == 'true' && $this->templateEdition->getEdition() == 'FREE'): ?>
<div class="jsn-section-pro alert alert-block">
<p class="pull-left"><?php echo JText::_('JSN_TPLFW_FEATURES_AVAILABLE_IN_PRO') ?></p>
<?php if ($showUpgradeButton) {?>
<a href="javascript:void(0)" class="jsn-upgrade-link btn pull-right"><?php echo JText::_('JSN_TPLFW_UPGRADE_NOW') ?></a>
<?php } ?>
<div class="clearfix"></div>
</div>
<?php endif ?>
<?php if (isset($xmlFieldSet['twoColumns']) && $xmlFieldSet['twoColumns'] == 'true'): ?>
<?php include JSN_PATH_TPLFRAMEWORK_LIBRARIES . '/template/tmpl/default_layout.php' ?>
<?php else: ?>
<?php foreach ($xmlFieldSet->children() as $field): ?>
<?php $nodeName = strtolower($field->getName()) ?>
<?php if ($nodeName == 'field'): ?>
<?php $input = $this->adminForm->getField($field['name'], 'jsn') ?>
<?php if (trim($field['label']) != '') : ?>
<div class="control-group">
<div class="control-label">
<label for="<?php echo $input->id ?>" rel="tipsy" title="<?php echo JText::_($field['label'] . '_DESC') ?>">
<?php echo JText::_($field['label']) ?>
</label>
</div>
<div class="controls">
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
</div>
<?php else : ?>
<div>
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
<?php endif; ?>
<?php elseif ($nodeName == 'fieldset'): ?>
<fieldset class="<?php echo $field['name'] ?>">
<legend><?php echo JText::_($field['label']) ?></legend>
<?php foreach ($field->children() as $innerField): ?>
<?php $input = $this->adminForm->getField($innerField['name'], 'jsn') ?>
<?php if (trim($innerField['label']) != '') : ?>
<div class="control-group">
<div class="control-label">
<label for="<?php echo $input->id ?>" rel="tipsy" title="<?php echo JText::_($innerField['label'] . '_DESC') ?>">
<?php echo JText::_($innerField['label']) ?>
</label>
</div>
<div class="controls">
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
</div>
<?php else : ?>
<div>
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
<?php endif; ?>
<?php endforeach ?>
</fieldset>
<?php endif ?>
<?php endforeach ?>
<?php endif ?>
</div>
<?php endif ?>
<?php endforeach ?>
<div id="menu-assignment">
<?php include JSN_PATH_TPLFRAMEWORK_LIBRARIES . '/template/tmpl/default_assignment.php' ?>
</div>
</div>
</form>
<?php if ($promotion) : ?>
<div id="see-other-products">
<h2 class="jsn-section-header">
<?php echo JText::_('JSN_TPLFW_SEE_OTHER_PRODUCTS') ?>
<ul class="jsn-list-horizontal pull-right">
<li>
<a
class="jsn-icon24 jsn-icon-social jsn-icon-facebook"
href="http://www.facebook.com/joomlashine"
title="<?php echo JText::_('JSN_TPLFW_CONNECT_WITH_US_ON_FACEBOOK') ?>"
target="_blank">
</a>
</li>
<li>
<a
class="jsn-icon24 jsn-icon-social jsn-icon-twitter"
href="http://www.twitter.com/joomlashine"
title="<?php echo JText::_('JSN_TPLFW_FOLLOW_US_ON_TWITTER') ?>"
target="_blank">
</a>
</li>
<li>
<a
class="jsn-icon24 jsn-icon-social jsn-icon-youtube"
href="http://www.youtube.com/joomlashine"
title="<?php echo JText::_('JSN_TPLFW_WATCH_US_ON_YOUTUBE') ?>"
target="_blank">
</a>
</li>
</ul>
</h2>
<div class="clearbreak"></div>
<div class="bxslider">
<?php foreach ($jsn_templates as $item) :
$download = 'javascript:void(0)';
$title = 'Joomla Templates by JoomlaShine.com';
if (preg_match('#/jsn-([a-z0-9]+)\.#i', $item->image, $m))
{
$download = 'http://www.joomlashine.com/joomla-templates/jsn-' . $m[1] . '-download.html';
$title = 'JSN ' . ucfirst($m[1]);
} ?>
<a <?php echo 'href="http://demo.joomlashine.com/products-intro/' . $item->image . '" title="' . $title . '" data-demo="' . $item->link . '" data-download="' . $download . '" rel="cross-promo"'; ?>>
<img src="http://demo.joomlashine.com/products-intro/<?php echo $item->thumbnail; ?>" />
</a>
<?php endforeach; ?>
</div>
<input type="hidden" name="visited" value="" />
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var promotion = $('.bxslider'); slicesPerView = parseInt(promotion.innerWidth() / 250);
promotion.bxSlider({
hideControlOnEnd: true,
adaptiveHeight: true,
pager: false,
slideWidth: 250,
slideMargin: 10,
minSlides: slicesPerView,
maxSlides: slicesPerView,
});
$('.bxslider > a').colorbox({
rel: 'cross-promo',
onComplete: function(event) {
// Set title
$('#colorbox #cboxCurrent').html($(event.el).attr('title'));
// Set buttons
$('#colorbox #cboxTitle').html(
'<div class="jsn-master"><div class="jsn-bootstrap">'
+
'<a href="' + $(event.el).attr('data-demo') + '" class="btn btn-primary" target="_blank"><?php echo JText::_('JSN_TPLFW_DEMO'); ?></a>'
+
'<a href="' + $(event.el).attr('data-download') + '" class="btn btn-success" target="_blank"><?php echo JText::_('JSN_TPLFW_DOWNLOAD'); ?></a>'
+
'</div></div>'
);
},
});
});
})(jQuery);
</script>
</div>
<?php endif; ?>
<div class="modal hide" id="jsn_pro_edition_only_modal">
<div class="modal-body">
<p><?php echo JText::_('JSN_TPLFW_PRO_EDITION_ONLY'); ?></p>
</div>
<div class="modal-footer">
<a class="btn btn-primary jsn-upgrade-link" href="javascript:void(0)" onclick="jQuery(this).parent().parent().addClass('hide');"><?php echo JText::_('JSN_TPLFW_UPGRADE_NOW'); ?></a>
<a class="btn" href="javascript:void(0)" onclick="jQuery(this).parent().parent().addClass('hide');"><?php echo JText::_('JSN_TPLFW_CLOSE'); ?></a>
</div>
</div>
<div class="jsn-form-validation-failed jsn-box-shadow-medium alert alert-error hide">
<span></span>
<a href="javascript:void(0);" title="<?php echo JText::_('JSN_TPLFW_CLOSE'); ?>" class="close" onclick="jQuery(this).parent().addClass('hide');">×</a>
</div>
</div></div>
<div class="jsn-master">
<div class="jsn-page-footer jsn-bootstrap" id="jsn-footer">
<?php if ($replaceFooterContent) { ?>
<?php echo $replacedFooterContent; ?>
<?php } else { ?>
<div class="pull-left">
<ul class="jsn-footer-menu">
<li class="first">
<a target="_blank" href="http://www.joomlashine.com/joomla-templates/<?php echo $templateName ?>-docs.zip"><?php echo JText::_('JSN_TPLFW_DOCUMENTATION'); ?></a>
</li>
<li>
<a target="_blank" href="http://www.joomlashine.com/contact-us/get-support.html"><?php echo JText::_('JSN_TPLFW_SUPPORT'); ?></a>
</li>
<li class="jsn-iconbar">
<strong>Keep in touch:</strong>
<a href="http://www.facebook.com/joomlashine" target="_blank" title="Find us on Facebook"><i class="jsn-icon16 jsn-icon-social jsn-icon-facebook"></i></a><a href="http://www.twitter.com/joomlashine" target="_blank" title="Follow us on Twitter"><i "="" class="jsn-icon16 jsn-icon-social jsn-icon-twitter"></i></a><a href="http://www.youtube.com/joomlashine" target="_blank" title="Watch us on YouTube"><i "="" class="jsn-icon16 jsn-icon-social jsn-icon-youtube"></i></a>
</li>
</ul>
<ul class="jsn-footer-menu">
<li class="first">
<a target="_blank" href="<?php echo $templateLink ?>"><?php echo JText::_($template->name) ?> <?php echo $edition ?> v<?php echo $version ?></a> by <a target="_blank" href="http://www.joomlashine.com">JoomlaShine.com</a>
<?php if ($nextEdition) : ?>
<a class="label label-important jsn-upgrade-link" href="javascript:void()"><strong class="jsn-text-attention"><?php echo JText::_($nextEdition == 'STANDARD' ? 'JSN_TPLFW_UPGRADE_TO_PRO' : 'JSN_TPLFW_UPGRADE_TO_PRO_UNLIMITED'); ?></strong></a>
<?php endif; ?>
</li>
<li class="jsn-outdated-version" id="jsn-global-check-version-result" style="display:none">
<span class="jsn-global-outdated-version"><?php echo JText::_('JSN_TPLFW_UPDATE_AVAILABLE'); ?></span>
<a class="label label-important jsn-update-link" data-target="template" href="javascript:void(0)"><?php echo JText::_('JSN_TPLFW_UPDATE_NOW'); ?></a>
</li>
</ul>
</div>
<div class="pull-right">
<ul class="jsn-footer-menu">
<li class="jsn-iconbar first">
<a href="http://www.joomlashine.com/joomla-extensions/jsn-poweradmin.html" target="_blank" title="JSN PowerAdmin - Manage Joomla websites with ease and joy">
<i class="jsn-icon32 jsn-icon-products jsn-icon-poweradmin"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-imageshow.html" target="_blank" title="JSN ImageShow - One Joomla gallery extension for all image presentation needs">
<i class="jsn-icon32 jsn-icon-products jsn-icon-imageshow"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-uniform.html" target="_blank" title="JSN UniForm - The most easy, yet sophisticated Joomla form builder extension">
<i class="jsn-icon32 jsn-icon-products jsn-icon-uniform"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-mobilize.html" target="_blank" title="JSN Mobilize - Painless mobile site creator">
<i class="jsn-icon32 jsn-icon-products jsn-icon-mobilize"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-pagebuilder.html" target="_blank" title="JSN PageBuilder - Easiest way to build Joomla pages">
<i class="jsn-icon32 jsn-icon-products jsn-icon-pagebuilder"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-easyslider.html" target="_blank" title="JSN EasySlider - Multipurpose content slider with super user-friendly interface">
<i class="jsn-icon32 jsn-icon-products jsn-icon-easyslider"></i>
</a>
</li>
</ul>
</div>
<?php } ?>
<div class="clearbreak"></div>
</div>
</div>
<!-- Hidden form for saving/restoring template parameters -->
<form id="jsn-template-maintenance-restore-params-form" method="post" enctype="multipart/form-data" target="jsn-silent-save" class="hide">
<input type="file" name="backup-upload" />
</form>
<iframe id="jsn-silent-save" name="jsn-silent-save" class="hide" src="about:blank"></iframe>
<script type="text/javascript">
(function($) {
$(document).ready(function() {
$(".jsn-modal-overlay,.jsn-modal-indicator").remove();
$("body").append($("<div/>", {
"class":"jsn-modal-overlay",
"style":"z-index: 1000; display: inline;"
})).append($("<div/>", {
"class":"jsn-modal-indicator",
"style":"display:block"
})).addClass("jsn-loading-page");
$(".jsn-modal-overlay,.jsn-modal-indicator").delay(1200).queue(function () {
$(this).remove();
$("#jsn-template-config-tabs").removeClass("jsn-hide");
});
});
// Setup tabs
$('#jsn-template-config-tabs').tabs();
// Setup form validation
new $.JSNFormValidation({
lang: {
JSN_TPLFW_INVALID_VALUE_TYPE: '<?php echo JText::_('JSN_TPLFW_INVALID_VALUE_TYPE'); ?>',
JSN_TPLFW_ERROR_FORM_VALIDATION_FAILED: '<?php echo JText::_('JSN_TPLFW_ERROR_FORM_VALIDATION_FAILED'); ?>',
JSN_TPLFW_SYSTEM_CUSTOM_ASSETS_INVALID: '<?php echo JText::_('JSN_TPLFW_SYSTEM_CUSTOM_ASSETS_INVALID'); ?>'
}
});
})(jQuery);
</script>
| k-yar/jadis | plugins/system/jsntplframework/libraries/joomlashine/template/tmpl/default.php | PHP | gpl-2.0 | 20,799 |
#ifndef _SYS_PARAM_H
#define _SYS_PARAM_H
#include <limits.h>
#define MAXPATHLEN PATH_MAX
#define MAXHOSTNAMELEN 64
#define NGROUPS 32
#define NOGROUP (-1)
#define NOFILE OPEN_MAX
#undef MIN
#undef MAX
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))
#ifdef __alpha__
#define HZ 1024
#else
#define HZ 100
#endif
#ifndef howmany
# define howmany(x, y) (((x)+((y)-1))/(y))
#endif
#define roundup(x, y) ((((x)+((y)-1))/(y))*(y))
#define powerof2(x) ((((x)-1)&(x))==0)
#endif
| ensc/dietlibc | include/sys/param.h | C | gpl-2.0 | 513 |
/*
8139too.c: A RealTek RTL-8139 Fast Ethernet driver for Linux.
Maintained by Jeff Garzik <jgarzik@pobox.com>
Copyright 2000-2002 Jeff Garzik
Much code comes from Donald Becker's rtl8139.c driver,
versions 1.13 and older. This driver was originally based
on rtl8139.c version 1.07. Header of rtl8139.c version 1.13:
-----<snip>-----
Written 1997-2001 by Donald Becker.
This software may be used and distributed according to the
terms of the GNU General Public License (GPL), incorporated
herein by reference. Drivers based on or derived from this
code fall under the GPL and must retain the authorship,
copyright and license notice. This file is not a complete
program and may only be used when the entire operating
system is licensed under the GPL.
This driver is for boards based on the RTL8129 and RTL8139
PCI ethernet chips.
The author may be reached as becker@scyld.com, or C/O Scyld
Computing Corporation 410 Severn Ave., Suite 210 Annapolis
MD 21403
Support and updates available at
http://www.scyld.com/network/rtl8139.html
Twister-tuning table provided by Kinston
<shangh@realtek.com.tw>.
-----<snip>-----
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
Contributors:
Donald Becker - he wrote the original driver, kudos to him!
(but please don't e-mail him for support, this isn't his driver)
Tigran Aivazian - bug fixes, skbuff free cleanup
Martin Mares - suggestions for PCI cleanup
David S. Miller - PCI DMA and softnet updates
Ernst Gill - fixes ported from BSD driver
Daniel Kobras - identified specific locations of
posted MMIO write bugginess
Gerard Sharp - bug fix, testing and feedback
David Ford - Rx ring wrap fix
Dan DeMaggio - swapped RTL8139 cards with me, and allowed me
to find and fix a crucial bug on older chipsets.
Donald Becker/Chris Butterworth/Marcus Westergren -
Noticed various Rx packet size-related buglets.
Santiago Garcia Mantinan - testing and feedback
Jens David - 2.2.x kernel backports
Martin Dennett - incredibly helpful insight on undocumented
features of the 8139 chips
Jean-Jacques Michel - bug fix
Tobias Ringström - Rx interrupt status checking suggestion
Andrew Morton - Clear blocked signals, avoid
buffer overrun setting current->comm.
Kalle Olavi Niemitalo - Wake-on-LAN ioctls
Robert Kuebel - Save kernel thread from dying on any signal.
Submitting bug reports:
"rtl8139-diag -mmmaaavvveefN" output
enable RTL8139_DEBUG below, and look at 'dmesg' or kernel log
*/
#define DRV_NAME "8139too"
#define DRV_VERSION "0.9.28"
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/compiler.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/rtnetlink.h>
#include <linux/delay.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/completion.h>
#include <linux/crc32.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/irq.h>
#define RTL8139_DRIVER_NAME DRV_NAME " Fast Ethernet driver " DRV_VERSION
#define PFX DRV_NAME ": "
/* Default Message level */
#define RTL8139_DEF_MSG_ENABLE (NETIF_MSG_DRV | \
NETIF_MSG_PROBE | \
NETIF_MSG_LINK)
/* enable PIO instead of MMIO, if CONFIG_8139TOO_PIO is selected */
#ifdef CONFIG_8139TOO_PIO
#define USE_IO_OPS 1
#endif
/* define to 1, 2 or 3 to enable copious debugging info */
#define RTL8139_DEBUG 0
/* define to 1 to disable lightweight runtime debugging checks */
#undef RTL8139_NDEBUG
#if RTL8139_DEBUG
/* note: prints function name for you */
# define DPRINTK(fmt, args...) printk(KERN_DEBUG "%s: " fmt, __FUNCTION__ , ## args)
#else
# define DPRINTK(fmt, args...)
#endif
#ifdef RTL8139_NDEBUG
# define assert(expr) do {} while (0)
#else
# define assert(expr) \
if(unlikely(!(expr))) { \
printk(KERN_ERR "Assertion failed! %s,%s,%s,line=%d\n", \
#expr,__FILE__,__FUNCTION__,__LINE__); \
}
#endif
/* A few user-configurable values. */
/* media options */
#define MAX_UNITS 8
static int media[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
static int full_duplex[MAX_UNITS] = {-1, -1, -1, -1, -1, -1, -1, -1};
/* Maximum number of multicast addresses to filter (vs. Rx-all-multicast).
The RTL chips use a 64 element hash table based on the Ethernet CRC. */
static int multicast_filter_limit = 32;
/* bitmapped message enable number */
static int debug = -1;
/*
* Receive ring size
* Warning: 64K ring has hardware issues and may lock up.
*/
#if defined(CONFIG_SH_DREAMCAST)
#define RX_BUF_IDX 1 /* 16K ring */
#else
#define RX_BUF_IDX 2 /* 32K ring */
#endif
#define RX_BUF_LEN (8192 << RX_BUF_IDX)
#define RX_BUF_PAD 16
#define RX_BUF_WRAP_PAD 2048 /* spare padding to handle lack of packet wrap */
#if RX_BUF_LEN == 65536
#define RX_BUF_TOT_LEN RX_BUF_LEN
#else
#define RX_BUF_TOT_LEN (RX_BUF_LEN + RX_BUF_PAD + RX_BUF_WRAP_PAD)
#endif
/* Number of Tx descriptor registers. */
#define NUM_TX_DESC 4
/* max supported ethernet frame size -- must be at least (dev->mtu+14+4).*/
#define MAX_ETH_FRAME_SIZE 1536
/* Size of the Tx bounce buffers -- must be at least (dev->mtu+14+4). */
#define TX_BUF_SIZE MAX_ETH_FRAME_SIZE
#define TX_BUF_TOT_LEN (TX_BUF_SIZE * NUM_TX_DESC)
/* PCI Tuning Parameters
Threshold is bytes transferred to chip before transmission starts. */
#define TX_FIFO_THRESH 256 /* In bytes, rounded down to 32 byte units. */
/* The following settings are log_2(bytes)-4: 0 == 16 bytes .. 6==1024, 7==end of packet. */
#define RX_FIFO_THRESH 7 /* Rx buffer level before first PCI xfer. */
#define RX_DMA_BURST 7 /* Maximum PCI burst, '6' is 1024 */
#define TX_DMA_BURST 6 /* Maximum PCI burst, '6' is 1024 */
#define TX_RETRY 8 /* 0-15. retries = 16 + (TX_RETRY * 16) */
/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (6*HZ)
enum {
HAS_MII_XCVR = 0x010000,
HAS_CHIP_XCVR = 0x020000,
HAS_LNK_CHNG = 0x040000,
};
#define RTL_NUM_STATS 4 /* number of ETHTOOL_GSTATS u64's */
#define RTL_REGS_VER 1 /* version of reg. data in ETHTOOL_GREGS */
#define RTL_MIN_IO_SIZE 0x80
#define RTL8139B_IO_SIZE 256
#define RTL8129_CAPS HAS_MII_XCVR
#define RTL8139_CAPS HAS_CHIP_XCVR|HAS_LNK_CHNG
typedef enum {
RTL8139 = 0,
RTL8129,
} board_t;
/* indexed by board_t, above */
static const struct {
const char *name;
u32 hw_flags;
} board_info[] __devinitdata = {
{ "RealTek RTL8139", RTL8139_CAPS },
{ "RealTek RTL8129", RTL8129_CAPS },
};
static struct pci_device_id rtl8139_pci_tbl[] = {
{0x10ec, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x10ec, 0x8138, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1113, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1500, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x4033, 0x1360, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1186, 0x1300, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1186, 0x1340, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x13d1, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1259, 0xa117, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1259, 0xa11e, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x14ea, 0xab06, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x14ea, 0xab07, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x11db, 0x1234, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1432, 0x9130, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x02ac, 0x1012, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x018a, 0x0106, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x126c, 0x1211, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x1743, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
{0x021b, 0x8139, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
#ifdef CONFIG_SH_SECUREEDGE5410
/* Bogus 8139 silicon reports 8129 without external PROM :-( */
{0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8139 },
#endif
#ifdef CONFIG_8139TOO_8129
{0x10ec, 0x8129, PCI_ANY_ID, PCI_ANY_ID, 0, 0, RTL8129 },
#endif
/* some crazy cards report invalid vendor ids like
* 0x0001 here. The other ids are valid and constant,
* so we simply don't match on the main vendor id.
*/
{PCI_ANY_ID, 0x8139, 0x10ec, 0x8139, 0, 0, RTL8139 },
{PCI_ANY_ID, 0x8139, 0x1186, 0x1300, 0, 0, RTL8139 },
{PCI_ANY_ID, 0x8139, 0x13d1, 0xab06, 0, 0, RTL8139 },
{0,}
};
MODULE_DEVICE_TABLE (pci, rtl8139_pci_tbl);
static struct {
const char str[ETH_GSTRING_LEN];
} ethtool_stats_keys[] = {
{ "early_rx" },
{ "tx_buf_mapped" },
{ "tx_timeouts" },
{ "rx_lost_in_ring" },
};
/* The rest of these values should never change. */
/* Symbolic offsets to registers. */
enum RTL8139_registers {
MAC0 = 0, /* Ethernet hardware address. */
MAR0 = 8, /* Multicast filter. */
TxStatus0 = 0x10, /* Transmit status (Four 32bit registers). */
TxAddr0 = 0x20, /* Tx descriptors (also four 32bit). */
RxBuf = 0x30,
ChipCmd = 0x37,
RxBufPtr = 0x38,
RxBufAddr = 0x3A,
IntrMask = 0x3C,
IntrStatus = 0x3E,
TxConfig = 0x40,
RxConfig = 0x44,
Timer = 0x48, /* A general-purpose counter. */
RxMissed = 0x4C, /* 24 bits valid, write clears. */
Cfg9346 = 0x50,
Config0 = 0x51,
Config1 = 0x52,
FlashReg = 0x54,
MediaStatus = 0x58,
Config3 = 0x59,
Config4 = 0x5A, /* absent on RTL-8139A */
HltClk = 0x5B,
MultiIntr = 0x5C,
TxSummary = 0x60,
BasicModeCtrl = 0x62,
BasicModeStatus = 0x64,
NWayAdvert = 0x66,
NWayLPAR = 0x68,
NWayExpansion = 0x6A,
/* Undocumented registers, but required for proper operation. */
FIFOTMS = 0x70, /* FIFO Control and test. */
CSCR = 0x74, /* Chip Status and Configuration Register. */
PARA78 = 0x78,
PARA7c = 0x7c, /* Magic transceiver parameter register. */
Config5 = 0xD8, /* absent on RTL-8139A */
};
enum ClearBitMasks {
MultiIntrClear = 0xF000,
ChipCmdClear = 0xE2,
Config1Clear = (1<<7)|(1<<6)|(1<<3)|(1<<2)|(1<<1),
};
enum ChipCmdBits {
CmdReset = 0x10,
CmdRxEnb = 0x08,
CmdTxEnb = 0x04,
RxBufEmpty = 0x01,
};
/* Interrupt register bits, using my own meaningful names. */
enum IntrStatusBits {
PCIErr = 0x8000,
PCSTimeout = 0x4000,
RxFIFOOver = 0x40,
RxUnderrun = 0x20,
RxOverflow = 0x10,
TxErr = 0x08,
TxOK = 0x04,
RxErr = 0x02,
RxOK = 0x01,
RxAckBits = RxFIFOOver | RxOverflow | RxOK,
};
enum TxStatusBits {
TxHostOwns = 0x2000,
TxUnderrun = 0x4000,
TxStatOK = 0x8000,
TxOutOfWindow = 0x20000000,
TxAborted = 0x40000000,
TxCarrierLost = 0x80000000,
};
enum RxStatusBits {
RxMulticast = 0x8000,
RxPhysical = 0x4000,
RxBroadcast = 0x2000,
RxBadSymbol = 0x0020,
RxRunt = 0x0010,
RxTooLong = 0x0008,
RxCRCErr = 0x0004,
RxBadAlign = 0x0002,
RxStatusOK = 0x0001,
};
/* Bits in RxConfig. */
enum rx_mode_bits {
AcceptErr = 0x20,
AcceptRunt = 0x10,
AcceptBroadcast = 0x08,
AcceptMulticast = 0x04,
AcceptMyPhys = 0x02,
AcceptAllPhys = 0x01,
};
/* Bits in TxConfig. */
enum tx_config_bits {
/* Interframe Gap Time. Only TxIFG96 doesn't violate IEEE 802.3 */
TxIFGShift = 24,
TxIFG84 = (0 << TxIFGShift), /* 8.4us / 840ns (10 / 100Mbps) */
TxIFG88 = (1 << TxIFGShift), /* 8.8us / 880ns (10 / 100Mbps) */
TxIFG92 = (2 << TxIFGShift), /* 9.2us / 920ns (10 / 100Mbps) */
TxIFG96 = (3 << TxIFGShift), /* 9.6us / 960ns (10 / 100Mbps) */
TxLoopBack = (1 << 18) | (1 << 17), /* enable loopback test mode */
TxCRC = (1 << 16), /* DISABLE appending CRC to end of Tx packets */
TxClearAbt = (1 << 0), /* Clear abort (WO) */
TxDMAShift = 8, /* DMA burst value (0-7) is shifted this many bits */
TxRetryShift = 4, /* TXRR value (0-15) is shifted this many bits */
TxVersionMask = 0x7C800000, /* mask out version bits 30-26, 23 */
};
/* Bits in Config1 */
enum Config1Bits {
Cfg1_PM_Enable = 0x01,
Cfg1_VPD_Enable = 0x02,
Cfg1_PIO = 0x04,
Cfg1_MMIO = 0x08,
LWAKE = 0x10, /* not on 8139, 8139A */
Cfg1_Driver_Load = 0x20,
Cfg1_LED0 = 0x40,
Cfg1_LED1 = 0x80,
SLEEP = (1 << 1), /* only on 8139, 8139A */
PWRDN = (1 << 0), /* only on 8139, 8139A */
};
/* Bits in Config3 */
enum Config3Bits {
Cfg3_FBtBEn = (1 << 0), /* 1 = Fast Back to Back */
Cfg3_FuncRegEn = (1 << 1), /* 1 = enable CardBus Function registers */
Cfg3_CLKRUN_En = (1 << 2), /* 1 = enable CLKRUN */
Cfg3_CardB_En = (1 << 3), /* 1 = enable CardBus registers */
Cfg3_LinkUp = (1 << 4), /* 1 = wake up on link up */
Cfg3_Magic = (1 << 5), /* 1 = wake up on Magic Packet (tm) */
Cfg3_PARM_En = (1 << 6), /* 0 = software can set twister parameters */
Cfg3_GNTSel = (1 << 7), /* 1 = delay 1 clock from PCI GNT signal */
};
/* Bits in Config4 */
enum Config4Bits {
LWPTN = (1 << 2), /* not on 8139, 8139A */
};
/* Bits in Config5 */
enum Config5Bits {
Cfg5_PME_STS = (1 << 0), /* 1 = PCI reset resets PME_Status */
Cfg5_LANWake = (1 << 1), /* 1 = enable LANWake signal */
Cfg5_LDPS = (1 << 2), /* 0 = save power when link is down */
Cfg5_FIFOAddrPtr = (1 << 3), /* Realtek internal SRAM testing */
Cfg5_UWF = (1 << 4), /* 1 = accept unicast wakeup frame */
Cfg5_MWF = (1 << 5), /* 1 = accept multicast wakeup frame */
Cfg5_BWF = (1 << 6), /* 1 = accept broadcast wakeup frame */
};
enum RxConfigBits {
/* rx fifo threshold */
RxCfgFIFOShift = 13,
RxCfgFIFONone = (7 << RxCfgFIFOShift),
/* Max DMA burst */
RxCfgDMAShift = 8,
RxCfgDMAUnlimited = (7 << RxCfgDMAShift),
/* rx ring buffer length */
RxCfgRcv8K = 0,
RxCfgRcv16K = (1 << 11),
RxCfgRcv32K = (1 << 12),
RxCfgRcv64K = (1 << 11) | (1 << 12),
/* Disable packet wrap at end of Rx buffer. (not possible with 64k) */
RxNoWrap = (1 << 7),
};
/* Twister tuning parameters from RealTek.
Completely undocumented, but required to tune bad links on some boards. */
enum CSCRBits {
CSCR_LinkOKBit = 0x0400,
CSCR_LinkChangeBit = 0x0800,
CSCR_LinkStatusBits = 0x0f000,
CSCR_LinkDownOffCmd = 0x003c0,
CSCR_LinkDownCmd = 0x0f3c0,
};
enum Cfg9346Bits {
Cfg9346_Lock = 0x00,
Cfg9346_Unlock = 0xC0,
};
typedef enum {
CH_8139 = 0,
CH_8139_K,
CH_8139A,
CH_8139A_G,
CH_8139B,
CH_8130,
CH_8139C,
CH_8100,
CH_8100B_8139D,
CH_8101,
} chip_t;
enum chip_flags {
HasHltClk = (1 << 0),
HasLWake = (1 << 1),
};
#define HW_REVID(b30, b29, b28, b27, b26, b23, b22) \
(b30<<30 | b29<<29 | b28<<28 | b27<<27 | b26<<26 | b23<<23 | b22<<22)
#define HW_REVID_MASK HW_REVID(1, 1, 1, 1, 1, 1, 1)
/* directly indexed by chip_t, above */
static const struct {
const char *name;
u32 version; /* from RTL8139C/RTL8139D docs */
u32 flags;
} rtl_chip_info[] = {
{ "RTL-8139",
HW_REVID(1, 0, 0, 0, 0, 0, 0),
HasHltClk,
},
{ "RTL-8139 rev K",
HW_REVID(1, 1, 0, 0, 0, 0, 0),
HasHltClk,
},
{ "RTL-8139A",
HW_REVID(1, 1, 1, 0, 0, 0, 0),
HasHltClk, /* XXX undocumented? */
},
{ "RTL-8139A rev G",
HW_REVID(1, 1, 1, 0, 0, 1, 0),
HasHltClk, /* XXX undocumented? */
},
{ "RTL-8139B",
HW_REVID(1, 1, 1, 1, 0, 0, 0),
HasLWake,
},
{ "RTL-8130",
HW_REVID(1, 1, 1, 1, 1, 0, 0),
HasLWake,
},
{ "RTL-8139C",
HW_REVID(1, 1, 1, 0, 1, 0, 0),
HasLWake,
},
{ "RTL-8100",
HW_REVID(1, 1, 1, 1, 0, 1, 0),
HasLWake,
},
{ "RTL-8100B/8139D",
HW_REVID(1, 1, 1, 0, 1, 0, 1),
HasHltClk /* XXX undocumented? */
| HasLWake,
},
{ "RTL-8101",
HW_REVID(1, 1, 1, 0, 1, 1, 1),
HasLWake,
},
};
struct rtl_extra_stats {
unsigned long early_rx;
unsigned long tx_buf_mapped;
unsigned long tx_timeouts;
unsigned long rx_lost_in_ring;
};
struct rtl8139_private {
void __iomem *mmio_addr;
int drv_flags;
struct pci_dev *pci_dev;
u32 msg_enable;
struct net_device_stats stats;
unsigned char *rx_ring;
unsigned int cur_rx; /* Index into the Rx buffer of next Rx pkt. */
unsigned int tx_flag;
unsigned long cur_tx;
unsigned long dirty_tx;
unsigned char *tx_buf[NUM_TX_DESC]; /* Tx bounce buffers */
unsigned char *tx_bufs; /* Tx bounce buffer region. */
dma_addr_t rx_ring_dma;
dma_addr_t tx_bufs_dma;
signed char phys[4]; /* MII device addresses. */
char twistie, twist_row, twist_col; /* Twister tune state. */
unsigned int watchdog_fired : 1;
unsigned int default_port : 4; /* Last dev->if_port value. */
unsigned int have_thread : 1;
spinlock_t lock;
spinlock_t rx_lock;
chip_t chipset;
u32 rx_config;
struct rtl_extra_stats xstats;
struct work_struct thread;
struct mii_if_info mii;
unsigned int regs_len;
unsigned long fifo_copy_timeout;
};
MODULE_AUTHOR ("Jeff Garzik <jgarzik@pobox.com>");
MODULE_DESCRIPTION ("RealTek RTL-8139 Fast Ethernet driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
module_param(multicast_filter_limit, int, 0);
module_param_array(media, int, NULL, 0);
module_param_array(full_duplex, int, NULL, 0);
module_param(debug, int, 0);
MODULE_PARM_DESC (debug, "8139too bitmapped message enable number");
MODULE_PARM_DESC (multicast_filter_limit, "8139too maximum number of filtered multicast addresses");
MODULE_PARM_DESC (media, "8139too: Bits 4+9: force full duplex, bit 5: 100Mbps");
MODULE_PARM_DESC (full_duplex, "8139too: Force full duplex for board(s) (1)");
static int read_eeprom (void __iomem *ioaddr, int location, int addr_len);
static int rtl8139_open (struct net_device *dev);
static int mdio_read (struct net_device *dev, int phy_id, int location);
static void mdio_write (struct net_device *dev, int phy_id, int location,
int val);
static void rtl8139_start_thread(struct rtl8139_private *tp);
static void rtl8139_tx_timeout (struct net_device *dev);
static void rtl8139_init_ring (struct net_device *dev);
static int rtl8139_start_xmit (struct sk_buff *skb,
struct net_device *dev);
static int rtl8139_poll(struct net_device *dev, int *budget);
#ifdef CONFIG_NET_POLL_CONTROLLER
static void rtl8139_poll_controller(struct net_device *dev);
#endif
static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance);
static int rtl8139_close (struct net_device *dev);
static int netdev_ioctl (struct net_device *dev, struct ifreq *rq, int cmd);
static struct net_device_stats *rtl8139_get_stats (struct net_device *dev);
static void rtl8139_set_rx_mode (struct net_device *dev);
static void __set_rx_mode (struct net_device *dev);
static void rtl8139_hw_start (struct net_device *dev);
static void rtl8139_thread (void *_data);
static void rtl8139_tx_timeout_task(void *_data);
static const struct ethtool_ops rtl8139_ethtool_ops;
/* write MMIO register, with flush */
/* Flush avoids rtl8139 bug w/ posted MMIO writes */
#define RTL_W8_F(reg, val8) do { iowrite8 ((val8), ioaddr + (reg)); ioread8 (ioaddr + (reg)); } while (0)
#define RTL_W16_F(reg, val16) do { iowrite16 ((val16), ioaddr + (reg)); ioread16 (ioaddr + (reg)); } while (0)
#define RTL_W32_F(reg, val32) do { iowrite32 ((val32), ioaddr + (reg)); ioread32 (ioaddr + (reg)); } while (0)
#define MMIO_FLUSH_AUDIT_COMPLETE 1
#if MMIO_FLUSH_AUDIT_COMPLETE
/* write MMIO register */
#define RTL_W8(reg, val8) iowrite8 ((val8), ioaddr + (reg))
#define RTL_W16(reg, val16) iowrite16 ((val16), ioaddr + (reg))
#define RTL_W32(reg, val32) iowrite32 ((val32), ioaddr + (reg))
#else
/* write MMIO register, then flush */
#define RTL_W8 RTL_W8_F
#define RTL_W16 RTL_W16_F
#define RTL_W32 RTL_W32_F
#endif /* MMIO_FLUSH_AUDIT_COMPLETE */
/* read MMIO register */
#define RTL_R8(reg) ioread8 (ioaddr + (reg))
#define RTL_R16(reg) ioread16 (ioaddr + (reg))
#define RTL_R32(reg) ((unsigned long) ioread32 (ioaddr + (reg)))
static const u16 rtl8139_intr_mask =
PCIErr | PCSTimeout | RxUnderrun | RxOverflow | RxFIFOOver |
TxErr | TxOK | RxErr | RxOK;
static const u16 rtl8139_norx_intr_mask =
PCIErr | PCSTimeout | RxUnderrun |
TxErr | TxOK | RxErr ;
#if RX_BUF_IDX == 0
static const unsigned int rtl8139_rx_config =
RxCfgRcv8K | RxNoWrap |
(RX_FIFO_THRESH << RxCfgFIFOShift) |
(RX_DMA_BURST << RxCfgDMAShift);
#elif RX_BUF_IDX == 1
static const unsigned int rtl8139_rx_config =
RxCfgRcv16K | RxNoWrap |
(RX_FIFO_THRESH << RxCfgFIFOShift) |
(RX_DMA_BURST << RxCfgDMAShift);
#elif RX_BUF_IDX == 2
static const unsigned int rtl8139_rx_config =
RxCfgRcv32K | RxNoWrap |
(RX_FIFO_THRESH << RxCfgFIFOShift) |
(RX_DMA_BURST << RxCfgDMAShift);
#elif RX_BUF_IDX == 3
static const unsigned int rtl8139_rx_config =
RxCfgRcv64K |
(RX_FIFO_THRESH << RxCfgFIFOShift) |
(RX_DMA_BURST << RxCfgDMAShift);
#else
#error "Invalid configuration for 8139_RXBUF_IDX"
#endif
static const unsigned int rtl8139_tx_config =
TxIFG96 | (TX_DMA_BURST << TxDMAShift) | (TX_RETRY << TxRetryShift);
static void __rtl8139_cleanup_dev (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
struct pci_dev *pdev;
assert (dev != NULL);
assert (tp->pci_dev != NULL);
pdev = tp->pci_dev;
#ifdef USE_IO_OPS
if (tp->mmio_addr)
ioport_unmap (tp->mmio_addr);
#else
if (tp->mmio_addr)
pci_iounmap (pdev, tp->mmio_addr);
#endif /* USE_IO_OPS */
/* it's ok to call this even if we have no regions to free */
pci_release_regions (pdev);
free_netdev(dev);
pci_set_drvdata (pdev, NULL);
}
static void rtl8139_chip_reset (void __iomem *ioaddr)
{
int i;
/* Soft reset the chip. */
RTL_W8 (ChipCmd, CmdReset);
/* Check that the chip has finished the reset. */
for (i = 1000; i > 0; i--) {
barrier();
if ((RTL_R8 (ChipCmd) & CmdReset) == 0)
break;
udelay (10);
}
}
static int __devinit rtl8139_init_board (struct pci_dev *pdev,
struct net_device **dev_out)
{
void __iomem *ioaddr;
struct net_device *dev;
struct rtl8139_private *tp;
u8 tmp8;
int rc, disable_dev_on_err = 0;
unsigned int i;
unsigned long pio_start, pio_end, pio_flags, pio_len;
unsigned long mmio_start, mmio_end, mmio_flags, mmio_len;
u32 version;
assert (pdev != NULL);
*dev_out = NULL;
/* dev and priv zeroed in alloc_etherdev */
dev = alloc_etherdev (sizeof (*tp));
if (dev == NULL) {
dev_err(&pdev->dev, "Unable to alloc new net device\n");
return -ENOMEM;
}
SET_MODULE_OWNER(dev);
SET_NETDEV_DEV(dev, &pdev->dev);
tp = netdev_priv(dev);
tp->pci_dev = pdev;
/* enable device (incl. PCI PM wakeup and hotplug setup) */
rc = pci_enable_device (pdev);
if (rc)
goto err_out;
pio_start = pci_resource_start (pdev, 0);
pio_end = pci_resource_end (pdev, 0);
pio_flags = pci_resource_flags (pdev, 0);
pio_len = pci_resource_len (pdev, 0);
mmio_start = pci_resource_start (pdev, 1);
mmio_end = pci_resource_end (pdev, 1);
mmio_flags = pci_resource_flags (pdev, 1);
mmio_len = pci_resource_len (pdev, 1);
/* set this immediately, we need to know before
* we talk to the chip directly */
DPRINTK("PIO region size == 0x%02X\n", pio_len);
DPRINTK("MMIO region size == 0x%02lX\n", mmio_len);
#ifdef USE_IO_OPS
/* make sure PCI base addr 0 is PIO */
if (!(pio_flags & IORESOURCE_IO)) {
dev_err(&pdev->dev, "region #0 not a PIO resource, aborting\n");
rc = -ENODEV;
goto err_out;
}
/* check for weird/broken PCI region reporting */
if (pio_len < RTL_MIN_IO_SIZE) {
dev_err(&pdev->dev, "Invalid PCI I/O region size(s), aborting\n");
rc = -ENODEV;
goto err_out;
}
#else
/* make sure PCI base addr 1 is MMIO */
if (!(mmio_flags & IORESOURCE_MEM)) {
dev_err(&pdev->dev, "region #1 not an MMIO resource, aborting\n");
rc = -ENODEV;
goto err_out;
}
if (mmio_len < RTL_MIN_IO_SIZE) {
dev_err(&pdev->dev, "Invalid PCI mem region size(s), aborting\n");
rc = -ENODEV;
goto err_out;
}
#endif
rc = pci_request_regions (pdev, DRV_NAME);
if (rc)
goto err_out;
disable_dev_on_err = 1;
/* enable PCI bus-mastering */
pci_set_master (pdev);
#ifdef USE_IO_OPS
ioaddr = ioport_map(pio_start, pio_len);
if (!ioaddr) {
dev_err(&pdev->dev, "cannot map PIO, aborting\n");
rc = -EIO;
goto err_out;
}
dev->base_addr = pio_start;
tp->mmio_addr = ioaddr;
tp->regs_len = pio_len;
#else
/* ioremap MMIO region */
ioaddr = pci_iomap(pdev, 1, 0);
if (ioaddr == NULL) {
dev_err(&pdev->dev, "cannot remap MMIO, aborting\n");
rc = -EIO;
goto err_out;
}
dev->base_addr = (long) ioaddr;
tp->mmio_addr = ioaddr;
tp->regs_len = mmio_len;
#endif /* USE_IO_OPS */
/* Bring old chips out of low-power mode. */
RTL_W8 (HltClk, 'R');
/* check for missing/broken hardware */
if (RTL_R32 (TxConfig) == 0xFFFFFFFF) {
dev_err(&pdev->dev, "Chip not responding, ignoring board\n");
rc = -EIO;
goto err_out;
}
/* identify chip attached to board */
version = RTL_R32 (TxConfig) & HW_REVID_MASK;
for (i = 0; i < ARRAY_SIZE (rtl_chip_info); i++)
if (version == rtl_chip_info[i].version) {
tp->chipset = i;
goto match;
}
/* if unknown chip, assume array element #0, original RTL-8139 in this case */
dev_printk (KERN_DEBUG, &pdev->dev,
"unknown chip version, assuming RTL-8139\n");
dev_printk (KERN_DEBUG, &pdev->dev,
"TxConfig = 0x%lx\n", RTL_R32 (TxConfig));
tp->chipset = 0;
match:
DPRINTK ("chipset id (%d) == index %d, '%s'\n",
version, i, rtl_chip_info[i].name);
if (tp->chipset >= CH_8139B) {
u8 new_tmp8 = tmp8 = RTL_R8 (Config1);
DPRINTK("PCI PM wakeup\n");
if ((rtl_chip_info[tp->chipset].flags & HasLWake) &&
(tmp8 & LWAKE))
new_tmp8 &= ~LWAKE;
new_tmp8 |= Cfg1_PM_Enable;
if (new_tmp8 != tmp8) {
RTL_W8 (Cfg9346, Cfg9346_Unlock);
RTL_W8 (Config1, tmp8);
RTL_W8 (Cfg9346, Cfg9346_Lock);
}
if (rtl_chip_info[tp->chipset].flags & HasLWake) {
tmp8 = RTL_R8 (Config4);
if (tmp8 & LWPTN) {
RTL_W8 (Cfg9346, Cfg9346_Unlock);
RTL_W8 (Config4, tmp8 & ~LWPTN);
RTL_W8 (Cfg9346, Cfg9346_Lock);
}
}
} else {
DPRINTK("Old chip wakeup\n");
tmp8 = RTL_R8 (Config1);
tmp8 &= ~(SLEEP | PWRDN);
RTL_W8 (Config1, tmp8);
}
rtl8139_chip_reset (ioaddr);
*dev_out = dev;
return 0;
err_out:
__rtl8139_cleanup_dev (dev);
if (disable_dev_on_err)
pci_disable_device (pdev);
return rc;
}
static int __devinit rtl8139_init_one (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev = NULL;
struct rtl8139_private *tp;
int i, addr_len, option;
void __iomem *ioaddr;
static int board_idx = -1;
u8 pci_rev;
assert (pdev != NULL);
assert (ent != NULL);
board_idx++;
/* when we're built into the kernel, the driver version message
* is only printed if at least one 8139 board has been found
*/
#ifndef MODULE
{
static int printed_version;
if (!printed_version++)
printk (KERN_INFO RTL8139_DRIVER_NAME "\n");
}
#endif
pci_read_config_byte(pdev, PCI_REVISION_ID, &pci_rev);
if (pdev->vendor == PCI_VENDOR_ID_REALTEK &&
pdev->device == PCI_DEVICE_ID_REALTEK_8139 && pci_rev >= 0x20) {
dev_info(&pdev->dev,
"This (id %04x:%04x rev %02x) is an enhanced 8139C+ chip\n",
pdev->vendor, pdev->device, pci_rev);
dev_info(&pdev->dev,
"Use the \"8139cp\" driver for improved performance and stability.\n");
}
i = rtl8139_init_board (pdev, &dev);
if (i < 0)
return i;
assert (dev != NULL);
tp = netdev_priv(dev);
ioaddr = tp->mmio_addr;
assert (ioaddr != NULL);
addr_len = read_eeprom (ioaddr, 0, 8) == 0x8129 ? 8 : 6;
for (i = 0; i < 3; i++)
((u16 *) (dev->dev_addr))[i] =
le16_to_cpu (read_eeprom (ioaddr, i + 7, addr_len));
memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
/* The Rtl8139-specific entries in the device structure. */
dev->open = rtl8139_open;
dev->hard_start_xmit = rtl8139_start_xmit;
dev->poll = rtl8139_poll;
dev->weight = 64;
dev->stop = rtl8139_close;
dev->get_stats = rtl8139_get_stats;
dev->set_multicast_list = rtl8139_set_rx_mode;
dev->do_ioctl = netdev_ioctl;
dev->ethtool_ops = &rtl8139_ethtool_ops;
dev->tx_timeout = rtl8139_tx_timeout;
dev->watchdog_timeo = TX_TIMEOUT;
#ifdef CONFIG_NET_POLL_CONTROLLER
dev->poll_controller = rtl8139_poll_controller;
#endif
/* note: the hardware is not capable of sg/csum/highdma, however
* through the use of skb_copy_and_csum_dev we enable these
* features
*/
dev->features |= NETIF_F_SG | NETIF_F_HW_CSUM | NETIF_F_HIGHDMA;
dev->irq = pdev->irq;
/* tp zeroed and aligned in alloc_etherdev */
tp = netdev_priv(dev);
/* note: tp->chipset set in rtl8139_init_board */
tp->drv_flags = board_info[ent->driver_data].hw_flags;
tp->mmio_addr = ioaddr;
tp->msg_enable =
(debug < 0 ? RTL8139_DEF_MSG_ENABLE : ((1 << debug) - 1));
spin_lock_init (&tp->lock);
spin_lock_init (&tp->rx_lock);
INIT_WORK(&tp->thread, rtl8139_thread, dev);
tp->mii.dev = dev;
tp->mii.mdio_read = mdio_read;
tp->mii.mdio_write = mdio_write;
tp->mii.phy_id_mask = 0x3f;
tp->mii.reg_num_mask = 0x1f;
/* dev is fully set up and ready to use now */
DPRINTK("about to register device named %s (%p)...\n", dev->name, dev);
i = register_netdev (dev);
if (i) goto err_out;
pci_set_drvdata (pdev, dev);
printk (KERN_INFO "%s: %s at 0x%lx, "
"%2.2x:%2.2x:%2.2x:%2.2x:%2.2x:%2.2x, "
"IRQ %d\n",
dev->name,
board_info[ent->driver_data].name,
dev->base_addr,
dev->dev_addr[0], dev->dev_addr[1],
dev->dev_addr[2], dev->dev_addr[3],
dev->dev_addr[4], dev->dev_addr[5],
dev->irq);
printk (KERN_DEBUG "%s: Identified 8139 chip type '%s'\n",
dev->name, rtl_chip_info[tp->chipset].name);
/* Find the connected MII xcvrs.
Doing this in open() would allow detecting external xcvrs later, but
takes too much time. */
#ifdef CONFIG_8139TOO_8129
if (tp->drv_flags & HAS_MII_XCVR) {
int phy, phy_idx = 0;
for (phy = 0; phy < 32 && phy_idx < sizeof(tp->phys); phy++) {
int mii_status = mdio_read(dev, phy, 1);
if (mii_status != 0xffff && mii_status != 0x0000) {
u16 advertising = mdio_read(dev, phy, 4);
tp->phys[phy_idx++] = phy;
printk(KERN_INFO "%s: MII transceiver %d status 0x%4.4x "
"advertising %4.4x.\n",
dev->name, phy, mii_status, advertising);
}
}
if (phy_idx == 0) {
printk(KERN_INFO "%s: No MII transceivers found! Assuming SYM "
"transceiver.\n",
dev->name);
tp->phys[0] = 32;
}
} else
#endif
tp->phys[0] = 32;
tp->mii.phy_id = tp->phys[0];
/* The lower four bits are the media type. */
option = (board_idx >= MAX_UNITS) ? 0 : media[board_idx];
if (option > 0) {
tp->mii.full_duplex = (option & 0x210) ? 1 : 0;
tp->default_port = option & 0xFF;
if (tp->default_port)
tp->mii.force_media = 1;
}
if (board_idx < MAX_UNITS && full_duplex[board_idx] > 0)
tp->mii.full_duplex = full_duplex[board_idx];
if (tp->mii.full_duplex) {
printk(KERN_INFO "%s: Media type forced to Full Duplex.\n", dev->name);
/* Changing the MII-advertised media because might prevent
re-connection. */
tp->mii.force_media = 1;
}
if (tp->default_port) {
printk(KERN_INFO " Forcing %dMbps %s-duplex operation.\n",
(option & 0x20 ? 100 : 10),
(option & 0x10 ? "full" : "half"));
mdio_write(dev, tp->phys[0], 0,
((option & 0x20) ? 0x2000 : 0) | /* 100Mbps? */
((option & 0x10) ? 0x0100 : 0)); /* Full duplex? */
}
/* Put the chip into low-power mode. */
if (rtl_chip_info[tp->chipset].flags & HasHltClk)
RTL_W8 (HltClk, 'H'); /* 'R' would leave the clock running. */
return 0;
err_out:
__rtl8139_cleanup_dev (dev);
pci_disable_device (pdev);
return i;
}
static void __devexit rtl8139_remove_one (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata (pdev);
assert (dev != NULL);
unregister_netdev (dev);
__rtl8139_cleanup_dev (dev);
pci_disable_device (pdev);
}
/* Serial EEPROM section. */
/* EEPROM_Ctrl bits. */
#define EE_SHIFT_CLK 0x04 /* EEPROM shift clock. */
#define EE_CS 0x08 /* EEPROM chip select. */
#define EE_DATA_WRITE 0x02 /* EEPROM chip data in. */
#define EE_WRITE_0 0x00
#define EE_WRITE_1 0x02
#define EE_DATA_READ 0x01 /* EEPROM chip data out. */
#define EE_ENB (0x80 | EE_CS)
/* Delay between EEPROM clock transitions.
No extra delay is needed with 33Mhz PCI, but 66Mhz may change this.
*/
#define eeprom_delay() (void)RTL_R32(Cfg9346)
/* The EEPROM commands include the alway-set leading bit. */
#define EE_WRITE_CMD (5)
#define EE_READ_CMD (6)
#define EE_ERASE_CMD (7)
static int __devinit read_eeprom (void __iomem *ioaddr, int location, int addr_len)
{
int i;
unsigned retval = 0;
int read_cmd = location | (EE_READ_CMD << addr_len);
RTL_W8 (Cfg9346, EE_ENB & ~EE_CS);
RTL_W8 (Cfg9346, EE_ENB);
eeprom_delay ();
/* Shift the read command bits out. */
for (i = 4 + addr_len; i >= 0; i--) {
int dataval = (read_cmd & (1 << i)) ? EE_DATA_WRITE : 0;
RTL_W8 (Cfg9346, EE_ENB | dataval);
eeprom_delay ();
RTL_W8 (Cfg9346, EE_ENB | dataval | EE_SHIFT_CLK);
eeprom_delay ();
}
RTL_W8 (Cfg9346, EE_ENB);
eeprom_delay ();
for (i = 16; i > 0; i--) {
RTL_W8 (Cfg9346, EE_ENB | EE_SHIFT_CLK);
eeprom_delay ();
retval =
(retval << 1) | ((RTL_R8 (Cfg9346) & EE_DATA_READ) ? 1 :
0);
RTL_W8 (Cfg9346, EE_ENB);
eeprom_delay ();
}
/* Terminate the EEPROM access. */
RTL_W8 (Cfg9346, ~EE_CS);
eeprom_delay ();
return retval;
}
/* MII serial management: mostly bogus for now. */
/* Read and write the MII management registers using software-generated
serial MDIO protocol.
The maximum data clock rate is 2.5 Mhz. The minimum timing is usually
met by back-to-back PCI I/O cycles, but we insert a delay to avoid
"overclocking" issues. */
#define MDIO_DIR 0x80
#define MDIO_DATA_OUT 0x04
#define MDIO_DATA_IN 0x02
#define MDIO_CLK 0x01
#define MDIO_WRITE0 (MDIO_DIR)
#define MDIO_WRITE1 (MDIO_DIR | MDIO_DATA_OUT)
#define mdio_delay() RTL_R8(Config4)
static const char mii_2_8139_map[8] = {
BasicModeCtrl,
BasicModeStatus,
0,
0,
NWayAdvert,
NWayLPAR,
NWayExpansion,
0
};
#ifdef CONFIG_8139TOO_8129
/* Syncronize the MII management interface by shifting 32 one bits out. */
static void mdio_sync (void __iomem *ioaddr)
{
int i;
for (i = 32; i >= 0; i--) {
RTL_W8 (Config4, MDIO_WRITE1);
mdio_delay ();
RTL_W8 (Config4, MDIO_WRITE1 | MDIO_CLK);
mdio_delay ();
}
}
#endif
static int mdio_read (struct net_device *dev, int phy_id, int location)
{
struct rtl8139_private *tp = netdev_priv(dev);
int retval = 0;
#ifdef CONFIG_8139TOO_8129
void __iomem *ioaddr = tp->mmio_addr;
int mii_cmd = (0xf6 << 10) | (phy_id << 5) | location;
int i;
#endif
if (phy_id > 31) { /* Really a 8139. Use internal registers. */
void __iomem *ioaddr = tp->mmio_addr;
return location < 8 && mii_2_8139_map[location] ?
RTL_R16 (mii_2_8139_map[location]) : 0;
}
#ifdef CONFIG_8139TOO_8129
mdio_sync (ioaddr);
/* Shift the read command bits out. */
for (i = 15; i >= 0; i--) {
int dataval = (mii_cmd & (1 << i)) ? MDIO_DATA_OUT : 0;
RTL_W8 (Config4, MDIO_DIR | dataval);
mdio_delay ();
RTL_W8 (Config4, MDIO_DIR | dataval | MDIO_CLK);
mdio_delay ();
}
/* Read the two transition, 16 data, and wire-idle bits. */
for (i = 19; i > 0; i--) {
RTL_W8 (Config4, 0);
mdio_delay ();
retval = (retval << 1) | ((RTL_R8 (Config4) & MDIO_DATA_IN) ? 1 : 0);
RTL_W8 (Config4, MDIO_CLK);
mdio_delay ();
}
#endif
return (retval >> 1) & 0xffff;
}
static void mdio_write (struct net_device *dev, int phy_id, int location,
int value)
{
struct rtl8139_private *tp = netdev_priv(dev);
#ifdef CONFIG_8139TOO_8129
void __iomem *ioaddr = tp->mmio_addr;
int mii_cmd = (0x5002 << 16) | (phy_id << 23) | (location << 18) | value;
int i;
#endif
if (phy_id > 31) { /* Really a 8139. Use internal registers. */
void __iomem *ioaddr = tp->mmio_addr;
if (location == 0) {
RTL_W8 (Cfg9346, Cfg9346_Unlock);
RTL_W16 (BasicModeCtrl, value);
RTL_W8 (Cfg9346, Cfg9346_Lock);
} else if (location < 8 && mii_2_8139_map[location])
RTL_W16 (mii_2_8139_map[location], value);
return;
}
#ifdef CONFIG_8139TOO_8129
mdio_sync (ioaddr);
/* Shift the command bits out. */
for (i = 31; i >= 0; i--) {
int dataval =
(mii_cmd & (1 << i)) ? MDIO_WRITE1 : MDIO_WRITE0;
RTL_W8 (Config4, dataval);
mdio_delay ();
RTL_W8 (Config4, dataval | MDIO_CLK);
mdio_delay ();
}
/* Clear out extra bits. */
for (i = 2; i > 0; i--) {
RTL_W8 (Config4, 0);
mdio_delay ();
RTL_W8 (Config4, MDIO_CLK);
mdio_delay ();
}
#endif
}
static int rtl8139_open (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
int retval;
void __iomem *ioaddr = tp->mmio_addr;
retval = request_irq (dev->irq, rtl8139_interrupt, IRQF_SHARED, dev->name, dev);
if (retval)
return retval;
tp->tx_bufs = pci_alloc_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
&tp->tx_bufs_dma);
tp->rx_ring = pci_alloc_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
&tp->rx_ring_dma);
if (tp->tx_bufs == NULL || tp->rx_ring == NULL) {
free_irq(dev->irq, dev);
if (tp->tx_bufs)
pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
tp->tx_bufs, tp->tx_bufs_dma);
if (tp->rx_ring)
pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
tp->rx_ring, tp->rx_ring_dma);
return -ENOMEM;
}
tp->mii.full_duplex = tp->mii.force_media;
tp->tx_flag = (TX_FIFO_THRESH << 11) & 0x003f0000;
rtl8139_init_ring (dev);
rtl8139_hw_start (dev);
netif_start_queue (dev);
if (netif_msg_ifup(tp))
printk(KERN_DEBUG "%s: rtl8139_open() ioaddr %#llx IRQ %d"
" GP Pins %2.2x %s-duplex.\n", dev->name,
(unsigned long long)pci_resource_start (tp->pci_dev, 1),
dev->irq, RTL_R8 (MediaStatus),
tp->mii.full_duplex ? "full" : "half");
rtl8139_start_thread(tp);
return 0;
}
static void rtl_check_media (struct net_device *dev, unsigned int init_media)
{
struct rtl8139_private *tp = netdev_priv(dev);
if (tp->phys[0] >= 0) {
mii_check_media(&tp->mii, netif_msg_link(tp), init_media);
}
}
/* Start the hardware at open or resume. */
static void rtl8139_hw_start (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u32 i;
u8 tmp;
/* Bring old chips out of low-power mode. */
if (rtl_chip_info[tp->chipset].flags & HasHltClk)
RTL_W8 (HltClk, 'R');
rtl8139_chip_reset (ioaddr);
/* unlock Config[01234] and BMCR register writes */
RTL_W8_F (Cfg9346, Cfg9346_Unlock);
/* Restore our idea of the MAC address. */
RTL_W32_F (MAC0 + 0, cpu_to_le32 (*(u32 *) (dev->dev_addr + 0)));
RTL_W32_F (MAC0 + 4, cpu_to_le32 (*(u32 *) (dev->dev_addr + 4)));
/* Must enable Tx/Rx before setting transfer thresholds! */
RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
RTL_W32 (RxConfig, tp->rx_config);
RTL_W32 (TxConfig, rtl8139_tx_config);
tp->cur_rx = 0;
rtl_check_media (dev, 1);
if (tp->chipset >= CH_8139B) {
/* Disable magic packet scanning, which is enabled
* when PM is enabled in Config1. It can be reenabled
* via ETHTOOL_SWOL if desired. */
RTL_W8 (Config3, RTL_R8 (Config3) & ~Cfg3_Magic);
}
DPRINTK("init buffer addresses\n");
/* Lock Config[01234] and BMCR register writes */
RTL_W8 (Cfg9346, Cfg9346_Lock);
/* init Rx ring buffer DMA address */
RTL_W32_F (RxBuf, tp->rx_ring_dma);
/* init Tx buffer DMA addresses */
for (i = 0; i < NUM_TX_DESC; i++)
RTL_W32_F (TxAddr0 + (i * 4), tp->tx_bufs_dma + (tp->tx_buf[i] - tp->tx_bufs));
RTL_W32 (RxMissed, 0);
rtl8139_set_rx_mode (dev);
/* no early-rx interrupts */
RTL_W16 (MultiIntr, RTL_R16 (MultiIntr) & MultiIntrClear);
/* make sure RxTx has started */
tmp = RTL_R8 (ChipCmd);
if ((!(tmp & CmdRxEnb)) || (!(tmp & CmdTxEnb)))
RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
/* Enable all known interrupts by setting the interrupt mask. */
RTL_W16 (IntrMask, rtl8139_intr_mask);
}
/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
static void rtl8139_init_ring (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
int i;
tp->cur_rx = 0;
tp->cur_tx = 0;
tp->dirty_tx = 0;
for (i = 0; i < NUM_TX_DESC; i++)
tp->tx_buf[i] = &tp->tx_bufs[i * TX_BUF_SIZE];
}
/* This must be global for CONFIG_8139TOO_TUNE_TWISTER case */
static int next_tick = 3 * HZ;
#ifndef CONFIG_8139TOO_TUNE_TWISTER
static inline void rtl8139_tune_twister (struct net_device *dev,
struct rtl8139_private *tp) {}
#else
enum TwisterParamVals {
PARA78_default = 0x78fa8388,
PARA7c_default = 0xcb38de43, /* param[0][3] */
PARA7c_xxx = 0xcb38de43,
};
static const unsigned long param[4][4] = {
{0xcb39de43, 0xcb39ce43, 0xfb38de03, 0xcb38de43},
{0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
{0xcb39de43, 0xcb39ce43, 0xcb39ce83, 0xcb39ce83},
{0xbb39de43, 0xbb39ce43, 0xbb39ce83, 0xbb39ce83}
};
static void rtl8139_tune_twister (struct net_device *dev,
struct rtl8139_private *tp)
{
int linkcase;
void __iomem *ioaddr = tp->mmio_addr;
/* This is a complicated state machine to configure the "twister" for
impedance/echos based on the cable length.
All of this is magic and undocumented.
*/
switch (tp->twistie) {
case 1:
if (RTL_R16 (CSCR) & CSCR_LinkOKBit) {
/* We have link beat, let us tune the twister. */
RTL_W16 (CSCR, CSCR_LinkDownOffCmd);
tp->twistie = 2; /* Change to state 2. */
next_tick = HZ / 10;
} else {
/* Just put in some reasonable defaults for when beat returns. */
RTL_W16 (CSCR, CSCR_LinkDownCmd);
RTL_W32 (FIFOTMS, 0x20); /* Turn on cable test mode. */
RTL_W32 (PARA78, PARA78_default);
RTL_W32 (PARA7c, PARA7c_default);
tp->twistie = 0; /* Bail from future actions. */
}
break;
case 2:
/* Read how long it took to hear the echo. */
linkcase = RTL_R16 (CSCR) & CSCR_LinkStatusBits;
if (linkcase == 0x7000)
tp->twist_row = 3;
else if (linkcase == 0x3000)
tp->twist_row = 2;
else if (linkcase == 0x1000)
tp->twist_row = 1;
else
tp->twist_row = 0;
tp->twist_col = 0;
tp->twistie = 3; /* Change to state 2. */
next_tick = HZ / 10;
break;
case 3:
/* Put out four tuning parameters, one per 100msec. */
if (tp->twist_col == 0)
RTL_W16 (FIFOTMS, 0);
RTL_W32 (PARA7c, param[(int) tp->twist_row]
[(int) tp->twist_col]);
next_tick = HZ / 10;
if (++tp->twist_col >= 4) {
/* For short cables we are done.
For long cables (row == 3) check for mistune. */
tp->twistie =
(tp->twist_row == 3) ? 4 : 0;
}
break;
case 4:
/* Special case for long cables: check for mistune. */
if ((RTL_R16 (CSCR) &
CSCR_LinkStatusBits) == 0x7000) {
tp->twistie = 0;
break;
} else {
RTL_W32 (PARA7c, 0xfb38de03);
tp->twistie = 5;
next_tick = HZ / 10;
}
break;
case 5:
/* Retune for shorter cable (column 2). */
RTL_W32 (FIFOTMS, 0x20);
RTL_W32 (PARA78, PARA78_default);
RTL_W32 (PARA7c, PARA7c_default);
RTL_W32 (FIFOTMS, 0x00);
tp->twist_row = 2;
tp->twist_col = 0;
tp->twistie = 3;
next_tick = HZ / 10;
break;
default:
/* do nothing */
break;
}
}
#endif /* CONFIG_8139TOO_TUNE_TWISTER */
static inline void rtl8139_thread_iter (struct net_device *dev,
struct rtl8139_private *tp,
void __iomem *ioaddr)
{
int mii_lpa;
mii_lpa = mdio_read (dev, tp->phys[0], MII_LPA);
if (!tp->mii.force_media && mii_lpa != 0xffff) {
int duplex = (mii_lpa & LPA_100FULL)
|| (mii_lpa & 0x01C0) == 0x0040;
if (tp->mii.full_duplex != duplex) {
tp->mii.full_duplex = duplex;
if (mii_lpa) {
printk (KERN_INFO
"%s: Setting %s-duplex based on MII #%d link"
" partner ability of %4.4x.\n",
dev->name,
tp->mii.full_duplex ? "full" : "half",
tp->phys[0], mii_lpa);
} else {
printk(KERN_INFO"%s: media is unconnected, link down, or incompatible connection\n",
dev->name);
}
#if 0
RTL_W8 (Cfg9346, Cfg9346_Unlock);
RTL_W8 (Config1, tp->mii.full_duplex ? 0x60 : 0x20);
RTL_W8 (Cfg9346, Cfg9346_Lock);
#endif
}
}
next_tick = HZ * 60;
rtl8139_tune_twister (dev, tp);
DPRINTK ("%s: Media selection tick, Link partner %4.4x.\n",
dev->name, RTL_R16 (NWayLPAR));
DPRINTK ("%s: Other registers are IntMask %4.4x IntStatus %4.4x\n",
dev->name, RTL_R16 (IntrMask), RTL_R16 (IntrStatus));
DPRINTK ("%s: Chip config %2.2x %2.2x.\n",
dev->name, RTL_R8 (Config0),
RTL_R8 (Config1));
}
static void rtl8139_thread (void *_data)
{
struct net_device *dev = _data;
struct rtl8139_private *tp = netdev_priv(dev);
unsigned long thr_delay = next_tick;
if (tp->watchdog_fired) {
tp->watchdog_fired = 0;
rtl8139_tx_timeout_task(_data);
} else if (rtnl_trylock()) {
rtl8139_thread_iter (dev, tp, tp->mmio_addr);
rtnl_unlock ();
} else {
/* unlikely race. mitigate with fast poll. */
thr_delay = HZ / 2;
}
schedule_delayed_work(&tp->thread, thr_delay);
}
static void rtl8139_start_thread(struct rtl8139_private *tp)
{
tp->twistie = 0;
if (tp->chipset == CH_8139_K)
tp->twistie = 1;
else if (tp->drv_flags & HAS_LNK_CHNG)
return;
tp->have_thread = 1;
schedule_delayed_work(&tp->thread, next_tick);
}
static void rtl8139_stop_thread(struct rtl8139_private *tp)
{
if (tp->have_thread) {
cancel_rearming_delayed_work(&tp->thread);
tp->have_thread = 0;
} else
flush_scheduled_work();
}
static inline void rtl8139_tx_clear (struct rtl8139_private *tp)
{
tp->cur_tx = 0;
tp->dirty_tx = 0;
/* XXX account for unsent Tx packets in tp->stats.tx_dropped */
}
static void rtl8139_tx_timeout_task (void *_data)
{
struct net_device *dev = _data;
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
int i;
u8 tmp8;
printk (KERN_DEBUG "%s: Transmit timeout, status %2.2x %4.4x %4.4x "
"media %2.2x.\n", dev->name, RTL_R8 (ChipCmd),
RTL_R16(IntrStatus), RTL_R16(IntrMask), RTL_R8(MediaStatus));
/* Emit info to figure out what went wrong. */
printk (KERN_DEBUG "%s: Tx queue start entry %ld dirty entry %ld.\n",
dev->name, tp->cur_tx, tp->dirty_tx);
for (i = 0; i < NUM_TX_DESC; i++)
printk (KERN_DEBUG "%s: Tx descriptor %d is %8.8lx.%s\n",
dev->name, i, RTL_R32 (TxStatus0 + (i * 4)),
i == tp->dirty_tx % NUM_TX_DESC ?
" (queue head)" : "");
tp->xstats.tx_timeouts++;
/* disable Tx ASAP, if not already */
tmp8 = RTL_R8 (ChipCmd);
if (tmp8 & CmdTxEnb)
RTL_W8 (ChipCmd, CmdRxEnb);
spin_lock_bh(&tp->rx_lock);
/* Disable interrupts by clearing the interrupt mask. */
RTL_W16 (IntrMask, 0x0000);
/* Stop a shared interrupt from scavenging while we are. */
spin_lock_irq(&tp->lock);
rtl8139_tx_clear (tp);
spin_unlock_irq(&tp->lock);
/* ...and finally, reset everything */
if (netif_running(dev)) {
rtl8139_hw_start (dev);
netif_wake_queue (dev);
}
spin_unlock_bh(&tp->rx_lock);
}
static void rtl8139_tx_timeout (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
if (!tp->have_thread) {
INIT_WORK(&tp->thread, rtl8139_tx_timeout_task, dev);
schedule_delayed_work(&tp->thread, next_tick);
} else
tp->watchdog_fired = 1;
}
static int rtl8139_start_xmit (struct sk_buff *skb, struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned int entry;
unsigned int len = skb->len;
unsigned long flags;
/* Calculate the next Tx descriptor entry. */
entry = tp->cur_tx % NUM_TX_DESC;
/* Note: the chip doesn't have auto-pad! */
if (likely(len < TX_BUF_SIZE)) {
if (len < ETH_ZLEN)
memset(tp->tx_buf[entry], 0, ETH_ZLEN);
skb_copy_and_csum_dev(skb, tp->tx_buf[entry]);
dev_kfree_skb(skb);
} else {
dev_kfree_skb(skb);
tp->stats.tx_dropped++;
return 0;
}
spin_lock_irqsave(&tp->lock, flags);
RTL_W32_F (TxStatus0 + (entry * sizeof (u32)),
tp->tx_flag | max(len, (unsigned int)ETH_ZLEN));
dev->trans_start = jiffies;
tp->cur_tx++;
wmb();
if ((tp->cur_tx - NUM_TX_DESC) == tp->dirty_tx)
netif_stop_queue (dev);
spin_unlock_irqrestore(&tp->lock, flags);
if (netif_msg_tx_queued(tp))
printk (KERN_DEBUG "%s: Queued Tx packet size %u to slot %d.\n",
dev->name, len, entry);
return 0;
}
static void rtl8139_tx_interrupt (struct net_device *dev,
struct rtl8139_private *tp,
void __iomem *ioaddr)
{
unsigned long dirty_tx, tx_left;
assert (dev != NULL);
assert (ioaddr != NULL);
dirty_tx = tp->dirty_tx;
tx_left = tp->cur_tx - dirty_tx;
while (tx_left > 0) {
int entry = dirty_tx % NUM_TX_DESC;
int txstatus;
txstatus = RTL_R32 (TxStatus0 + (entry * sizeof (u32)));
if (!(txstatus & (TxStatOK | TxUnderrun | TxAborted)))
break; /* It still hasn't been Txed */
/* Note: TxCarrierLost is always asserted at 100mbps. */
if (txstatus & (TxOutOfWindow | TxAborted)) {
/* There was an major error, log it. */
if (netif_msg_tx_err(tp))
printk(KERN_DEBUG "%s: Transmit error, Tx status %8.8x.\n",
dev->name, txstatus);
tp->stats.tx_errors++;
if (txstatus & TxAborted) {
tp->stats.tx_aborted_errors++;
RTL_W32 (TxConfig, TxClearAbt);
RTL_W16 (IntrStatus, TxErr);
wmb();
}
if (txstatus & TxCarrierLost)
tp->stats.tx_carrier_errors++;
if (txstatus & TxOutOfWindow)
tp->stats.tx_window_errors++;
} else {
if (txstatus & TxUnderrun) {
/* Add 64 to the Tx FIFO threshold. */
if (tp->tx_flag < 0x00300000)
tp->tx_flag += 0x00020000;
tp->stats.tx_fifo_errors++;
}
tp->stats.collisions += (txstatus >> 24) & 15;
tp->stats.tx_bytes += txstatus & 0x7ff;
tp->stats.tx_packets++;
}
dirty_tx++;
tx_left--;
}
#ifndef RTL8139_NDEBUG
if (tp->cur_tx - dirty_tx > NUM_TX_DESC) {
printk (KERN_ERR "%s: Out-of-sync dirty pointer, %ld vs. %ld.\n",
dev->name, dirty_tx, tp->cur_tx);
dirty_tx += NUM_TX_DESC;
}
#endif /* RTL8139_NDEBUG */
/* only wake the queue if we did work, and the queue is stopped */
if (tp->dirty_tx != dirty_tx) {
tp->dirty_tx = dirty_tx;
mb();
netif_wake_queue (dev);
}
}
/* TODO: clean this up! Rx reset need not be this intensive */
static void rtl8139_rx_err (u32 rx_status, struct net_device *dev,
struct rtl8139_private *tp, void __iomem *ioaddr)
{
u8 tmp8;
#ifdef CONFIG_8139_OLD_RX_RESET
int tmp_work;
#endif
if (netif_msg_rx_err (tp))
printk(KERN_DEBUG "%s: Ethernet frame had errors, status %8.8x.\n",
dev->name, rx_status);
tp->stats.rx_errors++;
if (!(rx_status & RxStatusOK)) {
if (rx_status & RxTooLong) {
DPRINTK ("%s: Oversized Ethernet frame, status %4.4x!\n",
dev->name, rx_status);
/* A.C.: The chip hangs here. */
}
if (rx_status & (RxBadSymbol | RxBadAlign))
tp->stats.rx_frame_errors++;
if (rx_status & (RxRunt | RxTooLong))
tp->stats.rx_length_errors++;
if (rx_status & RxCRCErr)
tp->stats.rx_crc_errors++;
} else {
tp->xstats.rx_lost_in_ring++;
}
#ifndef CONFIG_8139_OLD_RX_RESET
tmp8 = RTL_R8 (ChipCmd);
RTL_W8 (ChipCmd, tmp8 & ~CmdRxEnb);
RTL_W8 (ChipCmd, tmp8);
RTL_W32 (RxConfig, tp->rx_config);
tp->cur_rx = 0;
#else
/* Reset the receiver, based on RealTek recommendation. (Bug?) */
/* disable receive */
RTL_W8_F (ChipCmd, CmdTxEnb);
tmp_work = 200;
while (--tmp_work > 0) {
udelay(1);
tmp8 = RTL_R8 (ChipCmd);
if (!(tmp8 & CmdRxEnb))
break;
}
if (tmp_work <= 0)
printk (KERN_WARNING PFX "rx stop wait too long\n");
/* restart receive */
tmp_work = 200;
while (--tmp_work > 0) {
RTL_W8_F (ChipCmd, CmdRxEnb | CmdTxEnb);
udelay(1);
tmp8 = RTL_R8 (ChipCmd);
if ((tmp8 & CmdRxEnb) && (tmp8 & CmdTxEnb))
break;
}
if (tmp_work <= 0)
printk (KERN_WARNING PFX "tx/rx enable wait too long\n");
/* and reinitialize all rx related registers */
RTL_W8_F (Cfg9346, Cfg9346_Unlock);
/* Must enable Tx/Rx before setting transfer thresholds! */
RTL_W8 (ChipCmd, CmdRxEnb | CmdTxEnb);
tp->rx_config = rtl8139_rx_config | AcceptBroadcast | AcceptMyPhys;
RTL_W32 (RxConfig, tp->rx_config);
tp->cur_rx = 0;
DPRINTK("init buffer addresses\n");
/* Lock Config[01234] and BMCR register writes */
RTL_W8 (Cfg9346, Cfg9346_Lock);
/* init Rx ring buffer DMA address */
RTL_W32_F (RxBuf, tp->rx_ring_dma);
/* A.C.: Reset the multicast list. */
__set_rx_mode (dev);
#endif
}
#if RX_BUF_IDX == 3
static __inline__ void wrap_copy(struct sk_buff *skb, const unsigned char *ring,
u32 offset, unsigned int size)
{
u32 left = RX_BUF_LEN - offset;
if (size > left) {
memcpy(skb->data, ring + offset, left);
memcpy(skb->data+left, ring, size - left);
} else
memcpy(skb->data, ring + offset, size);
}
#endif
static void rtl8139_isr_ack(struct rtl8139_private *tp)
{
void __iomem *ioaddr = tp->mmio_addr;
u16 status;
status = RTL_R16 (IntrStatus) & RxAckBits;
/* Clear out errors and receive interrupts */
if (likely(status != 0)) {
if (unlikely(status & (RxFIFOOver | RxOverflow))) {
tp->stats.rx_errors++;
if (status & RxFIFOOver)
tp->stats.rx_fifo_errors++;
}
RTL_W16_F (IntrStatus, RxAckBits);
}
}
static int rtl8139_rx(struct net_device *dev, struct rtl8139_private *tp,
int budget)
{
void __iomem *ioaddr = tp->mmio_addr;
int received = 0;
unsigned char *rx_ring = tp->rx_ring;
unsigned int cur_rx = tp->cur_rx;
unsigned int rx_size = 0;
DPRINTK ("%s: In rtl8139_rx(), current %4.4x BufAddr %4.4x,"
" free to %4.4x, Cmd %2.2x.\n", dev->name, (u16)cur_rx,
RTL_R16 (RxBufAddr),
RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
while (netif_running(dev) && received < budget
&& (RTL_R8 (ChipCmd) & RxBufEmpty) == 0) {
u32 ring_offset = cur_rx % RX_BUF_LEN;
u32 rx_status;
unsigned int pkt_size;
struct sk_buff *skb;
rmb();
/* read size+status of next frame from DMA ring buffer */
rx_status = le32_to_cpu (*(u32 *) (rx_ring + ring_offset));
rx_size = rx_status >> 16;
pkt_size = rx_size - 4;
if (netif_msg_rx_status(tp))
printk(KERN_DEBUG "%s: rtl8139_rx() status %4.4x, size %4.4x,"
" cur %4.4x.\n", dev->name, rx_status,
rx_size, cur_rx);
#if RTL8139_DEBUG > 2
{
int i;
DPRINTK ("%s: Frame contents ", dev->name);
for (i = 0; i < 70; i++)
printk (" %2.2x",
rx_ring[ring_offset + i]);
printk (".\n");
}
#endif
/* Packet copy from FIFO still in progress.
* Theoretically, this should never happen
* since EarlyRx is disabled.
*/
if (unlikely(rx_size == 0xfff0)) {
if (!tp->fifo_copy_timeout)
tp->fifo_copy_timeout = jiffies + 2;
else if (time_after(jiffies, tp->fifo_copy_timeout)) {
DPRINTK ("%s: hung FIFO. Reset.", dev->name);
rx_size = 0;
goto no_early_rx;
}
if (netif_msg_intr(tp)) {
printk(KERN_DEBUG "%s: fifo copy in progress.",
dev->name);
}
tp->xstats.early_rx++;
break;
}
no_early_rx:
tp->fifo_copy_timeout = 0;
/* If Rx err or invalid rx_size/rx_status received
* (which happens if we get lost in the ring),
* Rx process gets reset, so we abort any further
* Rx processing.
*/
if (unlikely((rx_size > (MAX_ETH_FRAME_SIZE+4)) ||
(rx_size < 8) ||
(!(rx_status & RxStatusOK)))) {
rtl8139_rx_err (rx_status, dev, tp, ioaddr);
received = -1;
goto out;
}
/* Malloc up new buffer, compatible with net-2e. */
/* Omit the four octet CRC from the length. */
skb = dev_alloc_skb (pkt_size + 2);
if (likely(skb)) {
skb->dev = dev;
skb_reserve (skb, 2); /* 16 byte align the IP fields. */
#if RX_BUF_IDX == 3
wrap_copy(skb, rx_ring, ring_offset+4, pkt_size);
#else
eth_copy_and_sum (skb, &rx_ring[ring_offset + 4], pkt_size, 0);
#endif
skb_put (skb, pkt_size);
skb->protocol = eth_type_trans (skb, dev);
dev->last_rx = jiffies;
tp->stats.rx_bytes += pkt_size;
tp->stats.rx_packets++;
netif_receive_skb (skb);
} else {
if (net_ratelimit())
printk (KERN_WARNING
"%s: Memory squeeze, dropping packet.\n",
dev->name);
tp->stats.rx_dropped++;
}
received++;
cur_rx = (cur_rx + rx_size + 4 + 3) & ~3;
RTL_W16 (RxBufPtr, (u16) (cur_rx - 16));
rtl8139_isr_ack(tp);
}
if (unlikely(!received || rx_size == 0xfff0))
rtl8139_isr_ack(tp);
#if RTL8139_DEBUG > 1
DPRINTK ("%s: Done rtl8139_rx(), current %4.4x BufAddr %4.4x,"
" free to %4.4x, Cmd %2.2x.\n", dev->name, cur_rx,
RTL_R16 (RxBufAddr),
RTL_R16 (RxBufPtr), RTL_R8 (ChipCmd));
#endif
tp->cur_rx = cur_rx;
/*
* The receive buffer should be mostly empty.
* Tell NAPI to reenable the Rx irq.
*/
if (tp->fifo_copy_timeout)
received = budget;
out:
return received;
}
static void rtl8139_weird_interrupt (struct net_device *dev,
struct rtl8139_private *tp,
void __iomem *ioaddr,
int status, int link_changed)
{
DPRINTK ("%s: Abnormal interrupt, status %8.8x.\n",
dev->name, status);
assert (dev != NULL);
assert (tp != NULL);
assert (ioaddr != NULL);
/* Update the error count. */
tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
RTL_W32 (RxMissed, 0);
if ((status & RxUnderrun) && link_changed &&
(tp->drv_flags & HAS_LNK_CHNG)) {
rtl_check_media(dev, 0);
status &= ~RxUnderrun;
}
if (status & (RxUnderrun | RxErr))
tp->stats.rx_errors++;
if (status & PCSTimeout)
tp->stats.rx_length_errors++;
if (status & RxUnderrun)
tp->stats.rx_fifo_errors++;
if (status & PCIErr) {
u16 pci_cmd_status;
pci_read_config_word (tp->pci_dev, PCI_STATUS, &pci_cmd_status);
pci_write_config_word (tp->pci_dev, PCI_STATUS, pci_cmd_status);
printk (KERN_ERR "%s: PCI Bus error %4.4x.\n",
dev->name, pci_cmd_status);
}
}
static int rtl8139_poll(struct net_device *dev, int *budget)
{
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
int orig_budget = min(*budget, dev->quota);
int done = 1;
spin_lock(&tp->rx_lock);
if (likely(RTL_R16(IntrStatus) & RxAckBits)) {
int work_done;
work_done = rtl8139_rx(dev, tp, orig_budget);
if (likely(work_done > 0)) {
*budget -= work_done;
dev->quota -= work_done;
done = (work_done < orig_budget);
}
}
if (done) {
/*
* Order is important since data can get interrupted
* again when we think we are done.
*/
local_irq_disable();
RTL_W16_F(IntrMask, rtl8139_intr_mask);
__netif_rx_complete(dev);
local_irq_enable();
}
spin_unlock(&tp->rx_lock);
return !done;
}
/* The interrupt handler does all of the Rx thread work and cleans up
after the Tx thread. */
static irqreturn_t rtl8139_interrupt (int irq, void *dev_instance)
{
struct net_device *dev = (struct net_device *) dev_instance;
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u16 status, ackstat;
int link_changed = 0; /* avoid bogus "uninit" warning */
int handled = 0;
spin_lock (&tp->lock);
status = RTL_R16 (IntrStatus);
/* shared irq? */
if (unlikely((status & rtl8139_intr_mask) == 0))
goto out;
handled = 1;
/* h/w no longer present (hotplug?) or major error, bail */
if (unlikely(status == 0xFFFF))
goto out;
/* close possible race's with dev_close */
if (unlikely(!netif_running(dev))) {
RTL_W16 (IntrMask, 0);
goto out;
}
/* Acknowledge all of the current interrupt sources ASAP, but
an first get an additional status bit from CSCR. */
if (unlikely(status & RxUnderrun))
link_changed = RTL_R16 (CSCR) & CSCR_LinkChangeBit;
ackstat = status & ~(RxAckBits | TxErr);
if (ackstat)
RTL_W16 (IntrStatus, ackstat);
/* Receive packets are processed by poll routine.
If not running start it now. */
if (status & RxAckBits){
if (netif_rx_schedule_prep(dev)) {
RTL_W16_F (IntrMask, rtl8139_norx_intr_mask);
__netif_rx_schedule (dev);
}
}
/* Check uncommon events with one test. */
if (unlikely(status & (PCIErr | PCSTimeout | RxUnderrun | RxErr)))
rtl8139_weird_interrupt (dev, tp, ioaddr,
status, link_changed);
if (status & (TxOK | TxErr)) {
rtl8139_tx_interrupt (dev, tp, ioaddr);
if (status & TxErr)
RTL_W16 (IntrStatus, TxErr);
}
out:
spin_unlock (&tp->lock);
DPRINTK ("%s: exiting interrupt, intr_status=%#4.4x.\n",
dev->name, RTL_R16 (IntrStatus));
return IRQ_RETVAL(handled);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling receive - used by netconsole and other diagnostic tools
* to allow network i/o with interrupts disabled.
*/
static void rtl8139_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
rtl8139_interrupt(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
static int rtl8139_close (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned long flags;
netif_stop_queue (dev);
rtl8139_stop_thread(tp);
if (netif_msg_ifdown(tp))
printk(KERN_DEBUG "%s: Shutting down ethercard, status was 0x%4.4x.\n",
dev->name, RTL_R16 (IntrStatus));
spin_lock_irqsave (&tp->lock, flags);
/* Stop the chip's Tx and Rx DMA processes. */
RTL_W8 (ChipCmd, 0);
/* Disable interrupts by clearing the interrupt mask. */
RTL_W16 (IntrMask, 0);
/* Update the error counts. */
tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
RTL_W32 (RxMissed, 0);
spin_unlock_irqrestore (&tp->lock, flags);
synchronize_irq (dev->irq); /* racy, but that's ok here */
free_irq (dev->irq, dev);
rtl8139_tx_clear (tp);
pci_free_consistent(tp->pci_dev, RX_BUF_TOT_LEN,
tp->rx_ring, tp->rx_ring_dma);
pci_free_consistent(tp->pci_dev, TX_BUF_TOT_LEN,
tp->tx_bufs, tp->tx_bufs_dma);
tp->rx_ring = NULL;
tp->tx_bufs = NULL;
/* Green! Put the chip in low-power mode. */
RTL_W8 (Cfg9346, Cfg9346_Unlock);
if (rtl_chip_info[tp->chipset].flags & HasHltClk)
RTL_W8 (HltClk, 'H'); /* 'R' would leave the clock running. */
return 0;
}
/* Get the ethtool Wake-on-LAN settings. Assumes that wol points to
kernel memory, *wol has been initialized as {ETHTOOL_GWOL}, and
other threads or interrupts aren't messing with the 8139. */
static void rtl8139_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct rtl8139_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->mmio_addr;
spin_lock_irq(&np->lock);
if (rtl_chip_info[np->chipset].flags & HasLWake) {
u8 cfg3 = RTL_R8 (Config3);
u8 cfg5 = RTL_R8 (Config5);
wol->supported = WAKE_PHY | WAKE_MAGIC
| WAKE_UCAST | WAKE_MCAST | WAKE_BCAST;
wol->wolopts = 0;
if (cfg3 & Cfg3_LinkUp)
wol->wolopts |= WAKE_PHY;
if (cfg3 & Cfg3_Magic)
wol->wolopts |= WAKE_MAGIC;
/* (KON)FIXME: See how netdev_set_wol() handles the
following constants. */
if (cfg5 & Cfg5_UWF)
wol->wolopts |= WAKE_UCAST;
if (cfg5 & Cfg5_MWF)
wol->wolopts |= WAKE_MCAST;
if (cfg5 & Cfg5_BWF)
wol->wolopts |= WAKE_BCAST;
}
spin_unlock_irq(&np->lock);
}
/* Set the ethtool Wake-on-LAN settings. Return 0 or -errno. Assumes
that wol points to kernel memory and other threads or interrupts
aren't messing with the 8139. */
static int rtl8139_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct rtl8139_private *np = netdev_priv(dev);
void __iomem *ioaddr = np->mmio_addr;
u32 support;
u8 cfg3, cfg5;
support = ((rtl_chip_info[np->chipset].flags & HasLWake)
? (WAKE_PHY | WAKE_MAGIC
| WAKE_UCAST | WAKE_MCAST | WAKE_BCAST)
: 0);
if (wol->wolopts & ~support)
return -EINVAL;
spin_lock_irq(&np->lock);
cfg3 = RTL_R8 (Config3) & ~(Cfg3_LinkUp | Cfg3_Magic);
if (wol->wolopts & WAKE_PHY)
cfg3 |= Cfg3_LinkUp;
if (wol->wolopts & WAKE_MAGIC)
cfg3 |= Cfg3_Magic;
RTL_W8 (Cfg9346, Cfg9346_Unlock);
RTL_W8 (Config3, cfg3);
RTL_W8 (Cfg9346, Cfg9346_Lock);
cfg5 = RTL_R8 (Config5) & ~(Cfg5_UWF | Cfg5_MWF | Cfg5_BWF);
/* (KON)FIXME: These are untested. We may have to set the
CRC0, Wakeup0 and LSBCRC0 registers too, but I have no
documentation. */
if (wol->wolopts & WAKE_UCAST)
cfg5 |= Cfg5_UWF;
if (wol->wolopts & WAKE_MCAST)
cfg5 |= Cfg5_MWF;
if (wol->wolopts & WAKE_BCAST)
cfg5 |= Cfg5_BWF;
RTL_W8 (Config5, cfg5); /* need not unlock via Cfg9346 */
spin_unlock_irq(&np->lock);
return 0;
}
static void rtl8139_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct rtl8139_private *np = netdev_priv(dev);
strcpy(info->driver, DRV_NAME);
strcpy(info->version, DRV_VERSION);
strcpy(info->bus_info, pci_name(np->pci_dev));
info->regdump_len = np->regs_len;
}
static int rtl8139_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct rtl8139_private *np = netdev_priv(dev);
spin_lock_irq(&np->lock);
mii_ethtool_gset(&np->mii, cmd);
spin_unlock_irq(&np->lock);
return 0;
}
static int rtl8139_set_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
struct rtl8139_private *np = netdev_priv(dev);
int rc;
spin_lock_irq(&np->lock);
rc = mii_ethtool_sset(&np->mii, cmd);
spin_unlock_irq(&np->lock);
return rc;
}
static int rtl8139_nway_reset(struct net_device *dev)
{
struct rtl8139_private *np = netdev_priv(dev);
return mii_nway_restart(&np->mii);
}
static u32 rtl8139_get_link(struct net_device *dev)
{
struct rtl8139_private *np = netdev_priv(dev);
return mii_link_ok(&np->mii);
}
static u32 rtl8139_get_msglevel(struct net_device *dev)
{
struct rtl8139_private *np = netdev_priv(dev);
return np->msg_enable;
}
static void rtl8139_set_msglevel(struct net_device *dev, u32 datum)
{
struct rtl8139_private *np = netdev_priv(dev);
np->msg_enable = datum;
}
/* TODO: we are too slack to do reg dumping for pio, for now */
#ifdef CONFIG_8139TOO_PIO
#define rtl8139_get_regs_len NULL
#define rtl8139_get_regs NULL
#else
static int rtl8139_get_regs_len(struct net_device *dev)
{
struct rtl8139_private *np = netdev_priv(dev);
return np->regs_len;
}
static void rtl8139_get_regs(struct net_device *dev, struct ethtool_regs *regs, void *regbuf)
{
struct rtl8139_private *np = netdev_priv(dev);
regs->version = RTL_REGS_VER;
spin_lock_irq(&np->lock);
memcpy_fromio(regbuf, np->mmio_addr, regs->len);
spin_unlock_irq(&np->lock);
}
#endif /* CONFIG_8139TOO_MMIO */
static int rtl8139_get_stats_count(struct net_device *dev)
{
return RTL_NUM_STATS;
}
static void rtl8139_get_ethtool_stats(struct net_device *dev, struct ethtool_stats *stats, u64 *data)
{
struct rtl8139_private *np = netdev_priv(dev);
data[0] = np->xstats.early_rx;
data[1] = np->xstats.tx_buf_mapped;
data[2] = np->xstats.tx_timeouts;
data[3] = np->xstats.rx_lost_in_ring;
}
static void rtl8139_get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
memcpy(data, ethtool_stats_keys, sizeof(ethtool_stats_keys));
}
static const struct ethtool_ops rtl8139_ethtool_ops = {
.get_drvinfo = rtl8139_get_drvinfo,
.get_settings = rtl8139_get_settings,
.set_settings = rtl8139_set_settings,
.get_regs_len = rtl8139_get_regs_len,
.get_regs = rtl8139_get_regs,
.nway_reset = rtl8139_nway_reset,
.get_link = rtl8139_get_link,
.get_msglevel = rtl8139_get_msglevel,
.set_msglevel = rtl8139_set_msglevel,
.get_wol = rtl8139_get_wol,
.set_wol = rtl8139_set_wol,
.get_strings = rtl8139_get_strings,
.get_stats_count = rtl8139_get_stats_count,
.get_ethtool_stats = rtl8139_get_ethtool_stats,
.get_perm_addr = ethtool_op_get_perm_addr,
};
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct rtl8139_private *np = netdev_priv(dev);
int rc;
if (!netif_running(dev))
return -EINVAL;
spin_lock_irq(&np->lock);
rc = generic_mii_ioctl(&np->mii, if_mii(rq), cmd, NULL);
spin_unlock_irq(&np->lock);
return rc;
}
static struct net_device_stats *rtl8139_get_stats (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned long flags;
if (netif_running(dev)) {
spin_lock_irqsave (&tp->lock, flags);
tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
RTL_W32 (RxMissed, 0);
spin_unlock_irqrestore (&tp->lock, flags);
}
return &tp->stats;
}
/* Set or clear the multicast filter for this adaptor.
This routine is not state sensitive and need not be SMP locked. */
static void __set_rx_mode (struct net_device *dev)
{
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
u32 mc_filter[2]; /* Multicast hash filter */
int i, rx_mode;
u32 tmp;
DPRINTK ("%s: rtl8139_set_rx_mode(%4.4x) done -- Rx config %8.8lx.\n",
dev->name, dev->flags, RTL_R32 (RxConfig));
/* Note: do not reorder, GCC is clever about common statements. */
if (dev->flags & IFF_PROMISC) {
rx_mode =
AcceptBroadcast | AcceptMulticast | AcceptMyPhys |
AcceptAllPhys;
mc_filter[1] = mc_filter[0] = 0xffffffff;
} else if ((dev->mc_count > multicast_filter_limit)
|| (dev->flags & IFF_ALLMULTI)) {
/* Too many to filter perfectly -- accept all multicasts. */
rx_mode = AcceptBroadcast | AcceptMulticast | AcceptMyPhys;
mc_filter[1] = mc_filter[0] = 0xffffffff;
} else {
struct dev_mc_list *mclist;
rx_mode = AcceptBroadcast | AcceptMyPhys;
mc_filter[1] = mc_filter[0] = 0;
for (i = 0, mclist = dev->mc_list; mclist && i < dev->mc_count;
i++, mclist = mclist->next) {
int bit_nr = ether_crc(ETH_ALEN, mclist->dmi_addr) >> 26;
mc_filter[bit_nr >> 5] |= 1 << (bit_nr & 31);
rx_mode |= AcceptMulticast;
}
}
/* We can safely update without stopping the chip. */
tmp = rtl8139_rx_config | rx_mode;
if (tp->rx_config != tmp) {
RTL_W32_F (RxConfig, tmp);
tp->rx_config = tmp;
}
RTL_W32_F (MAR0 + 0, mc_filter[0]);
RTL_W32_F (MAR0 + 4, mc_filter[1]);
}
static void rtl8139_set_rx_mode (struct net_device *dev)
{
unsigned long flags;
struct rtl8139_private *tp = netdev_priv(dev);
spin_lock_irqsave (&tp->lock, flags);
__set_rx_mode(dev);
spin_unlock_irqrestore (&tp->lock, flags);
}
#ifdef CONFIG_PM
static int rtl8139_suspend (struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata (pdev);
struct rtl8139_private *tp = netdev_priv(dev);
void __iomem *ioaddr = tp->mmio_addr;
unsigned long flags;
pci_save_state (pdev);
if (!netif_running (dev))
return 0;
netif_device_detach (dev);
spin_lock_irqsave (&tp->lock, flags);
/* Disable interrupts, stop Tx and Rx. */
RTL_W16 (IntrMask, 0);
RTL_W8 (ChipCmd, 0);
/* Update the error counts. */
tp->stats.rx_missed_errors += RTL_R32 (RxMissed);
RTL_W32 (RxMissed, 0);
spin_unlock_irqrestore (&tp->lock, flags);
pci_set_power_state (pdev, PCI_D3hot);
return 0;
}
static int rtl8139_resume (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata (pdev);
pci_restore_state (pdev);
if (!netif_running (dev))
return 0;
pci_set_power_state (pdev, PCI_D0);
rtl8139_init_ring (dev);
rtl8139_hw_start (dev);
netif_device_attach (dev);
return 0;
}
#endif /* CONFIG_PM */
static struct pci_driver rtl8139_pci_driver = {
.name = DRV_NAME,
.id_table = rtl8139_pci_tbl,
.probe = rtl8139_init_one,
.remove = __devexit_p(rtl8139_remove_one),
#ifdef CONFIG_PM
.suspend = rtl8139_suspend,
.resume = rtl8139_resume,
#endif /* CONFIG_PM */
};
static int __init rtl8139_init_module (void)
{
/* when we're a module, we always print a version message,
* even if no 8139 board is found.
*/
#ifdef MODULE
printk (KERN_INFO RTL8139_DRIVER_NAME "\n");
#endif
return pci_register_driver(&rtl8139_pci_driver);
}
static void __exit rtl8139_cleanup_module (void)
{
pci_unregister_driver (&rtl8139_pci_driver);
}
module_init(rtl8139_init_module);
module_exit(rtl8139_cleanup_module);
| milaq/linux-hpc | drivers/net/8139too.c | C | gpl-2.0 | 70,963 |
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Common.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Common.h"
#include "Network.h"
using namespace std;
using namespace dev;
using namespace dev::p2p;
const unsigned dev::p2p::c_protocolVersion = 4;
const unsigned dev::p2p::c_defaultIPPort = 30303;
static_assert(dev::p2p::c_protocolVersion == 4, "Replace v3 compatbility with v4 compatibility before updating network version.");
const dev::p2p::NodeIPEndpoint dev::p2p::UnspecifiedNodeIPEndpoint = NodeIPEndpoint(bi::address(), 0, 0);
const dev::p2p::Node dev::p2p::UnspecifiedNode = dev::p2p::Node(NodeID(), UnspecifiedNodeIPEndpoint);
bool dev::p2p::NodeIPEndpoint::test_allowLocal = false;
//⊳⊲◀▶■▣▢□▷◁▧▨▩▲◆◉◈◇◎●◍◌○◼☑☒☎☢☣☰☀♽♥♠✩✭❓✔✓✖✕✘✓✔✅⚒⚡⦸⬌∅⁕«««»»»⚙━┅┉▬
#if defined(_WIN32)
const char* NetWarn::name() { return EthYellow "N" EthRed " X"; }
const char* NetImpolite::name() { return EthYellow "N" EthRed " !"; }
const char* NetNote::name() { return EthYellow "N" EthBlue " i"; }
const char* NetConnect::name() { return EthYellow "N" EthYellow " C"; }
const char* NetMessageSummary::name() { return EthYellow "N" EthWhite " ."; }
const char* NetMessageDetail::name() { return EthYellow "N" EthGray " o"; }
const char* NetTriviaSummary::name() { return EthYellow "N" EthGray " O"; }
const char* NetTriviaDetail::name() { return EthYellow "N" EthCoal " 0"; }
const char* NetAllDetail::name() { return EthYellow "N" EthCoal " A"; }
const char* NetRight::name() { return EthYellow "N" EthGreen "->"; }
const char* NetLeft::name() { return EthYellow "N" EthNavy "<-"; }
const char* NetP2PWarn::name() { return EthYellow "N" EthRed " X"; }
const char* NetP2PNote::name() { return EthYellow "N" EthBlue " i"; }
const char* NetP2PConnect::name() { return EthYellow "N" EthYellow " C"; }
#else
const char* NetWarn::name() { return EthYellow "⧎" EthRed " ✘"; }
const char* NetImpolite::name() { return EthYellow "⧎" EthRed " !"; }
const char* NetNote::name() { return EthYellow "⧎" EthBlue " ℹ"; }
const char* NetConnect::name() { return EthYellow "⧎" EthYellow " ▢"; }
const char* NetMessageSummary::name() { return EthYellow "⧎" EthWhite " ◌"; }
const char* NetMessageDetail::name() { return EthYellow "⧎" EthGray " ○"; }
const char* NetTriviaSummary::name() { return EthYellow "⧎" EthGray " ◎"; }
const char* NetTriviaDetail::name() { return EthYellow "⧎" EthCoal " ◍"; }
const char* NetAllDetail::name() { return EthYellow "⧎" EthCoal " ●"; }
const char* NetRight::name() { return EthYellow "⧎" EthGreen "▬▶"; }
const char* NetLeft::name() { return EthYellow "⧎" EthNavy "◀▬"; }
const char* NetP2PWarn::name() { return EthYellow "⧎" EthRed " ✘"; }
const char* NetP2PNote::name() { return EthYellow "⧎" EthBlue " ℹ"; }
const char* NetP2PConnect::name() { return EthYellow "⧎" EthYellow " ▢"; }
#endif
bool p2p::isPublicAddress(std::string const& _addressToCheck)
{
return _addressToCheck.empty() ? false : isPublicAddress(bi::address::from_string(_addressToCheck));
}
bool p2p::isPublicAddress(bi::address const& _addressToCheck)
{
return !(isPrivateAddress(_addressToCheck) || isLocalHostAddress(_addressToCheck));
}
// Helper function to determine if an address falls within one of the reserved ranges
// For V4:
// Class A "10.*", Class B "172.[16->31].*", Class C "192.168.*"
bool p2p::isPrivateAddress(bi::address const& _addressToCheck)
{
if (_addressToCheck.is_v4())
{
bi::address_v4 v4Address = _addressToCheck.to_v4();
bi::address_v4::bytes_type bytesToCheck = v4Address.to_bytes();
if (bytesToCheck[0] == 10 || bytesToCheck[0] == 127)
return true;
if (bytesToCheck[0] == 172 && (bytesToCheck[1] >= 16 && bytesToCheck[1] <= 31))
return true;
if (bytesToCheck[0] == 192 && bytesToCheck[1] == 168)
return true;
}
else if (_addressToCheck.is_v6())
{
bi::address_v6 v6Address = _addressToCheck.to_v6();
bi::address_v6::bytes_type bytesToCheck = v6Address.to_bytes();
if (bytesToCheck[0] == 0xfd && bytesToCheck[1] == 0)
return true;
if (!bytesToCheck[0] && !bytesToCheck[1] && !bytesToCheck[2] && !bytesToCheck[3] && !bytesToCheck[4] && !bytesToCheck[5] && !bytesToCheck[6] && !bytesToCheck[7]
&& !bytesToCheck[8] && !bytesToCheck[9] && !bytesToCheck[10] && !bytesToCheck[11] && !bytesToCheck[12] && !bytesToCheck[13] && !bytesToCheck[14] && (bytesToCheck[15] == 0 || bytesToCheck[15] == 1))
return true;
}
return false;
}
bool p2p::isPrivateAddress(std::string const& _addressToCheck)
{
return _addressToCheck.empty() ? false : isPrivateAddress(bi::address::from_string(_addressToCheck));
}
// Helper function to determine if an address is localhost
bool p2p::isLocalHostAddress(bi::address const& _addressToCheck)
{
// @todo: ivp6 link-local adresses (macos), ex: fe80::1%lo0
static const set<bi::address> c_rejectAddresses = {
{bi::address_v4::from_string("127.0.0.1")},
{bi::address_v4::from_string("0.0.0.0")},
{bi::address_v6::from_string("::1")},
{bi::address_v6::from_string("::")}
};
return find(c_rejectAddresses.begin(), c_rejectAddresses.end(), _addressToCheck) != c_rejectAddresses.end();
}
bool p2p::isLocalHostAddress(std::string const& _addressToCheck)
{
return _addressToCheck.empty() ? false : isLocalHostAddress(bi::address::from_string(_addressToCheck));
}
std::string p2p::reasonOf(DisconnectReason _r)
{
switch (_r)
{
case DisconnectRequested: return "Disconnect was requested.";
case TCPError: return "Low-level TCP communication error.";
case BadProtocol: return "Data format error.";
case UselessPeer: return "Peer had no use for this node.";
case TooManyPeers: return "Peer had too many connections.";
case DuplicatePeer: return "Peer was already connected.";
case IncompatibleProtocol: return "Peer protocol versions are incompatible.";
case NullIdentity: return "Null identity given.";
case ClientQuit: return "Peer is exiting.";
case UnexpectedIdentity: return "Unexpected identity given.";
case LocalIdentity: return "Connected to ourselves.";
case UserReason: return "Subprotocol reason.";
case NoDisconnect: return "(No disconnect has happened.)";
default: return "Unknown reason.";
}
}
void NodeIPEndpoint::streamRLP(RLPStream& _s, RLPAppend _append) const
{
if (_append == StreamList)
_s.appendList(3);
if (address.is_v4())
_s << bytesConstRef(&address.to_v4().to_bytes()[0], 4);
else if (address.is_v6())
_s << bytesConstRef(&address.to_v6().to_bytes()[0], 16);
else
_s << bytes();
_s << udpPort << tcpPort;
}
void NodeIPEndpoint::interpretRLP(RLP const& _r)
{
if (_r[0].size() == 4)
address = bi::address_v4(*(bi::address_v4::bytes_type*)_r[0].toBytes().data());
else if (_r[0].size() == 16)
address = bi::address_v6(*(bi::address_v6::bytes_type*)_r[0].toBytes().data());
else
address = bi::address();
udpPort = _r[1].toInt<uint16_t>();
tcpPort = _r[2].toInt<uint16_t>();
}
void DeadlineOps::reap()
{
if (m_stopped)
return;
Guard l(x_timers);
std::vector<DeadlineOp>::iterator t = m_timers.begin();
while (t != m_timers.end())
if (t->expired())
{
t->wait();
t = m_timers.erase(t);
}
else
t++;
m_timers.emplace_back(m_io, m_reapIntervalMs, [this](boost::system::error_code const& ec)
{
if (!ec && !m_stopped)
reap();
});
}
Node::Node(NodeSpec const& _s, PeerType _p):
id(_s.id()),
endpoint(_s.nodeIPEndpoint()),
peerType(_p)
{}
NodeSpec::NodeSpec(string const& _user)
{
m_address = _user;
if (m_address.substr(0, 8) == "enode://" && m_address.find('@') == 136)
{
m_id = p2p::NodeID(m_address.substr(8, 128));
m_address = m_address.substr(137);
}
size_t colon = m_address.find_first_of(":");
if (colon != string::npos)
{
string ports = m_address.substr(colon + 1);
m_address = m_address.substr(0, colon);
size_t p2 = ports.find_first_of(".");
if (p2 != string::npos)
{
m_udpPort = stoi(ports.substr(p2 + 1));
m_tcpPort = stoi(ports.substr(0, p2));
}
else
m_tcpPort = m_udpPort = stoi(ports);
}
}
NodeIPEndpoint NodeSpec::nodeIPEndpoint() const
{
return NodeIPEndpoint(p2p::Network::resolveHost(m_address).address(), m_udpPort, m_tcpPort);
}
std::string NodeSpec::enode() const
{
string ret = m_address;
if (m_tcpPort)
if (m_udpPort && m_tcpPort != m_udpPort)
ret += ":" + toString(m_tcpPort) + "." + toString(m_udpPort);
else
ret += ":" + toString(m_tcpPort);
else if (m_udpPort)
ret += ":" + toString(m_udpPort);
if (m_id)
return "enode://" + m_id.hex() + "@" + ret;
return ret;
}
namespace dev
{
std::ostream& operator<<(std::ostream& _out, dev::p2p::NodeIPEndpoint const& _ep)
{
_out << _ep.address << _ep.udpPort << _ep.tcpPort;
return _out;
}
}
| ZiberLTD/windows | microsip/blockchain/libp2p/Common.cpp | C++ | gpl-2.0 | 9,432 |
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Generic socket support routines. Memory allocators, socket lock/release
* handler for protocols to use and generic option handler.
*
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Florian La Roche, <flla@stud.uni-sb.de>
* Alan Cox, <A.Cox@swansea.ac.uk>
*
* Fixes:
* Alan Cox : Numerous verify_area() problems
* Alan Cox : Connecting on a connecting socket
* now returns an error for tcp.
* Alan Cox : sock->protocol is set correctly.
* and is not sometimes left as 0.
* Alan Cox : connect handles icmp errors on a
* connect properly. Unfortunately there
* is a restart syscall nasty there. I
* can't match BSD without hacking the C
* library. Ideas urgently sought!
* Alan Cox : Disallow bind() to addresses that are
* not ours - especially broadcast ones!!
* Alan Cox : Socket 1024 _IS_ ok for users. (fencepost)
* Alan Cox : sock_wfree/sock_rfree don't destroy sockets,
* instead they leave that for the DESTROY timer.
* Alan Cox : Clean up error flag in accept
* Alan Cox : TCP ack handling is buggy, the DESTROY timer
* was buggy. Put a remove_sock() in the handler
* for memory when we hit 0. Also altered the timer
* code. The ACK stuff can wait and needs major
* TCP layer surgery.
* Alan Cox : Fixed TCP ack bug, removed remove sock
* and fixed timer/inet_bh race.
* Alan Cox : Added zapped flag for TCP
* Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code
* Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb
* Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources
* Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing.
* Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so...
* Rick Sladkey : Relaxed UDP rules for matching packets.
* C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support
* Pauline Middelink : identd support
* Alan Cox : Fixed connect() taking signals I think.
* Alan Cox : SO_LINGER supported
* Alan Cox : Error reporting fixes
* Anonymous : inet_create tidied up (sk->reuse setting)
* Alan Cox : inet sockets don't set sk->type!
* Alan Cox : Split socket option code
* Alan Cox : Callbacks
* Alan Cox : Nagle flag for Charles & Johannes stuff
* Alex : Removed restriction on inet fioctl
* Alan Cox : Splitting INET from NET core
* Alan Cox : Fixed bogus SO_TYPE handling in getsockopt()
* Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code
* Alan Cox : Split IP from generic code
* Alan Cox : New kfree_skbmem()
* Alan Cox : Make SO_DEBUG superuser only.
* Alan Cox : Allow anyone to clear SO_DEBUG
* (compatibility fix)
* Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput.
* Alan Cox : Allocator for a socket is settable.
* Alan Cox : SO_ERROR includes soft errors.
* Alan Cox : Allow NULL arguments on some SO_ opts
* Alan Cox : Generic socket allocation to make hooks
* easier (suggested by Craig Metz).
* Michael Pall : SO_ERROR returns positive errno again
* Steve Whitehouse: Added default destructor to free
* protocol private data.
* Steve Whitehouse: Added various other default routines
* common to several socket families.
* Chris Evans : Call suser() check last on F_SETOWN
* Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER.
* Andi Kleen : Add sock_kmalloc()/sock_kfree_s()
* Andi Kleen : Fix write_space callback
* Chris Evans : Security fixes - signedness again
* Arnaldo C. Melo : cleanups, use skb_queue_purge
*
* To Fix:
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/errqueue.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/poll.h>
#include <linux/tcp.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/user_namespace.h>
#include <linux/static_key.h>
#include <linux/memcontrol.h>
#include <linux/prefetch.h>
#include <asm/uaccess.h>
#include <linux/netdevice.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/request_sock.h>
#include <net/sock.h>
#include <linux/net_tstamp.h>
#include <net/xfrm.h>
#include <linux/ipsec.h>
#include <net/cls_cgroup.h>
#include <net/netprio_cgroup.h>
#include <linux/sock_diag.h>
#include <linux/filter.h>
#include <net/sock_reuseport.h>
#include <trace/events/sock.h>
#ifdef CONFIG_INET
#include <net/tcp.h>
#endif
#include <net/busy_poll.h>
static DEFINE_MUTEX(proto_list_mutex);
static LIST_HEAD(proto_list);
/**
* sk_ns_capable - General socket capability test
* @sk: Socket to use a capability on or through
* @user_ns: The user namespace of the capability to use
* @cap: The capability to use
*
* Test to see if the opener of the socket had when the socket was
* created and the current process has the capability @cap in the user
* namespace @user_ns.
*/
bool sk_ns_capable(const struct sock *sk,
struct user_namespace *user_ns, int cap)
{
return file_ns_capable(sk->sk_socket->file, user_ns, cap) &&
ns_capable(user_ns, cap);
}
EXPORT_SYMBOL(sk_ns_capable);
/**
* sk_capable - Socket global capability test
* @sk: Socket to use a capability on or through
* @cap: The global capability to use
*
* Test to see if the opener of the socket had when the socket was
* created and the current process has the capability @cap in all user
* namespaces.
*/
bool sk_capable(const struct sock *sk, int cap)
{
return sk_ns_capable(sk, &init_user_ns, cap);
}
EXPORT_SYMBOL(sk_capable);
/**
* sk_net_capable - Network namespace socket capability test
* @sk: Socket to use a capability on or through
* @cap: The capability to use
*
* Test to see if the opener of the socket had when the socket was created
* and the current process has the capability @cap over the network namespace
* the socket is a member of.
*/
bool sk_net_capable(const struct sock *sk, int cap)
{
return sk_ns_capable(sk, sock_net(sk)->user_ns, cap);
}
EXPORT_SYMBOL(sk_net_capable);
/*
* Each address family might have different locking rules, so we have
* one slock key per address family:
*/
static struct lock_class_key af_family_keys[AF_MAX];
static struct lock_class_key af_family_slock_keys[AF_MAX];
/*
* Make lock validator output more readable. (we pre-construct these
* strings build-time, so that runtime initialization of socket
* locks is fast):
*/
static const char *const af_family_key_strings[AF_MAX+1] = {
"sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" ,
"sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK",
"sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" ,
"sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" ,
"sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" ,
"sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" ,
"sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" ,
"sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" ,
"sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" ,
"sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" ,
"sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" ,
"sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" ,
"sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" ,
"sk_lock-AF_NFC" , "sk_lock-AF_VSOCK" , "sk_lock-AF_KCM" ,
"sk_lock-AF_MAX"
};
static const char *const af_family_slock_key_strings[AF_MAX+1] = {
"slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" ,
"slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK",
"slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" ,
"slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" ,
"slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" ,
"slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" ,
"slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" ,
"slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" ,
"slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" ,
"slock-27" , "slock-28" , "slock-AF_CAN" ,
"slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" ,
"slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" ,
"slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" ,
"slock-AF_NFC" , "slock-AF_VSOCK" ,"slock-AF_KCM" ,
"slock-AF_MAX"
};
static const char *const af_family_clock_key_strings[AF_MAX+1] = {
"clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" ,
"clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK",
"clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" ,
"clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" ,
"clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" ,
"clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" ,
"clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" ,
"clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" ,
"clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" ,
"clock-27" , "clock-28" , "clock-AF_CAN" ,
"clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" ,
"clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" ,
"clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" ,
"clock-AF_NFC" , "clock-AF_VSOCK" , "clock-AF_KCM" ,
"clock-AF_MAX"
};
/*
* sk_callback_lock locking rules are per-address-family,
* so split the lock classes by using a per-AF key:
*/
static struct lock_class_key af_callback_keys[AF_MAX];
/* Take into consideration the size of the struct sk_buff overhead in the
* determination of these values, since that is non-constant across
* platforms. This makes socket queueing behavior and performance
* not depend upon such differences.
*/
#define _SK_MEM_PACKETS 256
#define _SK_MEM_OVERHEAD SKB_TRUESIZE(256)
#define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
#define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
/* Run time adjustable parameters. */
__u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
EXPORT_SYMBOL(sysctl_wmem_max);
__u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
EXPORT_SYMBOL(sysctl_rmem_max);
__u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
__u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
/* Maximal space eaten by iovec or ancillary data plus some space */
int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
EXPORT_SYMBOL(sysctl_optmem_max);
int sysctl_tstamp_allow_data __read_mostly = 1;
struct static_key memalloc_socks = STATIC_KEY_INIT_FALSE;
EXPORT_SYMBOL_GPL(memalloc_socks);
/**
* sk_set_memalloc - sets %SOCK_MEMALLOC
* @sk: socket to set it on
*
* Set %SOCK_MEMALLOC on a socket for access to emergency reserves.
* It's the responsibility of the admin to adjust min_free_kbytes
* to meet the requirements
*/
void sk_set_memalloc(struct sock *sk)
{
sock_set_flag(sk, SOCK_MEMALLOC);
sk->sk_allocation |= __GFP_MEMALLOC;
static_key_slow_inc(&memalloc_socks);
}
EXPORT_SYMBOL_GPL(sk_set_memalloc);
void sk_clear_memalloc(struct sock *sk)
{
sock_reset_flag(sk, SOCK_MEMALLOC);
sk->sk_allocation &= ~__GFP_MEMALLOC;
static_key_slow_dec(&memalloc_socks);
/*
* SOCK_MEMALLOC is allowed to ignore rmem limits to ensure forward
* progress of swapping. SOCK_MEMALLOC may be cleared while
* it has rmem allocations due to the last swapfile being deactivated
* but there is a risk that the socket is unusable due to exceeding
* the rmem limits. Reclaim the reserves and obey rmem limits again.
*/
sk_mem_reclaim(sk);
}
EXPORT_SYMBOL_GPL(sk_clear_memalloc);
int __sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
{
int ret;
unsigned long pflags = current->flags;
/* these should have been dropped before queueing */
BUG_ON(!sock_flag(sk, SOCK_MEMALLOC));
current->flags |= PF_MEMALLOC;
ret = sk->sk_backlog_rcv(sk, skb);
tsk_restore_flags(current, pflags, PF_MEMALLOC);
return ret;
}
EXPORT_SYMBOL(__sk_backlog_rcv);
static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen)
{
struct timeval tv;
if (optlen < sizeof(tv))
return -EINVAL;
if (copy_from_user(&tv, optval, sizeof(tv)))
return -EFAULT;
if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
return -EDOM;
if (tv.tv_sec < 0) {
static int warned __read_mostly;
*timeo_p = 0;
if (warned < 10 && net_ratelimit()) {
warned++;
pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
__func__, current->comm, task_pid_nr(current));
}
return 0;
}
*timeo_p = MAX_SCHEDULE_TIMEOUT;
if (tv.tv_sec == 0 && tv.tv_usec == 0)
return 0;
if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1))
*timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ);
return 0;
}
static void sock_warn_obsolete_bsdism(const char *name)
{
static int warned;
static char warncomm[TASK_COMM_LEN];
if (strcmp(warncomm, current->comm) && warned < 5) {
strcpy(warncomm, current->comm);
pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n",
warncomm, name);
warned++;
}
}
static bool sock_needs_netstamp(const struct sock *sk)
{
switch (sk->sk_family) {
case AF_UNSPEC:
case AF_UNIX:
return false;
default:
return true;
}
}
static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
{
if (sk->sk_flags & flags) {
sk->sk_flags &= ~flags;
if (sock_needs_netstamp(sk) &&
!(sk->sk_flags & SK_FLAGS_TIMESTAMP))
net_disable_timestamp();
}
}
int __sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
unsigned long flags;
struct sk_buff_head *list = &sk->sk_receive_queue;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
atomic_inc(&sk->sk_drops);
trace_sock_rcvqueue_full(sk, skb);
return -ENOMEM;
}
if (!sk_rmem_schedule(sk, skb, skb->truesize)) {
atomic_inc(&sk->sk_drops);
return -ENOBUFS;
}
skb->dev = NULL;
skb_set_owner_r(skb, sk);
/* we escape from rcu protected region, make sure we dont leak
* a norefcounted dst
*/
skb_dst_force(skb);
spin_lock_irqsave(&list->lock, flags);
sock_skb_set_dropcount(sk, skb);
__skb_queue_tail(list, skb);
spin_unlock_irqrestore(&list->lock, flags);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk);
return 0;
}
EXPORT_SYMBOL(__sock_queue_rcv_skb);
int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int err;
err = sk_filter(sk, skb);
if (err)
return err;
return __sock_queue_rcv_skb(sk, skb);
}
EXPORT_SYMBOL(sock_queue_rcv_skb);
int __sk_receive_skb(struct sock *sk, struct sk_buff *skb,
const int nested, unsigned int trim_cap, bool refcounted)
{
int rc = NET_RX_SUCCESS;
if (sk_filter_trim_cap(sk, skb, trim_cap))
goto discard_and_relse;
skb->dev = NULL;
if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) {
atomic_inc(&sk->sk_drops);
goto discard_and_relse;
}
if (nested)
bh_lock_sock_nested(sk);
else
bh_lock_sock(sk);
if (!sock_owned_by_user(sk)) {
/*
* trylock + unlock semantics:
*/
mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
rc = sk_backlog_rcv(sk, skb);
mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
} else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
bh_unlock_sock(sk);
atomic_inc(&sk->sk_drops);
goto discard_and_relse;
}
bh_unlock_sock(sk);
out:
if (refcounted)
sock_put(sk);
return rc;
discard_and_relse:
kfree_skb(skb);
goto out;
}
EXPORT_SYMBOL(__sk_receive_skb);
struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = __sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_tx_queue_clear(sk);
RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
dst_release(dst);
return NULL;
}
return dst;
}
EXPORT_SYMBOL(__sk_dst_check);
struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_dst_reset(sk);
dst_release(dst);
return NULL;
}
return dst;
}
EXPORT_SYMBOL(sk_dst_check);
static int sock_setbindtodevice(struct sock *sk, char __user *optval,
int optlen)
{
int ret = -ENOPROTOOPT;
#ifdef CONFIG_NETDEVICES
struct net *net = sock_net(sk);
char devname[IFNAMSIZ];
int index;
/* Sorry... */
ret = -EPERM;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
goto out;
ret = -EINVAL;
if (optlen < 0)
goto out;
/* Bind this socket to a particular device like "eth0",
* as specified in the passed interface name. If the
* name is "" or the option length is zero the socket
* is not bound.
*/
if (optlen > IFNAMSIZ - 1)
optlen = IFNAMSIZ - 1;
memset(devname, 0, sizeof(devname));
ret = -EFAULT;
if (copy_from_user(devname, optval, optlen))
goto out;
index = 0;
if (devname[0] != '\0') {
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, devname);
if (dev)
index = dev->ifindex;
rcu_read_unlock();
ret = -ENODEV;
if (!dev)
goto out;
}
lock_sock(sk);
sk->sk_bound_dev_if = index;
sk_dst_reset(sk);
release_sock(sk);
ret = 0;
out:
#endif
return ret;
}
static int sock_getbindtodevice(struct sock *sk, char __user *optval,
int __user *optlen, int len)
{
int ret = -ENOPROTOOPT;
#ifdef CONFIG_NETDEVICES
struct net *net = sock_net(sk);
char devname[IFNAMSIZ];
if (sk->sk_bound_dev_if == 0) {
len = 0;
goto zero;
}
ret = -EINVAL;
if (len < IFNAMSIZ)
goto out;
ret = netdev_get_name(net, devname, sk->sk_bound_dev_if);
if (ret)
goto out;
len = strlen(devname) + 1;
ret = -EFAULT;
if (copy_to_user(optval, devname, len))
goto out;
zero:
ret = -EFAULT;
if (put_user(len, optlen))
goto out;
ret = 0;
out:
#endif
return ret;
}
static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool)
{
if (valbool)
sock_set_flag(sk, bit);
else
sock_reset_flag(sk, bit);
}
bool sk_mc_loop(struct sock *sk)
{
if (dev_recursion_level())
return false;
if (!sk)
return true;
switch (sk->sk_family) {
case AF_INET:
return inet_sk(sk)->mc_loop;
#if IS_ENABLED(CONFIG_IPV6)
case AF_INET6:
return inet6_sk(sk)->mc_loop;
#endif
}
WARN_ON(1);
return true;
}
EXPORT_SYMBOL(sk_mc_loop);
/*
* This is meant for all protocols to use and covers goings on
* at the socket level. Everything here is generic.
*/
int sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int val;
int valbool;
struct linger ling;
int ret = 0;
/*
* Options without arguments
*/
if (optname == SO_BINDTODEVICE)
return sock_setbindtodevice(sk, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
valbool = val ? 1 : 0;
lock_sock(sk);
switch (optname) {
case SO_DEBUG:
if (val && !capable(CAP_NET_ADMIN))
ret = -EACCES;
else
sock_valbool_flag(sk, SOCK_DBG, valbool);
break;
case SO_REUSEADDR:
sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
break;
case SO_REUSEPORT:
sk->sk_reuseport = valbool;
break;
case SO_TYPE:
case SO_PROTOCOL:
case SO_DOMAIN:
case SO_ERROR:
ret = -ENOPROTOOPT;
break;
case SO_DONTROUTE:
sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
break;
case SO_BROADCAST:
sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
break;
case SO_SNDBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_wmem_max);
set_sndbuf:
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = max_t(int, val * 2, SOCK_MIN_SNDBUF);
/* Wake up sending tasks if we upped the value. */
sk->sk_write_space(sk);
break;
case SO_SNDBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_sndbuf;
case SO_RCVBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_rmem_max);
set_rcvbuf:
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
/*
* We double it on the way in to account for
* "struct sk_buff" etc. overhead. Applications
* assume that the SO_RCVBUF setting they make will
* allow that much actual data to be received on that
* socket.
*
* Applications are unaware that "struct sk_buff" and
* other overheads allocate from the receive buffer
* during socket buffer allocation.
*
* And after considering the possible alternatives,
* returning the value we actually used in getsockopt
* is the most desirable behavior.
*/
sk->sk_rcvbuf = max_t(int, val * 2, SOCK_MIN_RCVBUF);
break;
case SO_RCVBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_rcvbuf;
case SO_KEEPALIVE:
#ifdef CONFIG_INET
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM)
tcp_set_keepalive(sk, valbool);
#endif
sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
break;
case SO_OOBINLINE:
sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
break;
case SO_NO_CHECK:
sk->sk_no_check_tx = valbool;
break;
case SO_PRIORITY:
if ((val >= 0 && val <= 6) ||
ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
sk->sk_priority = val;
else
ret = -EPERM;
break;
case SO_LINGER:
if (optlen < sizeof(ling)) {
ret = -EINVAL; /* 1003.1g */
break;
}
if (copy_from_user(&ling, optval, sizeof(ling))) {
ret = -EFAULT;
break;
}
if (!ling.l_onoff)
sock_reset_flag(sk, SOCK_LINGER);
else {
#if (BITS_PER_LONG == 32)
if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
else
#endif
sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
sock_set_flag(sk, SOCK_LINGER);
}
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("setsockopt");
break;
case SO_PASSCRED:
if (valbool)
set_bit(SOCK_PASSCRED, &sock->flags);
else
clear_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_TIMESTAMP:
case SO_TIMESTAMPNS:
if (valbool) {
if (optname == SO_TIMESTAMP)
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
else
sock_set_flag(sk, SOCK_RCVTSTAMPNS);
sock_set_flag(sk, SOCK_RCVTSTAMP);
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
} else {
sock_reset_flag(sk, SOCK_RCVTSTAMP);
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
}
break;
case SO_TIMESTAMPING:
if (val & ~SOF_TIMESTAMPING_MASK) {
ret = -EINVAL;
break;
}
if (val & SOF_TIMESTAMPING_OPT_ID &&
!(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID)) {
if (sk->sk_protocol == IPPROTO_TCP &&
sk->sk_type == SOCK_STREAM) {
if ((1 << sk->sk_state) &
(TCPF_CLOSE | TCPF_LISTEN)) {
ret = -EINVAL;
break;
}
sk->sk_tskey = tcp_sk(sk)->snd_una;
} else {
sk->sk_tskey = 0;
}
}
if (val & SOF_TIMESTAMPING_OPT_STATS &&
!(val & SOF_TIMESTAMPING_OPT_TSONLY)) {
ret = -EINVAL;
break;
}
sk->sk_tsflags = val;
if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
sock_enable_timestamp(sk,
SOCK_TIMESTAMPING_RX_SOFTWARE);
else
sock_disable_timestamp(sk,
(1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
break;
case SO_RCVLOWAT:
if (val < 0)
val = INT_MAX;
sk->sk_rcvlowat = val ? : 1;
break;
case SO_RCVTIMEO:
ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
break;
case SO_SNDTIMEO:
ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
break;
case SO_ATTACH_FILTER:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, sk);
}
break;
case SO_ATTACH_BPF:
ret = -EINVAL;
if (optlen == sizeof(u32)) {
u32 ufd;
ret = -EFAULT;
if (copy_from_user(&ufd, optval, sizeof(ufd)))
break;
ret = sk_attach_bpf(ufd, sk);
}
break;
case SO_ATTACH_REUSEPORT_CBPF:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_reuseport_attach_filter(&fprog, sk);
}
break;
case SO_ATTACH_REUSEPORT_EBPF:
ret = -EINVAL;
if (optlen == sizeof(u32)) {
u32 ufd;
ret = -EFAULT;
if (copy_from_user(&ufd, optval, sizeof(ufd)))
break;
ret = sk_reuseport_attach_bpf(ufd, sk);
}
break;
case SO_DETACH_FILTER:
ret = sk_detach_filter(sk);
break;
case SO_LOCK_FILTER:
if (sock_flag(sk, SOCK_FILTER_LOCKED) && !valbool)
ret = -EPERM;
else
sock_valbool_flag(sk, SOCK_FILTER_LOCKED, valbool);
break;
case SO_PASSSEC:
if (valbool)
set_bit(SOCK_PASSSEC, &sock->flags);
else
clear_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_MARK:
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
ret = -EPERM;
else
sk->sk_mark = val;
break;
case SO_RXQ_OVFL:
sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
break;
case SO_WIFI_STATUS:
sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
break;
case SO_PEEK_OFF:
if (sock->ops->set_peek_off)
ret = sock->ops->set_peek_off(sk, val);
else
ret = -EOPNOTSUPP;
break;
case SO_NOFCS:
sock_valbool_flag(sk, SOCK_NOFCS, valbool);
break;
case SO_SELECT_ERR_QUEUE:
sock_valbool_flag(sk, SOCK_SELECT_ERR_QUEUE, valbool);
break;
#ifdef CONFIG_NET_RX_BUSY_POLL
case SO_BUSY_POLL:
/* allow unprivileged users to decrease the value */
if ((val > sk->sk_ll_usec) && !capable(CAP_NET_ADMIN))
ret = -EPERM;
else {
if (val < 0)
ret = -EINVAL;
else
sk->sk_ll_usec = val;
}
break;
#endif
case SO_MAX_PACING_RATE:
sk->sk_max_pacing_rate = val;
sk->sk_pacing_rate = min(sk->sk_pacing_rate,
sk->sk_max_pacing_rate);
break;
case SO_INCOMING_CPU:
sk->sk_incoming_cpu = val;
break;
case SO_CNX_ADVICE:
if (val == 1)
dst_negative_advice(sk);
break;
default:
ret = -ENOPROTOOPT;
break;
}
release_sock(sk);
return ret;
}
EXPORT_SYMBOL(sock_setsockopt);
static void cred_to_ucred(struct pid *pid, const struct cred *cred,
struct ucred *ucred)
{
ucred->pid = pid_vnr(pid);
ucred->uid = ucred->gid = -1;
if (cred) {
struct user_namespace *current_ns = current_user_ns();
ucred->uid = from_kuid_munged(current_ns, cred->euid);
ucred->gid = from_kgid_munged(current_ns, cred->egid);
}
}
int sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
union {
int val;
struct linger ling;
struct timeval tm;
} v;
int lv = sizeof(int);
int len;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
memset(&v, 0, sizeof(v));
switch (optname) {
case SO_DEBUG:
v.val = sock_flag(sk, SOCK_DBG);
break;
case SO_DONTROUTE:
v.val = sock_flag(sk, SOCK_LOCALROUTE);
break;
case SO_BROADCAST:
v.val = sock_flag(sk, SOCK_BROADCAST);
break;
case SO_SNDBUF:
v.val = sk->sk_sndbuf;
break;
case SO_RCVBUF:
v.val = sk->sk_rcvbuf;
break;
case SO_REUSEADDR:
v.val = sk->sk_reuse;
break;
case SO_REUSEPORT:
v.val = sk->sk_reuseport;
break;
case SO_KEEPALIVE:
v.val = sock_flag(sk, SOCK_KEEPOPEN);
break;
case SO_TYPE:
v.val = sk->sk_type;
break;
case SO_PROTOCOL:
v.val = sk->sk_protocol;
break;
case SO_DOMAIN:
v.val = sk->sk_family;
break;
case SO_ERROR:
v.val = -sock_error(sk);
if (v.val == 0)
v.val = xchg(&sk->sk_err_soft, 0);
break;
case SO_OOBINLINE:
v.val = sock_flag(sk, SOCK_URGINLINE);
break;
case SO_NO_CHECK:
v.val = sk->sk_no_check_tx;
break;
case SO_PRIORITY:
v.val = sk->sk_priority;
break;
case SO_LINGER:
lv = sizeof(v.ling);
v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
v.ling.l_linger = sk->sk_lingertime / HZ;
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("getsockopt");
break;
case SO_TIMESTAMP:
v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
!sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPNS:
v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPING:
v.val = sk->sk_tsflags;
break;
case SO_RCVTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_SNDTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_sndtimeo / HZ;
v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_RCVLOWAT:
v.val = sk->sk_rcvlowat;
break;
case SO_SNDLOWAT:
v.val = 1;
break;
case SO_PASSCRED:
v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_PEERCRED:
{
struct ucred peercred;
if (len > sizeof(peercred))
len = sizeof(peercred);
cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
if (copy_to_user(optval, &peercred, len))
return -EFAULT;
goto lenout;
}
case SO_PEERNAME:
{
char address[128];
if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))
return -ENOTCONN;
if (lv < len)
return -EINVAL;
if (copy_to_user(optval, address, len))
return -EFAULT;
goto lenout;
}
/* Dubious BSD thing... Probably nobody even uses it, but
* the UNIX standard wants it for whatever reason... -DaveM
*/
case SO_ACCEPTCONN:
v.val = sk->sk_state == TCP_LISTEN;
break;
case SO_PASSSEC:
v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_PEERSEC:
return security_socket_getpeersec_stream(sock, optval, optlen, len);
case SO_MARK:
v.val = sk->sk_mark;
break;
case SO_RXQ_OVFL:
v.val = sock_flag(sk, SOCK_RXQ_OVFL);
break;
case SO_WIFI_STATUS:
v.val = sock_flag(sk, SOCK_WIFI_STATUS);
break;
case SO_PEEK_OFF:
if (!sock->ops->set_peek_off)
return -EOPNOTSUPP;
v.val = sk->sk_peek_off;
break;
case SO_NOFCS:
v.val = sock_flag(sk, SOCK_NOFCS);
break;
case SO_BINDTODEVICE:
return sock_getbindtodevice(sk, optval, optlen, len);
case SO_GET_FILTER:
len = sk_get_filter(sk, (struct sock_filter __user *)optval, len);
if (len < 0)
return len;
goto lenout;
case SO_LOCK_FILTER:
v.val = sock_flag(sk, SOCK_FILTER_LOCKED);
break;
case SO_BPF_EXTENSIONS:
v.val = bpf_tell_extensions();
break;
case SO_SELECT_ERR_QUEUE:
v.val = sock_flag(sk, SOCK_SELECT_ERR_QUEUE);
break;
#ifdef CONFIG_NET_RX_BUSY_POLL
case SO_BUSY_POLL:
v.val = sk->sk_ll_usec;
break;
#endif
case SO_MAX_PACING_RATE:
v.val = sk->sk_max_pacing_rate;
break;
case SO_INCOMING_CPU:
v.val = sk->sk_incoming_cpu;
break;
default:
/* We implement the SO_SNDLOWAT etc to not be settable
* (1003.1g 7).
*/
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (copy_to_user(optval, &v, len))
return -EFAULT;
lenout:
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/*
* Initialize an sk_lock.
*
* (We also register the sk_lock with the lock validator.)
*/
static inline void sock_lock_init(struct sock *sk)
{
sock_lock_init_class_and_name(sk,
af_family_slock_key_strings[sk->sk_family],
af_family_slock_keys + sk->sk_family,
af_family_key_strings[sk->sk_family],
af_family_keys + sk->sk_family);
}
/*
* Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
* even temporarly, because of RCU lookups. sk_node should also be left as is.
* We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
*/
static void sock_copy(struct sock *nsk, const struct sock *osk)
{
#ifdef CONFIG_SECURITY_NETWORK
void *sptr = nsk->sk_security;
#endif
memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
#ifdef CONFIG_SECURITY_NETWORK
nsk->sk_security = sptr;
security_sk_clone(osk, nsk);
#endif
}
static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
int family)
{
struct sock *sk;
struct kmem_cache *slab;
slab = prot->slab;
if (slab != NULL) {
sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
if (!sk)
return sk;
if (priority & __GFP_ZERO)
sk_prot_clear_nulls(sk, prot->obj_size);
} else
sk = kmalloc(prot->obj_size, priority);
if (sk != NULL) {
kmemcheck_annotate_bitfield(sk, flags);
if (security_sk_alloc(sk, family, priority))
goto out_free;
if (!try_module_get(prot->owner))
goto out_free_sec;
sk_tx_queue_clear(sk);
}
return sk;
out_free_sec:
security_sk_free(sk);
out_free:
if (slab != NULL)
kmem_cache_free(slab, sk);
else
kfree(sk);
return NULL;
}
static void sk_prot_free(struct proto *prot, struct sock *sk)
{
struct kmem_cache *slab;
struct module *owner;
owner = prot->owner;
slab = prot->slab;
cgroup_sk_free(&sk->sk_cgrp_data);
mem_cgroup_sk_free(sk);
security_sk_free(sk);
if (slab != NULL)
kmem_cache_free(slab, sk);
else
kfree(sk);
module_put(owner);
}
/**
* sk_alloc - All socket objects are allocated here
* @net: the applicable net namespace
* @family: protocol family
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
* @prot: struct proto associated with this new sock instance
* @kern: is this to be a kernel socket?
*/
struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
struct proto *prot, int kern)
{
struct sock *sk;
sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
if (sk) {
sk->sk_family = family;
/*
* See comment in struct sock definition to understand
* why we need sk_prot_creator -acme
*/
sk->sk_prot = sk->sk_prot_creator = prot;
sock_lock_init(sk);
sk->sk_net_refcnt = kern ? 0 : 1;
if (likely(sk->sk_net_refcnt))
get_net(net);
sock_net_set(sk, net);
atomic_set(&sk->sk_wmem_alloc, 1);
mem_cgroup_sk_alloc(sk);
cgroup_sk_alloc(&sk->sk_cgrp_data);
sock_update_classid(&sk->sk_cgrp_data);
sock_update_netprioidx(&sk->sk_cgrp_data);
}
return sk;
}
EXPORT_SYMBOL(sk_alloc);
/* Sockets having SOCK_RCU_FREE will call this function after one RCU
* grace period. This is the case for UDP sockets and TCP listeners.
*/
static void __sk_destruct(struct rcu_head *head)
{
struct sock *sk = container_of(head, struct sock, sk_rcu);
struct sk_filter *filter;
if (sk->sk_destruct)
sk->sk_destruct(sk);
filter = rcu_dereference_check(sk->sk_filter,
atomic_read(&sk->sk_wmem_alloc) == 0);
if (filter) {
sk_filter_uncharge(sk, filter);
RCU_INIT_POINTER(sk->sk_filter, NULL);
}
if (rcu_access_pointer(sk->sk_reuseport_cb))
reuseport_detach_sock(sk);
sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
if (atomic_read(&sk->sk_omem_alloc))
pr_debug("%s: optmem leakage (%d bytes) detected\n",
__func__, atomic_read(&sk->sk_omem_alloc));
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
put_pid(sk->sk_peer_pid);
if (likely(sk->sk_net_refcnt))
put_net(sock_net(sk));
sk_prot_free(sk->sk_prot_creator, sk);
}
void sk_destruct(struct sock *sk)
{
if (sock_flag(sk, SOCK_RCU_FREE))
call_rcu(&sk->sk_rcu, __sk_destruct);
else
__sk_destruct(&sk->sk_rcu);
}
static void __sk_free(struct sock *sk)
{
if (unlikely(sock_diag_has_destroy_listeners(sk) && sk->sk_net_refcnt))
sock_diag_broadcast_destroy(sk);
else
sk_destruct(sk);
}
void sk_free(struct sock *sk)
{
/*
* We subtract one from sk_wmem_alloc and can know if
* some packets are still in some tx queue.
* If not null, sock_wfree() will call __sk_free(sk) later
*/
if (atomic_dec_and_test(&sk->sk_wmem_alloc))
__sk_free(sk);
}
EXPORT_SYMBOL(sk_free);
/**
* sk_clone_lock - clone a socket, and lock its clone
* @sk: the socket to clone
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
*
* Caller must unlock socket even in error path (bh_unlock_sock(newsk))
*/
struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
{
struct sock *newsk;
bool is_charged = true;
newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family);
if (newsk != NULL) {
struct sk_filter *filter;
sock_copy(newsk, sk);
/* SANITY */
if (likely(newsk->sk_net_refcnt))
get_net(sock_net(newsk));
sk_node_init(&newsk->sk_node);
sock_lock_init(newsk);
bh_lock_sock(newsk);
newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
newsk->sk_backlog.len = 0;
atomic_set(&newsk->sk_rmem_alloc, 0);
/*
* sk_wmem_alloc set to one (see sk_free() and sock_wfree())
*/
atomic_set(&newsk->sk_wmem_alloc, 1);
atomic_set(&newsk->sk_omem_alloc, 0);
skb_queue_head_init(&newsk->sk_receive_queue);
skb_queue_head_init(&newsk->sk_write_queue);
rwlock_init(&newsk->sk_callback_lock);
lockdep_set_class_and_name(&newsk->sk_callback_lock,
af_callback_keys + newsk->sk_family,
af_family_clock_key_strings[newsk->sk_family]);
newsk->sk_dst_cache = NULL;
newsk->sk_wmem_queued = 0;
newsk->sk_forward_alloc = 0;
atomic_set(&newsk->sk_drops, 0);
newsk->sk_send_head = NULL;
newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
sock_reset_flag(newsk, SOCK_DONE);
skb_queue_head_init(&newsk->sk_error_queue);
filter = rcu_dereference_protected(newsk->sk_filter, 1);
if (filter != NULL)
/* though it's an empty new sock, the charging may fail
* if sysctl_optmem_max was changed between creation of
* original socket and cloning
*/
is_charged = sk_filter_charge(newsk, filter);
if (unlikely(!is_charged || xfrm_sk_clone_policy(newsk, sk))) {
/* It is still raw copy of parent, so invalidate
* destructor and make plain sk_free() */
newsk->sk_destruct = NULL;
bh_unlock_sock(newsk);
sk_free(newsk);
newsk = NULL;
goto out;
}
RCU_INIT_POINTER(newsk->sk_reuseport_cb, NULL);
newsk->sk_err = 0;
newsk->sk_err_soft = 0;
newsk->sk_priority = 0;
newsk->sk_incoming_cpu = raw_smp_processor_id();
atomic64_set(&newsk->sk_cookie, 0);
mem_cgroup_sk_alloc(newsk);
cgroup_sk_alloc(&newsk->sk_cgrp_data);
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&newsk->sk_refcnt, 2);
/*
* Increment the counter in the same struct proto as the master
* sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
* is the same as sk->sk_prot->socks, as this field was copied
* with memcpy).
*
* This _changes_ the previous behaviour, where
* tcp_create_openreq_child always was incrementing the
* equivalent to tcp_prot->socks (inet_sock_nr), so this have
* to be taken into account in all callers. -acme
*/
sk_refcnt_debug_inc(newsk);
sk_set_socket(newsk, NULL);
newsk->sk_wq = NULL;
if (newsk->sk_prot->sockets_allocated)
sk_sockets_allocated_inc(newsk);
if (sock_needs_netstamp(sk) &&
newsk->sk_flags & SK_FLAGS_TIMESTAMP)
net_enable_timestamp();
}
out:
return newsk;
}
EXPORT_SYMBOL_GPL(sk_clone_lock);
void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
{
u32 max_segs = 1;
sk_dst_set(sk, dst);
sk->sk_route_caps = dst->dev->features;
if (sk->sk_route_caps & NETIF_F_GSO)
sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
sk->sk_route_caps &= ~sk->sk_route_nocaps;
if (sk_can_gso(sk)) {
if (dst->header_len) {
sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
} else {
sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
sk->sk_gso_max_size = dst->dev->gso_max_size;
max_segs = max_t(u32, dst->dev->gso_max_segs, 1);
}
}
sk->sk_gso_max_segs = max_segs;
}
EXPORT_SYMBOL_GPL(sk_setup_caps);
/*
* Simple resource managers for sockets.
*/
/*
* Write buffer destructor automatically called from kfree_skb.
*/
void sock_wfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
unsigned int len = skb->truesize;
if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
/*
* Keep a reference on sk_wmem_alloc, this will be released
* after sk_write_space() call
*/
atomic_sub(len - 1, &sk->sk_wmem_alloc);
sk->sk_write_space(sk);
len = 1;
}
/*
* if sk_wmem_alloc reaches 0, we must finish what sk_free()
* could not do because of in-flight packets
*/
if (atomic_sub_and_test(len, &sk->sk_wmem_alloc))
__sk_free(sk);
}
EXPORT_SYMBOL(sock_wfree);
/* This variant of sock_wfree() is used by TCP,
* since it sets SOCK_USE_WRITE_QUEUE.
*/
void __sock_wfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
if (atomic_sub_and_test(skb->truesize, &sk->sk_wmem_alloc))
__sk_free(sk);
}
void skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
{
skb_orphan(skb);
skb->sk = sk;
#ifdef CONFIG_INET
if (unlikely(!sk_fullsock(sk))) {
skb->destructor = sock_edemux;
sock_hold(sk);
return;
}
#endif
skb->destructor = sock_wfree;
skb_set_hash_from_sk(skb, sk);
/*
* We used to take a refcount on sk, but following operation
* is enough to guarantee sk_free() wont free this sock until
* all in-flight packets are completed
*/
atomic_add(skb->truesize, &sk->sk_wmem_alloc);
}
EXPORT_SYMBOL(skb_set_owner_w);
/* This helper is used by netem, as it can hold packets in its
* delay queue. We want to allow the owner socket to send more
* packets, as if they were already TX completed by a typical driver.
* But we also want to keep skb->sk set because some packet schedulers
* rely on it (sch_fq for example). So we set skb->truesize to a small
* amount (1) and decrease sk_wmem_alloc accordingly.
*/
void skb_orphan_partial(struct sk_buff *skb)
{
/* If this skb is a TCP pure ACK or already went here,
* we have nothing to do. 2 is already a very small truesize.
*/
if (skb->truesize <= 2)
return;
/* TCP stack sets skb->ooo_okay based on sk_wmem_alloc,
* so we do not completely orphan skb, but transfert all
* accounted bytes but one, to avoid unexpected reorders.
*/
if (skb->destructor == sock_wfree
#ifdef CONFIG_INET
|| skb->destructor == tcp_wfree
#endif
) {
atomic_sub(skb->truesize - 1, &skb->sk->sk_wmem_alloc);
skb->truesize = 1;
} else {
skb_orphan(skb);
}
}
EXPORT_SYMBOL(skb_orphan_partial);
/*
* Read buffer destructor automatically called from kfree_skb.
*/
void sock_rfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
unsigned int len = skb->truesize;
atomic_sub(len, &sk->sk_rmem_alloc);
sk_mem_uncharge(sk, len);
}
EXPORT_SYMBOL(sock_rfree);
/*
* Buffer destructor for skbs that are not used directly in read or write
* path, e.g. for error handler skbs. Automatically called from kfree_skb.
*/
void sock_efree(struct sk_buff *skb)
{
sock_put(skb->sk);
}
EXPORT_SYMBOL(sock_efree);
kuid_t sock_i_uid(struct sock *sk)
{
kuid_t uid;
read_lock_bh(&sk->sk_callback_lock);
uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : GLOBAL_ROOT_UID;
read_unlock_bh(&sk->sk_callback_lock);
return uid;
}
EXPORT_SYMBOL(sock_i_uid);
unsigned long sock_i_ino(struct sock *sk)
{
unsigned long ino;
read_lock_bh(&sk->sk_callback_lock);
ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
read_unlock_bh(&sk->sk_callback_lock);
return ino;
}
EXPORT_SYMBOL(sock_i_ino);
/*
* Allocate a skb from the socket's send buffer.
*/
struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
gfp_t priority)
{
if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
struct sk_buff *skb = alloc_skb(size, priority);
if (skb) {
skb_set_owner_w(skb, sk);
return skb;
}
}
return NULL;
}
EXPORT_SYMBOL(sock_wmalloc);
/*
* Allocate a memory block from the socket's option memory buffer.
*/
void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
{
if ((unsigned int)size <= sysctl_optmem_max &&
atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) {
void *mem;
/* First do the add, to avoid the race if kmalloc
* might sleep.
*/
atomic_add(size, &sk->sk_omem_alloc);
mem = kmalloc(size, priority);
if (mem)
return mem;
atomic_sub(size, &sk->sk_omem_alloc);
}
return NULL;
}
EXPORT_SYMBOL(sock_kmalloc);
/* Free an option memory block. Note, we actually want the inline
* here as this allows gcc to detect the nullify and fold away the
* condition entirely.
*/
static inline void __sock_kfree_s(struct sock *sk, void *mem, int size,
const bool nullify)
{
if (WARN_ON_ONCE(!mem))
return;
if (nullify)
kzfree(mem);
else
kfree(mem);
atomic_sub(size, &sk->sk_omem_alloc);
}
void sock_kfree_s(struct sock *sk, void *mem, int size)
{
__sock_kfree_s(sk, mem, size, false);
}
EXPORT_SYMBOL(sock_kfree_s);
void sock_kzfree_s(struct sock *sk, void *mem, int size)
{
__sock_kfree_s(sk, mem, size, true);
}
EXPORT_SYMBOL(sock_kzfree_s);
/* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
I think, these locks should be removed for datagram sockets.
*/
static long sock_wait_for_wmem(struct sock *sk, long timeo)
{
DEFINE_WAIT(wait);
sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk);
for (;;) {
if (!timeo)
break;
if (signal_pending(current))
break;
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf)
break;
if (sk->sk_shutdown & SEND_SHUTDOWN)
break;
if (sk->sk_err)
break;
timeo = schedule_timeout(timeo);
}
finish_wait(sk_sleep(sk), &wait);
return timeo;
}
/*
* Generic send/receive buffer handlers
*/
struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
unsigned long data_len, int noblock,
int *errcode, int max_page_order)
{
struct sk_buff *skb;
long timeo;
int err;
timeo = sock_sndtimeo(sk, noblock);
for (;;) {
err = sock_error(sk);
if (err != 0)
goto failure;
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto failure;
if (sk_wmem_alloc_get(sk) < sk->sk_sndbuf)
break;
sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}
skb = alloc_skb_with_frags(header_len, data_len, max_page_order,
errcode, sk->sk_allocation);
if (skb)
skb_set_owner_w(skb, sk);
return skb;
interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
EXPORT_SYMBOL(sock_alloc_send_pskb);
struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
int noblock, int *errcode)
{
return sock_alloc_send_pskb(sk, size, 0, noblock, errcode, 0);
}
EXPORT_SYMBOL(sock_alloc_send_skb);
int __sock_cmsg_send(struct sock *sk, struct msghdr *msg, struct cmsghdr *cmsg,
struct sockcm_cookie *sockc)
{
u32 tsflags;
switch (cmsg->cmsg_type) {
case SO_MARK:
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
return -EINVAL;
sockc->mark = *(u32 *)CMSG_DATA(cmsg);
break;
case SO_TIMESTAMPING:
if (cmsg->cmsg_len != CMSG_LEN(sizeof(u32)))
return -EINVAL;
tsflags = *(u32 *)CMSG_DATA(cmsg);
if (tsflags & ~SOF_TIMESTAMPING_TX_RECORD_MASK)
return -EINVAL;
sockc->tsflags &= ~SOF_TIMESTAMPING_TX_RECORD_MASK;
sockc->tsflags |= tsflags;
break;
/* SCM_RIGHTS and SCM_CREDENTIALS are semantically in SOL_UNIX. */
case SCM_RIGHTS:
case SCM_CREDENTIALS:
break;
default:
return -EINVAL;
}
return 0;
}
EXPORT_SYMBOL(__sock_cmsg_send);
int sock_cmsg_send(struct sock *sk, struct msghdr *msg,
struct sockcm_cookie *sockc)
{
struct cmsghdr *cmsg;
int ret;
for_each_cmsghdr(cmsg, msg) {
if (!CMSG_OK(msg, cmsg))
return -EINVAL;
if (cmsg->cmsg_level != SOL_SOCKET)
continue;
ret = __sock_cmsg_send(sk, msg, cmsg, sockc);
if (ret)
return ret;
}
return 0;
}
EXPORT_SYMBOL(sock_cmsg_send);
/* On 32bit arches, an skb frag is limited to 2^15 */
#define SKB_FRAG_PAGE_ORDER get_order(32768)
/**
* skb_page_frag_refill - check that a page_frag contains enough room
* @sz: minimum size of the fragment we want to get
* @pfrag: pointer to page_frag
* @gfp: priority for memory allocation
*
* Note: While this allocator tries to use high order pages, there is
* no guarantee that allocations succeed. Therefore, @sz MUST be
* less or equal than PAGE_SIZE.
*/
bool skb_page_frag_refill(unsigned int sz, struct page_frag *pfrag, gfp_t gfp)
{
if (pfrag->page) {
if (page_ref_count(pfrag->page) == 1) {
pfrag->offset = 0;
return true;
}
if (pfrag->offset + sz <= pfrag->size)
return true;
put_page(pfrag->page);
}
pfrag->offset = 0;
if (SKB_FRAG_PAGE_ORDER) {
/* Avoid direct reclaim but allow kswapd to wake */
pfrag->page = alloc_pages((gfp & ~__GFP_DIRECT_RECLAIM) |
__GFP_COMP | __GFP_NOWARN |
__GFP_NORETRY,
SKB_FRAG_PAGE_ORDER);
if (likely(pfrag->page)) {
pfrag->size = PAGE_SIZE << SKB_FRAG_PAGE_ORDER;
return true;
}
}
pfrag->page = alloc_page(gfp);
if (likely(pfrag->page)) {
pfrag->size = PAGE_SIZE;
return true;
}
return false;
}
EXPORT_SYMBOL(skb_page_frag_refill);
bool sk_page_frag_refill(struct sock *sk, struct page_frag *pfrag)
{
if (likely(skb_page_frag_refill(32U, pfrag, sk->sk_allocation)))
return true;
sk_enter_memory_pressure(sk);
sk_stream_moderate_sndbuf(sk);
return false;
}
EXPORT_SYMBOL(sk_page_frag_refill);
static void __lock_sock(struct sock *sk)
__releases(&sk->sk_lock.slock)
__acquires(&sk->sk_lock.slock)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
TASK_UNINTERRUPTIBLE);
spin_unlock_bh(&sk->sk_lock.slock);
schedule();
spin_lock_bh(&sk->sk_lock.slock);
if (!sock_owned_by_user(sk))
break;
}
finish_wait(&sk->sk_lock.wq, &wait);
}
static void __release_sock(struct sock *sk)
__releases(&sk->sk_lock.slock)
__acquires(&sk->sk_lock.slock)
{
struct sk_buff *skb, *next;
while ((skb = sk->sk_backlog.head) != NULL) {
sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
spin_unlock_bh(&sk->sk_lock.slock);
do {
next = skb->next;
prefetch(next);
WARN_ON_ONCE(skb_dst_is_noref(skb));
skb->next = NULL;
sk_backlog_rcv(sk, skb);
cond_resched();
skb = next;
} while (skb != NULL);
spin_lock_bh(&sk->sk_lock.slock);
}
/*
* Doing the zeroing here guarantee we can not loop forever
* while a wild producer attempts to flood us.
*/
sk->sk_backlog.len = 0;
}
void __sk_flush_backlog(struct sock *sk)
{
spin_lock_bh(&sk->sk_lock.slock);
__release_sock(sk);
spin_unlock_bh(&sk->sk_lock.slock);
}
/**
* sk_wait_data - wait for data to arrive at sk_receive_queue
* @sk: sock to wait on
* @timeo: for how long
* @skb: last skb seen on sk_receive_queue
*
* Now socket state including sk->sk_err is changed only under lock,
* hence we may omit checks after joining wait queue.
* We check receive queue before schedule() only as optimization;
* it is very likely that release_sock() added new data.
*/
int sk_wait_data(struct sock *sk, long *timeo, const struct sk_buff *skb)
{
DEFINE_WAIT_FUNC(wait, woken_wake_function);
int rc;
add_wait_queue(sk_sleep(sk), &wait);
sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
rc = sk_wait_event(sk, timeo, skb_peek_tail(&sk->sk_receive_queue) != skb, &wait);
sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
remove_wait_queue(sk_sleep(sk), &wait);
return rc;
}
EXPORT_SYMBOL(sk_wait_data);
/**
* __sk_mem_raise_allocated - increase memory_allocated
* @sk: socket
* @size: memory size to allocate
* @amt: pages to allocate
* @kind: allocation type
*
* Similar to __sk_mem_schedule(), but does not update sk_forward_alloc
*/
int __sk_mem_raise_allocated(struct sock *sk, int size, int amt, int kind)
{
struct proto *prot = sk->sk_prot;
long allocated = sk_memory_allocated_add(sk, amt);
if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
!mem_cgroup_charge_skmem(sk->sk_memcg, amt))
goto suppress_allocation;
/* Under limit. */
if (allocated <= sk_prot_mem_limits(sk, 0)) {
sk_leave_memory_pressure(sk);
return 1;
}
/* Under pressure. */
if (allocated > sk_prot_mem_limits(sk, 1))
sk_enter_memory_pressure(sk);
/* Over hard limit. */
if (allocated > sk_prot_mem_limits(sk, 2))
goto suppress_allocation;
/* guarantee minimum buffer size under pressure */
if (kind == SK_MEM_RECV) {
if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0])
return 1;
} else { /* SK_MEM_SEND */
if (sk->sk_type == SOCK_STREAM) {
if (sk->sk_wmem_queued < prot->sysctl_wmem[0])
return 1;
} else if (atomic_read(&sk->sk_wmem_alloc) <
prot->sysctl_wmem[0])
return 1;
}
if (sk_has_memory_pressure(sk)) {
int alloc;
if (!sk_under_memory_pressure(sk))
return 1;
alloc = sk_sockets_allocated_read_positive(sk);
if (sk_prot_mem_limits(sk, 2) > alloc *
sk_mem_pages(sk->sk_wmem_queued +
atomic_read(&sk->sk_rmem_alloc) +
sk->sk_forward_alloc))
return 1;
}
suppress_allocation:
if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
sk_stream_moderate_sndbuf(sk);
/* Fail only if socket is _under_ its sndbuf.
* In this case we cannot block, so that we have to fail.
*/
if (sk->sk_wmem_queued + size >= sk->sk_sndbuf)
return 1;
}
trace_sock_exceed_buf_limit(sk, prot, allocated);
sk_memory_allocated_sub(sk, amt);
if (mem_cgroup_sockets_enabled && sk->sk_memcg)
mem_cgroup_uncharge_skmem(sk->sk_memcg, amt);
return 0;
}
EXPORT_SYMBOL(__sk_mem_raise_allocated);
/**
* __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
* @sk: socket
* @size: memory size to allocate
* @kind: allocation type
*
* If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
* rmem allocation. This function assumes that protocols which have
* memory_pressure use sk_wmem_queued as write buffer accounting.
*/
int __sk_mem_schedule(struct sock *sk, int size, int kind)
{
int ret, amt = sk_mem_pages(size);
sk->sk_forward_alloc += amt << SK_MEM_QUANTUM_SHIFT;
ret = __sk_mem_raise_allocated(sk, size, amt, kind);
if (!ret)
sk->sk_forward_alloc -= amt << SK_MEM_QUANTUM_SHIFT;
return ret;
}
EXPORT_SYMBOL(__sk_mem_schedule);
/**
* __sk_mem_reduce_allocated - reclaim memory_allocated
* @sk: socket
* @amount: number of quanta
*
* Similar to __sk_mem_reclaim(), but does not update sk_forward_alloc
*/
void __sk_mem_reduce_allocated(struct sock *sk, int amount)
{
sk_memory_allocated_sub(sk, amount);
if (mem_cgroup_sockets_enabled && sk->sk_memcg)
mem_cgroup_uncharge_skmem(sk->sk_memcg, amount);
if (sk_under_memory_pressure(sk) &&
(sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
sk_leave_memory_pressure(sk);
}
EXPORT_SYMBOL(__sk_mem_reduce_allocated);
/**
* __sk_mem_reclaim - reclaim sk_forward_alloc and memory_allocated
* @sk: socket
* @amount: number of bytes (rounded down to a SK_MEM_QUANTUM multiple)
*/
void __sk_mem_reclaim(struct sock *sk, int amount)
{
amount >>= SK_MEM_QUANTUM_SHIFT;
sk->sk_forward_alloc -= amount << SK_MEM_QUANTUM_SHIFT;
__sk_mem_reduce_allocated(sk, amount);
}
EXPORT_SYMBOL(__sk_mem_reclaim);
int sk_set_peek_off(struct sock *sk, int val)
{
if (val < 0)
return -EINVAL;
sk->sk_peek_off = val;
return 0;
}
EXPORT_SYMBOL_GPL(sk_set_peek_off);
/*
* Set of default routines for initialising struct proto_ops when
* the protocol does not support a particular function. In certain
* cases where it makes no sense for a protocol to have a "do nothing"
* function, some default processing is provided.
*/
int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_bind);
int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
int len, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_connect);
int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_socketpair);
int sock_no_accept(struct socket *sock, struct socket *newsock, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_accept);
int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
int *len, int peer)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_getname);
unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt)
{
return 0;
}
EXPORT_SYMBOL(sock_no_poll);
int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_ioctl);
int sock_no_listen(struct socket *sock, int backlog)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_listen);
int sock_no_shutdown(struct socket *sock, int how)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_shutdown);
int sock_no_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_setsockopt);
int sock_no_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_getsockopt);
int sock_no_sendmsg(struct socket *sock, struct msghdr *m, size_t len)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_sendmsg);
int sock_no_recvmsg(struct socket *sock, struct msghdr *m, size_t len,
int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_recvmsg);
int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
{
/* Mirror missing mmap method error code */
return -ENODEV;
}
EXPORT_SYMBOL(sock_no_mmap);
ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
{
ssize_t res;
struct msghdr msg = {.msg_flags = flags};
struct kvec iov;
char *kaddr = kmap(page);
iov.iov_base = kaddr + offset;
iov.iov_len = size;
res = kernel_sendmsg(sock, &msg, &iov, 1, size);
kunmap(page);
return res;
}
EXPORT_SYMBOL(sock_no_sendpage);
/*
* Default Socket Callbacks
*/
static void sock_def_wakeup(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (skwq_has_sleeper(wq))
wake_up_interruptible_all(&wq->wait);
rcu_read_unlock();
}
static void sock_def_error_report(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (skwq_has_sleeper(wq))
wake_up_interruptible_poll(&wq->wait, POLLERR);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
rcu_read_unlock();
}
static void sock_def_readable(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (skwq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI |
POLLRDNORM | POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static void sock_def_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
/* Do not wake up a writer until he can make "significant"
* progress. --DaveM
*/
if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) {
wq = rcu_dereference(sk->sk_wq);
if (skwq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLWRNORM | POLLWRBAND);
/* Should agree with poll, otherwise some programs break */
if (sock_writeable(sk))
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
static void sock_def_destruct(struct sock *sk)
{
}
void sk_send_sigurg(struct sock *sk)
{
if (sk->sk_socket && sk->sk_socket->file)
if (send_sigurg(&sk->sk_socket->file->f_owner))
sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
}
EXPORT_SYMBOL(sk_send_sigurg);
void sk_reset_timer(struct sock *sk, struct timer_list* timer,
unsigned long expires)
{
if (!mod_timer(timer, expires))
sock_hold(sk);
}
EXPORT_SYMBOL(sk_reset_timer);
void sk_stop_timer(struct sock *sk, struct timer_list* timer)
{
if (del_timer(timer))
__sock_put(sk);
}
EXPORT_SYMBOL(sk_stop_timer);
void sock_init_data(struct socket *sock, struct sock *sk)
{
skb_queue_head_init(&sk->sk_receive_queue);
skb_queue_head_init(&sk->sk_write_queue);
skb_queue_head_init(&sk->sk_error_queue);
sk->sk_send_head = NULL;
init_timer(&sk->sk_timer);
sk->sk_allocation = GFP_KERNEL;
sk->sk_rcvbuf = sysctl_rmem_default;
sk->sk_sndbuf = sysctl_wmem_default;
sk->sk_state = TCP_CLOSE;
sk_set_socket(sk, sock);
sock_set_flag(sk, SOCK_ZAPPED);
if (sock) {
sk->sk_type = sock->type;
sk->sk_wq = sock->wq;
sock->sk = sk;
sk->sk_uid = SOCK_INODE(sock)->i_uid;
} else {
sk->sk_wq = NULL;
sk->sk_uid = make_kuid(sock_net(sk)->user_ns, 0);
}
rwlock_init(&sk->sk_callback_lock);
lockdep_set_class_and_name(&sk->sk_callback_lock,
af_callback_keys + sk->sk_family,
af_family_clock_key_strings[sk->sk_family]);
sk->sk_state_change = sock_def_wakeup;
sk->sk_data_ready = sock_def_readable;
sk->sk_write_space = sock_def_write_space;
sk->sk_error_report = sock_def_error_report;
sk->sk_destruct = sock_def_destruct;
sk->sk_frag.page = NULL;
sk->sk_frag.offset = 0;
sk->sk_peek_off = -1;
sk->sk_peer_pid = NULL;
sk->sk_peer_cred = NULL;
sk->sk_write_pending = 0;
sk->sk_rcvlowat = 1;
sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
sk->sk_stamp = ktime_set(-1L, 0);
#ifdef CONFIG_NET_RX_BUSY_POLL
sk->sk_napi_id = 0;
sk->sk_ll_usec = sysctl_net_busy_read;
#endif
sk->sk_max_pacing_rate = ~0U;
sk->sk_pacing_rate = ~0U;
sk->sk_incoming_cpu = -1;
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&sk->sk_refcnt, 1);
atomic_set(&sk->sk_drops, 0);
}
EXPORT_SYMBOL(sock_init_data);
void lock_sock_nested(struct sock *sk, int subclass)
{
might_sleep();
spin_lock_bh(&sk->sk_lock.slock);
if (sk->sk_lock.owned)
__lock_sock(sk);
sk->sk_lock.owned = 1;
spin_unlock(&sk->sk_lock.slock);
/*
* The sk_lock has mutex_lock() semantics here:
*/
mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
local_bh_enable();
}
EXPORT_SYMBOL(lock_sock_nested);
void release_sock(struct sock *sk)
{
spin_lock_bh(&sk->sk_lock.slock);
if (sk->sk_backlog.tail)
__release_sock(sk);
/* Warning : release_cb() might need to release sk ownership,
* ie call sock_release_ownership(sk) before us.
*/
if (sk->sk_prot->release_cb)
sk->sk_prot->release_cb(sk);
sock_release_ownership(sk);
if (waitqueue_active(&sk->sk_lock.wq))
wake_up(&sk->sk_lock.wq);
spin_unlock_bh(&sk->sk_lock.slock);
}
EXPORT_SYMBOL(release_sock);
/**
* lock_sock_fast - fast version of lock_sock
* @sk: socket
*
* This version should be used for very small section, where process wont block
* return false if fast path is taken
* sk_lock.slock locked, owned = 0, BH disabled
* return true if slow path is taken
* sk_lock.slock unlocked, owned = 1, BH enabled
*/
bool lock_sock_fast(struct sock *sk)
{
might_sleep();
spin_lock_bh(&sk->sk_lock.slock);
if (!sk->sk_lock.owned)
/*
* Note : We must disable BH
*/
return false;
__lock_sock(sk);
sk->sk_lock.owned = 1;
spin_unlock(&sk->sk_lock.slock);
/*
* The sk_lock has mutex_lock() semantics here:
*/
mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_);
local_bh_enable();
return true;
}
EXPORT_SYMBOL(lock_sock_fast);
int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp)
{
struct timeval tv;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
tv = ktime_to_timeval(sk->sk_stamp);
if (tv.tv_sec == -1)
return -ENOENT;
if (tv.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
tv = ktime_to_timeval(sk->sk_stamp);
}
return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0;
}
EXPORT_SYMBOL(sock_get_timestamp);
int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp)
{
struct timespec ts;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
ts = ktime_to_timespec(sk->sk_stamp);
if (ts.tv_sec == -1)
return -ENOENT;
if (ts.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
ts = ktime_to_timespec(sk->sk_stamp);
}
return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0;
}
EXPORT_SYMBOL(sock_get_timestampns);
void sock_enable_timestamp(struct sock *sk, int flag)
{
if (!sock_flag(sk, flag)) {
unsigned long previous_flags = sk->sk_flags;
sock_set_flag(sk, flag);
/*
* we just set one of the two flags which require net
* time stamping, but time stamping might have been on
* already because of the other one
*/
if (sock_needs_netstamp(sk) &&
!(previous_flags & SK_FLAGS_TIMESTAMP))
net_enable_timestamp();
}
}
int sock_recv_errqueue(struct sock *sk, struct msghdr *msg, int len,
int level, int type)
{
struct sock_exterr_skb *serr;
struct sk_buff *skb;
int copied, err;
err = -EAGAIN;
skb = sock_dequeue_err_skb(sk);
if (skb == NULL)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (err)
goto out_free_skb;
sock_recv_timestamp(msg, sk, skb);
serr = SKB_EXT_ERR(skb);
put_cmsg(msg, level, type, sizeof(serr->ee), &serr->ee);
msg->msg_flags |= MSG_ERRQUEUE;
err = copied;
out_free_skb:
kfree_skb(skb);
out:
return err;
}
EXPORT_SYMBOL(sock_recv_errqueue);
/*
* Get a socket option on an socket.
*
* FIX: POSIX 1003.1g is very ambiguous here. It states that
* asynchronous errors should be reported by getsockopt. We assume
* this means if you specify SO_ERROR (otherwise whats the point of it).
*/
int sock_common_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(sock_common_getsockopt);
#ifdef CONFIG_COMPAT
int compat_sock_common_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
if (sk->sk_prot->compat_getsockopt != NULL)
return sk->sk_prot->compat_getsockopt(sk, level, optname,
optval, optlen);
return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_sock_common_getsockopt);
#endif
int sock_common_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
int addr_len = 0;
int err;
err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
flags & ~MSG_DONTWAIT, &addr_len);
if (err >= 0)
msg->msg_namelen = addr_len;
return err;
}
EXPORT_SYMBOL(sock_common_recvmsg);
/*
* Set socket options on an inet socket.
*/
int sock_common_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(sock_common_setsockopt);
#ifdef CONFIG_COMPAT
int compat_sock_common_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
if (sk->sk_prot->compat_setsockopt != NULL)
return sk->sk_prot->compat_setsockopt(sk, level, optname,
optval, optlen);
return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_sock_common_setsockopt);
#endif
void sk_common_release(struct sock *sk)
{
if (sk->sk_prot->destroy)
sk->sk_prot->destroy(sk);
/*
* Observation: when sock_common_release is called, processes have
* no access to socket. But net still has.
* Step one, detach it from networking:
*
* A. Remove from hash tables.
*/
sk->sk_prot->unhash(sk);
/*
* In this point socket cannot receive new packets, but it is possible
* that some packets are in flight because some CPU runs receiver and
* did hash table lookup before we unhashed socket. They will achieve
* receive queue and will be purged by socket destructor.
*
* Also we still have packets pending on receive queue and probably,
* our own packets waiting in device queues. sock_destroy will drain
* receive queue, but transmitted packets will delay socket destruction
* until the last reference will be released.
*/
sock_orphan(sk);
xfrm_sk_free_policy(sk);
sk_refcnt_debug_release(sk);
if (sk->sk_frag.page) {
put_page(sk->sk_frag.page);
sk->sk_frag.page = NULL;
}
sock_put(sk);
}
EXPORT_SYMBOL(sk_common_release);
#ifdef CONFIG_PROC_FS
#define PROTO_INUSE_NR 64 /* should be enough for the first time */
struct prot_inuse {
int val[PROTO_INUSE_NR];
};
static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
#ifdef CONFIG_NET_NS
void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
{
__this_cpu_add(net->core.inuse->val[prot->inuse_idx], val);
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
int sock_prot_inuse_get(struct net *net, struct proto *prot)
{
int cpu, idx = prot->inuse_idx;
int res = 0;
for_each_possible_cpu(cpu)
res += per_cpu_ptr(net->core.inuse, cpu)->val[idx];
return res >= 0 ? res : 0;
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
static int __net_init sock_inuse_init_net(struct net *net)
{
net->core.inuse = alloc_percpu(struct prot_inuse);
return net->core.inuse ? 0 : -ENOMEM;
}
static void __net_exit sock_inuse_exit_net(struct net *net)
{
free_percpu(net->core.inuse);
}
static struct pernet_operations net_inuse_ops = {
.init = sock_inuse_init_net,
.exit = sock_inuse_exit_net,
};
static __init int net_inuse_init(void)
{
if (register_pernet_subsys(&net_inuse_ops))
panic("Cannot initialize net inuse counters");
return 0;
}
core_initcall(net_inuse_init);
#else
static DEFINE_PER_CPU(struct prot_inuse, prot_inuse);
void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
{
__this_cpu_add(prot_inuse.val[prot->inuse_idx], val);
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
int sock_prot_inuse_get(struct net *net, struct proto *prot)
{
int cpu, idx = prot->inuse_idx;
int res = 0;
for_each_possible_cpu(cpu)
res += per_cpu(prot_inuse, cpu).val[idx];
return res >= 0 ? res : 0;
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
#endif
static void assign_proto_idx(struct proto *prot)
{
prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
pr_err("PROTO_INUSE_NR exhausted\n");
return;
}
set_bit(prot->inuse_idx, proto_inuse_idx);
}
static void release_proto_idx(struct proto *prot)
{
if (prot->inuse_idx != PROTO_INUSE_NR - 1)
clear_bit(prot->inuse_idx, proto_inuse_idx);
}
#else
static inline void assign_proto_idx(struct proto *prot)
{
}
static inline void release_proto_idx(struct proto *prot)
{
}
#endif
static void req_prot_cleanup(struct request_sock_ops *rsk_prot)
{
if (!rsk_prot)
return;
kfree(rsk_prot->slab_name);
rsk_prot->slab_name = NULL;
kmem_cache_destroy(rsk_prot->slab);
rsk_prot->slab = NULL;
}
static int req_prot_init(const struct proto *prot)
{
struct request_sock_ops *rsk_prot = prot->rsk_prot;
if (!rsk_prot)
return 0;
rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s",
prot->name);
if (!rsk_prot->slab_name)
return -ENOMEM;
rsk_prot->slab = kmem_cache_create(rsk_prot->slab_name,
rsk_prot->obj_size, 0,
prot->slab_flags, NULL);
if (!rsk_prot->slab) {
pr_crit("%s: Can't create request sock SLAB cache!\n",
prot->name);
return -ENOMEM;
}
return 0;
}
int proto_register(struct proto *prot, int alloc_slab)
{
if (alloc_slab) {
prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0,
SLAB_HWCACHE_ALIGN | prot->slab_flags,
NULL);
if (prot->slab == NULL) {
pr_crit("%s: Can't create sock SLAB cache!\n",
prot->name);
goto out;
}
if (req_prot_init(prot))
goto out_free_request_sock_slab;
if (prot->twsk_prot != NULL) {
prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name);
if (prot->twsk_prot->twsk_slab_name == NULL)
goto out_free_request_sock_slab;
prot->twsk_prot->twsk_slab =
kmem_cache_create(prot->twsk_prot->twsk_slab_name,
prot->twsk_prot->twsk_obj_size,
0,
prot->slab_flags,
NULL);
if (prot->twsk_prot->twsk_slab == NULL)
goto out_free_timewait_sock_slab_name;
}
}
mutex_lock(&proto_list_mutex);
list_add(&prot->node, &proto_list);
assign_proto_idx(prot);
mutex_unlock(&proto_list_mutex);
return 0;
out_free_timewait_sock_slab_name:
kfree(prot->twsk_prot->twsk_slab_name);
out_free_request_sock_slab:
req_prot_cleanup(prot->rsk_prot);
kmem_cache_destroy(prot->slab);
prot->slab = NULL;
out:
return -ENOBUFS;
}
EXPORT_SYMBOL(proto_register);
void proto_unregister(struct proto *prot)
{
mutex_lock(&proto_list_mutex);
release_proto_idx(prot);
list_del(&prot->node);
mutex_unlock(&proto_list_mutex);
kmem_cache_destroy(prot->slab);
prot->slab = NULL;
req_prot_cleanup(prot->rsk_prot);
if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) {
kmem_cache_destroy(prot->twsk_prot->twsk_slab);
kfree(prot->twsk_prot->twsk_slab_name);
prot->twsk_prot->twsk_slab = NULL;
}
}
EXPORT_SYMBOL(proto_unregister);
#ifdef CONFIG_PROC_FS
static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(proto_list_mutex)
{
mutex_lock(&proto_list_mutex);
return seq_list_start_head(&proto_list, *pos);
}
static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_list_next(v, &proto_list, pos);
}
static void proto_seq_stop(struct seq_file *seq, void *v)
__releases(proto_list_mutex)
{
mutex_unlock(&proto_list_mutex);
}
static char proto_method_implemented(const void *method)
{
return method == NULL ? 'n' : 'y';
}
static long sock_prot_memory_allocated(struct proto *proto)
{
return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
}
static char *sock_prot_memory_pressure(struct proto *proto)
{
return proto->memory_pressure != NULL ?
proto_memory_pressure(proto) ? "yes" : "no" : "NI";
}
static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
{
seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
"%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
proto->name,
proto->obj_size,
sock_prot_inuse_get(seq_file_net(seq), proto),
sock_prot_memory_allocated(proto),
sock_prot_memory_pressure(proto),
proto->max_header,
proto->slab == NULL ? "no" : "yes",
module_name(proto->owner),
proto_method_implemented(proto->close),
proto_method_implemented(proto->connect),
proto_method_implemented(proto->disconnect),
proto_method_implemented(proto->accept),
proto_method_implemented(proto->ioctl),
proto_method_implemented(proto->init),
proto_method_implemented(proto->destroy),
proto_method_implemented(proto->shutdown),
proto_method_implemented(proto->setsockopt),
proto_method_implemented(proto->getsockopt),
proto_method_implemented(proto->sendmsg),
proto_method_implemented(proto->recvmsg),
proto_method_implemented(proto->sendpage),
proto_method_implemented(proto->bind),
proto_method_implemented(proto->backlog_rcv),
proto_method_implemented(proto->hash),
proto_method_implemented(proto->unhash),
proto_method_implemented(proto->get_port),
proto_method_implemented(proto->enter_memory_pressure));
}
static int proto_seq_show(struct seq_file *seq, void *v)
{
if (v == &proto_list)
seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
"protocol",
"size",
"sockets",
"memory",
"press",
"maxhdr",
"slab",
"module",
"cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
else
proto_seq_printf(seq, list_entry(v, struct proto, node));
return 0;
}
static const struct seq_operations proto_seq_ops = {
.start = proto_seq_start,
.next = proto_seq_next,
.stop = proto_seq_stop,
.show = proto_seq_show,
};
static int proto_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &proto_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations proto_seq_fops = {
.owner = THIS_MODULE,
.open = proto_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static __net_init int proto_init_net(struct net *net)
{
if (!proc_create("protocols", S_IRUGO, net->proc_net, &proto_seq_fops))
return -ENOMEM;
return 0;
}
static __net_exit void proto_exit_net(struct net *net)
{
remove_proc_entry("protocols", net->proc_net);
}
static __net_initdata struct pernet_operations proto_net_ops = {
.init = proto_init_net,
.exit = proto_exit_net,
};
static int __init proto_init(void)
{
return register_pernet_subsys(&proto_net_ops);
}
subsys_initcall(proto_init);
#endif /* PROC_FS */
| tgraf/net-next | net/core/sock.c | C | gpl-2.0 | 78,117 |
How to reinstall your site
=====
"Re-installation" here means not only using profile and installations site from scratch
but this means that you may use the reinstall.yml playbook as a tool for obtaining
dev or stage or even production environment locally.
Keep in mind that this script used by Jenkins server for getting Pull Request builds.
By overriding variables, that you can find within current playbook you can run it
with different conditions. These conditions can pre configure your drupal based software
- beed installed from scratch by using profile
- pre configure your drupal site by using extra provided database dump via url
So you should think about this script as universal tool, or may be better wording = application
that can do a lot of things to get your drupal based software pre configured from scratch.
Possible configurations
=====
Pretty standard way of running this playbook it to try defaults.
example
```sh
ansible-playbook reinstall.yml
```
creates drupal installation from scratch by using ```pp``` preinstalled drupal's profile
been shipped within [CIBOX](https://github.com/propeoplemd/cibox) suite.
What are defaults here?
=====
- installation_profile_name: pp
This variable talk the meaning itself - it can be overridden by
```sh
ansible-playbook reinstall.yml --extra-vars="installation_profile_name=minimal"
```
which helps you to get reinstalled drupal by using minimal drupal's standard profile.
Every variable, shipped with CIBOX suite can be overridden by the way above, just pass
them divided by whitespaces one after each other in a raw within --extra-vars command line key.
Widely used variables
=====
There are a lot of variables within CIBOX suite that can be overridden by Jenkins shell scripts
or by users due to requirements of the projects.
But here is a list of predefined variables that changed or overridden mostly every new project up.
Keep in mind we are talking about reinstall.yml playbook only.
- mysql_db: - This variable stores name of database, been used in a project for drupal site.
This variable can be changed only when you need to enpower your Jenkins instance with more than
one PR/DEMO/STAGE builders. You'll need this if the project contains 2,3 or even more sites and
you need to split sites for been used unique databases for avoiding conflicts.
- php_env_vars: - should be used when you need pass to your server's environment variable for
marking your environment as development. Useful for limiting large imports or background processes
for speedup development and builds.
- site_url: - variable for passing to drush commands or any other url dependant commands.
- pp_environment: - This is very useful and important variable that makes everything complicated.
There are states: default, demo, staging and production for this variable that used for splitting
reinstall.yml to be used as conditional single playbook for ability to get different development
environments.
* Every user and developer should think about reinstall.yml during extending it like:
this script can change almost every environment within a project workflow, starting from dev, ending
with production server. So if you want to change something you should add condition for which
environment this change should be. *
- workflow_type: - currently CIBOX suite enpowered with two types of possible workflows - ```profile```
and ```sql``` based.
Profile based workflow will do reinstall drupal site from scratch using predefined
profile from ```installation_profile_name``` variable.
Sql based workflow will prepare the site from database dump, that is obtained during process from
```source_database``` variable. There is a ```make_backup``` boolean variable for setting ability to
create backups alongside processing playbook.
- backup_user, backup_pass and source_database: - these variables should be used on Jenkins server for
pointing out to right place where sql dump archive stored by Jenkins by cron or any other background app.
Keep in mind that backup should be accessible for webserver via url, injected by ```source_database```
variable.
Switching from profile to sql flow
=====
Typically every new project, developed from scratch starts from Drupal profile creation.
This means teams should use ```workflow_type: profile``` variable state for reinstalling a site by
using profile, predefined in ```installation_profile_name``` variable.
But every project has a phase, where content managers start adding content and reinstall from profile
becomes non convenient for developers. Thats why there is ```sql``` flow predefined within reinstall.yml
playbook.
For switching to ```sql``` flow type, there are steps to be done for making it working.
- change to ```workflow_type: sql```
- create regular SQL db dumper from staging or production environment, depending of the flow complexity.
There is a BACKUP_PROD_DB job shipped by CIBOX suite for boilerplate example how to approach db dump.
The idea behind this to get dump periodically (daily, hourly), depending of project requirements and
to put it to webserver folder for ability to download from any environment and to use for DEV, PR, STAGE
or eny other environments.
- Depending of flow complexity you might want to have more than one DB dumpers - one for preparing dev
environment by using staging database, second one for preparing staging environment by using production
database. For approaching this you should add secondary DB DUMP job with appropriate configs and extend
reinstall.yml for using respective dumps for different ```pp_environment``` states.
Optional features
=====
There are memcache and solr features, disabled by default but shipped within reinstall.yml.
Search for ```CHANGE_ME``` to see how they were implemented for past projects and change them to meet
your project needs.
Best Practices and rules.
====
1. Every developer should extend, change this document when variables above changed, renamed, appended or
removed for some reason.
2. Every reviewer should check that point 1 was done during PR to CIBOX repo.
Please, do not add any features without adding comments to reinstall.yml and this documentation. | M1r1k/vuxenforvaltningens_informationsportal | drupal/README.reinstall.md | Markdown | gpl-2.0 | 6,206 |
/*
* focuser driver.
*
* Copyright (C) 2010 LGE Inc.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/delay.h>
#include <linux/fs.h>
#include <linux/i2c.h>
#include <linux/miscdevice.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <media/ar0832_focuser.h>
// LGE_CHANGE_S X2_ICS [byun.youngki@lge.com], 2012-05-03, < recover to GB version >
#include <media/ar0832_main.h>
// LGE_CHANGE_E X2_ICS [byun.youngki@lge.com], 2012-05-03, < recover to GB version >
#define POS_LOW 0//50
#define POS_HIGH 255
#define SETTLETIME_MS 100
#define FOCAL_LENGTH (3.5f)
#define FNUMBER (2.8f)
#define FPOS_COUNT 1024
DEFINE_MUTEX(star_focuser_lock);
#define DW9716_MAX_RETRIES (3)
static int ar0832_focuser_write(struct i2c_client *client, u16 value)
{
int count;
struct i2c_msg msg[1];
unsigned char data[2];
int retry = 0;
if (!client->adapter)
return -ENODEV;
data[0] = (u8) ((value >> 4) & 0x3F);
data[1] = (u8) ((value & 0xF) << 4);
data[1] = (data[1] &0xF0) |0x05; // Slew rate control (8 steps, 50us)
msg[0].addr = client->addr;
msg[0].flags = 0;
msg[0].len = ARRAY_SIZE(data);
msg[0].buf = data;
// pr_info("%s: focuser set position = %d, 0x%x\n", __func__, value, *(u16*)data);
do {
count = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg));
if (count == ARRAY_SIZE(msg))
return 0;
retry++;
pr_err("ar0832_focuser: i2c transfer failed, retrying %x\n",
value);
msleep(3);
}while (retry <= DW9716_MAX_RETRIES);
return -EIO;
}
static int ar0832_focuser_write_helper(struct ar0832_focuser_info *info, u16 value)
{
int ret;
switch(info->camera_mode){
case Main:
case LeftOnly:
ret = ar0832_focuser_write(info->i2c_client, value);
break;
case Stereo:
ret = ar0832_focuser_write(info->i2c_client, value);
ret = ar0832_focuser_write(info->i2c_client_right, value);
break;
case RightOnly:
ret = ar0832_focuser_write(info->i2c_client_right, value);
break;
default :
return -1;
}
return ret;
}
static int ar0832_focuser_set_position(struct ar0832_focuser_info *info, u32 position)
{
if (position < info->config.pos_low ||
position > info->config.pos_high)
return -EINVAL;
return ar0832_focuser_write(info->i2c_client, position);
}
static long ar0832_focuser_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
struct ar0832_focuser_info *info = file->private_data;
int ret;
switch (cmd) {
case AR0832_FOCUSER_IOCTL_GET_CONFIG:
{
if (copy_to_user((void __user *) arg,
&info->config,
sizeof(info->config))) {
pr_err("%s: 0x%x\n", __func__, __LINE__);
return -EFAULT;
}
break;
}
case AR0832_FOCUSER_IOCTL_SET_POSITION:
mutex_lock(&star_focuser_lock);
ret = ar0832_focuser_set_position(info, (u32) arg);
mutex_unlock(&star_focuser_lock);
return ret;
case AR0832_FOCUSER_IOCTL_SET_MODE:
info->camera_mode =(enum StereoCameraMode)arg;
break;
default:
return -EINVAL;
}
return 0;
}
static struct ar0832_focuser_info *info = NULL;
static int ar0832_focuser_open(struct inode *inode, struct file *file)
{
pr_info("ar0832_focuser: open!\n");
file->private_data = info;
if (info->regulator)
regulator_enable(info->regulator);
return 0;
}
int ar0832_focuser_release(struct inode *inode, struct file *file)
{
pr_info("ar0832_focuser: release!\n");
if (info->regulator)
regulator_disable(info->regulator);
file->private_data = NULL;
return 0;
}
static const struct file_operations ar0832_focuser_fileops = {
.owner = THIS_MODULE,
.open = ar0832_focuser_open,
.unlocked_ioctl = ar0832_focuser_ioctl,
.release = ar0832_focuser_release,
};
static struct miscdevice ar0832_focuser_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = "ar0832_focuser",
.fops = &ar0832_focuser_fileops,
};
static int ar0832_focuser_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
int err;
pr_info("ar0832_focuser: probing sensor.\n");
info = kzalloc(sizeof(struct ar0832_focuser_info), GFP_KERNEL);
if (!info) {
pr_err("ar0832_focuser: Unable to allocate memory!\n");
return -ENOMEM;
}
err = misc_register(&ar0832_focuser_device);
if (err) {
pr_err("ar0832_focuser: Unable to register misc device!\n");
kfree(info);
return err;
}
//WBT#196353 : don'use the regulator. the power turn on when camera turn on.
/*
info->regulator = regulator_get(&client->dev, "p_cam_avdd");
if (IS_ERR_OR_NULL(info->regulator)) {
dev_err(&client->dev, "unable to get regulator %s\n",
dev_name(&client->dev));
info->regulator = NULL;
} else {
regulator_enable(info->regulator);
}
*/
info->regulator = 0;
info->i2c_client = client;
info->config.settle_time = SETTLETIME_MS;
info->config.focal_length = FOCAL_LENGTH;
info->config.fnumber = FNUMBER;
info->config.pos_low = POS_LOW;
info->config.pos_high = POS_HIGH;
i2c_set_clientdata(client, info);
return 0;
}
static int ar0832_focuser_remove(struct i2c_client *client)
{
struct ar0832_focuser_info *info;
info = i2c_get_clientdata(client);
misc_deregister(&ar0832_focuser_device);
kfree(info);
return 0;
}
static const struct i2c_device_id ar0832_focuser_id[] = {
{ "ar0832_focuser", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, ar0832_focuser_id);
static struct i2c_driver ar0832_focuser_i2c_driver = {
.driver = {
.name = "ar0832_focuser",
.owner = THIS_MODULE,
},
.probe = ar0832_focuser_probe,
.remove = ar0832_focuser_remove,
.id_table = ar0832_focuser_id,
};
static int __init ar0832_focuser_init(void)
{
pr_info("ar0832_focuser sensor driver loading\n");
i2c_add_driver(&ar0832_focuser_i2c_driver);
return 0;
}
static void __exit ar0832_focuser_exit(void)
{
i2c_del_driver(&ar0832_focuser_i2c_driver);
}
module_init(ar0832_focuser_init);
module_exit(ar0832_focuser_exit);
| carburano/KingOfBirds_Kernel | drivers/media/video/tegra/ar0832_focuser.c | C | gpl-2.0 | 6,171 |
/* Linux-dependent part of branch trace support for GDB, and GDBserver.
Copyright (C) 2013-2017 Free Software Foundation, Inc.
Contributed by Intel Corp. <markus.t.metzger@intel.com>
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#ifndef LINUX_BTRACE_H
#define LINUX_BTRACE_H
#include "btrace-common.h"
#include "vec.h"
#if HAVE_LINUX_PERF_EVENT_H
# include <linux/perf_event.h>
#endif
struct target_ops;
#if HAVE_LINUX_PERF_EVENT_H
/* A Linux perf event buffer. */
struct perf_event_buffer
{
/* The mapped memory. */
const uint8_t *mem;
/* The size of the mapped memory in bytes. */
size_t size;
/* A pointer to the data_head field for this buffer. */
volatile __u64 *data_head;
/* The data_head value from the last read. */
__u64 last_head;
};
/* Branch trace target information for BTS tracing. */
struct btrace_tinfo_bts
{
/* The Linux perf_event configuration for collecting the branch trace. */
struct perf_event_attr attr;
/* The perf event file. */
int file;
/* The perf event configuration page. */
volatile struct perf_event_mmap_page *header;
/* The BTS perf event buffer. */
struct perf_event_buffer bts;
};
/* Branch trace target information for Intel Processor Trace
tracing. */
struct btrace_tinfo_pt
{
/* The Linux perf_event configuration for collecting the branch trace. */
struct perf_event_attr attr;
/* The perf event file. */
int file;
/* The perf event configuration page. */
volatile struct perf_event_mmap_page *header;
/* The trace perf event buffer. */
struct perf_event_buffer pt;
};
#endif /* HAVE_LINUX_PERF_EVENT_H */
/* Branch trace target information per thread. */
struct btrace_target_info
{
/* The ptid of this thread. */
ptid_t ptid;
/* The obtained branch trace configuration. */
struct btrace_config conf;
#if HAVE_LINUX_PERF_EVENT_H
/* The branch tracing format specific information. */
union
{
/* CONF.FORMAT == BTRACE_FORMAT_BTS. */
struct btrace_tinfo_bts bts;
/* CONF.FORMAT == BTRACE_FORMAT_PT. */
struct btrace_tinfo_pt pt;
} variant;
#endif /* HAVE_LINUX_PERF_EVENT_H */
};
/* See to_supports_btrace in target.h. */
extern int linux_supports_btrace (struct target_ops *, enum btrace_format);
/* See to_enable_btrace in target.h. */
extern struct btrace_target_info *
linux_enable_btrace (ptid_t ptid, const struct btrace_config *conf);
/* See to_disable_btrace in target.h. */
extern enum btrace_error linux_disable_btrace (struct btrace_target_info *ti);
/* See to_read_btrace in target.h. */
extern enum btrace_error linux_read_btrace (struct btrace_data *btrace,
struct btrace_target_info *btinfo,
enum btrace_read_type type);
/* See to_btrace_conf in target.h. */
extern const struct btrace_config *
linux_btrace_conf (const struct btrace_target_info *);
#endif /* LINUX_BTRACE_H */
| totalspectrum/binutils-propeller | gdb/nat/linux-btrace.h | C | gpl-2.0 | 3,526 |
/*
* 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)
*
* Copyright (c) 2011 Helge Bahmann
* Copyright (c) 2013 Tim Blechmann
* Copyright (c) 2014 Andrey Semashev
*/
/*!
* \file atomic/detail/atomic_template.hpp
*
* This header contains interface definition of \c atomic template.
*/
#ifndef BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
#include <cstddef>
#include <boost/cstdint.hpp>
#include <boost/assert.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/bitwise_cast.hpp>
#include <boost/atomic/detail/operations_fwd.hpp>
#include <boost/atomic/detail/type_traits/is_signed.hpp>
#include <boost/atomic/detail/type_traits/is_integral.hpp>
#include <boost/atomic/detail/type_traits/is_function.hpp>
#include <boost/atomic/detail/type_traits/conditional.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined(BOOST_MSVC)
#pragma warning(push)
// 'boost::atomics::atomic<T>' : multiple assignment operators specified
#pragma warning(disable: 4522)
#endif
/*
* IMPLEMENTATION NOTE: All interface functions MUST be declared with BOOST_FORCEINLINE,
* see comment for convert_memory_order_to_gcc in ops_gcc_atomic.hpp.
*/
namespace boost {
namespace atomics {
namespace detail {
BOOST_FORCEINLINE BOOST_CONSTEXPR memory_order deduce_failure_order(memory_order order) BOOST_NOEXCEPT
{
return order == memory_order_acq_rel ? memory_order_acquire : (order == memory_order_release ? memory_order_relaxed : order);
}
BOOST_FORCEINLINE BOOST_CONSTEXPR bool cas_failure_order_must_not_be_stronger_than_success_order(memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT
{
// 15 == (memory_order_seq_cst | memory_order_consume), see memory_order.hpp
// Given the enum values we can test the strength of memory order requirements with this single condition.
return (failure_order & 15u) <= (success_order & 15u);
}
template< typename T, bool IsFunction = boost::atomics::detail::is_function< T >::value >
struct classify_pointer
{
typedef void* type;
};
template< typename T >
struct classify_pointer< T, true >
{
typedef void type;
};
template< typename T, bool IsInt = boost::atomics::detail::is_integral< T >::value >
struct classify
{
typedef void type;
};
template< typename T >
struct classify< T, true > { typedef int type; };
template< typename T >
struct classify< T*, false > { typedef typename classify_pointer< T >::type type; };
template< >
struct classify< void*, false > { typedef void type; };
template< >
struct classify< const void*, false > { typedef void type; };
template< >
struct classify< volatile void*, false > { typedef void type; };
template< >
struct classify< const volatile void*, false > { typedef void type; };
template< typename T, typename U >
struct classify< T U::*, false > { typedef void type; };
template< bool >
struct boolean_constant {};
typedef boolean_constant< true > true_constant;
typedef boolean_constant< false > false_constant;
template< typename T, typename Kind >
class base_atomic;
//! General template. Implementation for user-defined types, such as structs and enums, and pointers to non-object types
template< typename T >
class base_atomic< T, void >
{
public:
typedef T value_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, false > operations;
typedef typename boost::atomics::detail::conditional< sizeof(value_type) <= sizeof(void*), value_type, value_type const& >::type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
private:
typedef boolean_constant< sizeof(value_type) == sizeof(storage_type) > value_matches_storage;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_FORCEINLINE explicit base_atomic(value_arg_type v = value_type()) BOOST_NOEXCEPT : m_storage(atomics::detail::bitwise_cast< storage_type >(v))
{
}
BOOST_FORCEINLINE void store(value_arg_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return atomics::detail::bitwise_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type exchange(value_arg_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::exchange(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
return compare_exchange_strong_impl(expected, desired, success_order, failure_order, value_matches_storage());
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_arg_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
return compare_exchange_weak_impl(expected, desired, success_order, failure_order, value_matches_storage());
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_arg_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
private:
BOOST_FORCEINLINE bool compare_exchange_strong_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, true_constant) volatile BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
return compare_exchange_strong_impl(expected, desired, success_order, failure_order, false_constant());
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, false_constant) volatile BOOST_NOEXCEPT
{
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
}
BOOST_FORCEINLINE bool compare_exchange_weak_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, true_constant) volatile BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
return compare_exchange_weak_impl(expected, desired, success_order, failure_order, false_constant());
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, false_constant) volatile BOOST_NOEXCEPT
{
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
}
};
//! Implementation for integers
template< typename T >
class base_atomic< T, int >
{
public:
typedef T value_type;
typedef T difference_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, boost::atomics::detail::is_signed< T >::value > operations;
typedef value_type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : m_storage(v) {}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return static_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_add(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_sub(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::exchange(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = static_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = static_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_and(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_or(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_xor(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type operator++(int) volatile BOOST_NOEXCEPT
{
return fetch_add(1);
}
BOOST_FORCEINLINE value_type operator++() volatile BOOST_NOEXCEPT
{
return fetch_add(1) + 1;
}
BOOST_FORCEINLINE value_type operator--(int) volatile BOOST_NOEXCEPT
{
return fetch_sub(1);
}
BOOST_FORCEINLINE value_type operator--() volatile BOOST_NOEXCEPT
{
return fetch_sub(1) - 1;
}
BOOST_FORCEINLINE value_type operator+=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_add(v) + v;
}
BOOST_FORCEINLINE value_type operator-=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_sub(v) - v;
}
BOOST_FORCEINLINE value_type operator&=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_and(v) & v;
}
BOOST_FORCEINLINE value_type operator|=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_or(v) | v;
}
BOOST_FORCEINLINE value_type operator^=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_xor(v) ^ v;
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
//! Implementation for bool
template< >
class base_atomic< bool, int >
{
public:
typedef bool value_type;
protected:
typedef atomics::detail::operations< 1u, false > operations;
typedef value_type value_arg_type;
public:
typedef operations::storage_type storage_type;
protected:
operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : m_storage(v) {}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return !!operations::load(m_storage.value, order);
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return !!operations::exchange(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = !!old_value;
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = !!old_value;
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
//! Implementation for pointers to object types
template< typename T >
class base_atomic< T*, void* >
{
public:
typedef T* value_type;
typedef std::ptrdiff_t difference_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, false > operations;
typedef value_type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_FORCEINLINE explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : m_storage(atomics::detail::bitwise_cast< storage_type >(v))
{
}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return atomics::detail::bitwise_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::fetch_add(m_storage.value, static_cast< storage_type >(v * sizeof(T)), order));
}
BOOST_FORCEINLINE value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::fetch_sub(m_storage.value, static_cast< storage_type >(v * sizeof(T)), order));
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::exchange(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE value_type operator++(int) volatile BOOST_NOEXCEPT
{
return fetch_add(1);
}
BOOST_FORCEINLINE value_type operator++() volatile BOOST_NOEXCEPT
{
return fetch_add(1) + 1;
}
BOOST_FORCEINLINE value_type operator--(int) volatile BOOST_NOEXCEPT
{
return fetch_sub(1);
}
BOOST_FORCEINLINE value_type operator--() volatile BOOST_NOEXCEPT
{
return fetch_sub(1) - 1;
}
BOOST_FORCEINLINE value_type operator+=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_add(v) + v;
}
BOOST_FORCEINLINE value_type operator-=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_sub(v) - v;
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
} // namespace detail
template< typename T >
class atomic :
public atomics::detail::base_atomic< T, typename atomics::detail::classify< T >::type >
{
private:
typedef atomics::detail::base_atomic< T, typename atomics::detail::classify< T >::type > base_type;
typedef typename base_type::value_arg_type value_arg_type;
public:
typedef typename base_type::value_type value_type;
typedef typename base_type::storage_type storage_type;
public:
static BOOST_CONSTEXPR_OR_CONST bool is_always_lock_free = base_type::operations::is_always_lock_free;
public:
BOOST_DEFAULTED_FUNCTION(atomic(), BOOST_NOEXCEPT {})
// NOTE: The constructor is made explicit because gcc 4.7 complains that
// operator=(value_arg_type) is considered ambiguous with operator=(atomic const&)
// in assignment expressions, even though conversion to atomic<> is less preferred
// than conversion to value_arg_type.
BOOST_FORCEINLINE explicit BOOST_CONSTEXPR atomic(value_arg_type v) BOOST_NOEXCEPT : base_type(v) {}
BOOST_FORCEINLINE value_type operator= (value_arg_type v) volatile BOOST_NOEXCEPT
{
this->store(v);
return v;
}
BOOST_FORCEINLINE operator value_type() const volatile BOOST_NOEXCEPT
{
return this->load();
}
BOOST_FORCEINLINE bool is_lock_free() const volatile BOOST_NOEXCEPT
{
// C++17 requires all instances of atomic<> return a value consistent with is_always_lock_free here
return is_always_lock_free;
}
BOOST_FORCEINLINE storage_type& storage() BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type volatile& storage() volatile BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type const& storage() const BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type const volatile& storage() const volatile BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_DELETED_FUNCTION(atomic(atomic const&))
BOOST_DELETED_FUNCTION(atomic& operator= (atomic const&))
BOOST_DELETED_FUNCTION(atomic& operator= (atomic const&) volatile)
};
template< typename T >
BOOST_CONSTEXPR_OR_CONST bool atomic< T >::is_always_lock_free;
typedef atomic< char > atomic_char;
typedef atomic< unsigned char > atomic_uchar;
typedef atomic< signed char > atomic_schar;
typedef atomic< uint8_t > atomic_uint8_t;
typedef atomic< int8_t > atomic_int8_t;
typedef atomic< unsigned short > atomic_ushort;
typedef atomic< short > atomic_short;
typedef atomic< uint16_t > atomic_uint16_t;
typedef atomic< int16_t > atomic_int16_t;
typedef atomic< unsigned int > atomic_uint;
typedef atomic< int > atomic_int;
typedef atomic< uint32_t > atomic_uint32_t;
typedef atomic< int32_t > atomic_int32_t;
typedef atomic< unsigned long > atomic_ulong;
typedef atomic< long > atomic_long;
typedef atomic< uint64_t > atomic_uint64_t;
typedef atomic< int64_t > atomic_int64_t;
#ifdef BOOST_HAS_LONG_LONG
typedef atomic< boost::ulong_long_type > atomic_ullong;
typedef atomic< boost::long_long_type > atomic_llong;
#endif
typedef atomic< void* > atomic_address;
typedef atomic< bool > atomic_bool;
typedef atomic< wchar_t > atomic_wchar_t;
#if !defined(BOOST_NO_CXX11_CHAR16_T)
typedef atomic< char16_t > atomic_char16_t;
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T)
typedef atomic< char32_t > atomic_char32_t;
#endif
typedef atomic< int_least8_t > atomic_int_least8_t;
typedef atomic< uint_least8_t > atomic_uint_least8_t;
typedef atomic< int_least16_t > atomic_int_least16_t;
typedef atomic< uint_least16_t > atomic_uint_least16_t;
typedef atomic< int_least32_t > atomic_int_least32_t;
typedef atomic< uint_least32_t > atomic_uint_least32_t;
typedef atomic< int_least64_t > atomic_int_least64_t;
typedef atomic< uint_least64_t > atomic_uint_least64_t;
typedef atomic< int_fast8_t > atomic_int_fast8_t;
typedef atomic< uint_fast8_t > atomic_uint_fast8_t;
typedef atomic< int_fast16_t > atomic_int_fast16_t;
typedef atomic< uint_fast16_t > atomic_uint_fast16_t;
typedef atomic< int_fast32_t > atomic_int_fast32_t;
typedef atomic< uint_fast32_t > atomic_uint_fast32_t;
typedef atomic< int_fast64_t > atomic_int_fast64_t;
typedef atomic< uint_fast64_t > atomic_uint_fast64_t;
typedef atomic< intmax_t > atomic_intmax_t;
typedef atomic< uintmax_t > atomic_uintmax_t;
typedef atomic< std::size_t > atomic_size_t;
typedef atomic< std::ptrdiff_t > atomic_ptrdiff_t;
#if defined(BOOST_HAS_INTPTR_T)
typedef atomic< intptr_t > atomic_intptr_t;
typedef atomic< uintptr_t > atomic_uintptr_t;
#endif
} // namespace atomics
} // namespace boost
#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif
#endif // BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
| jack8z/TODOP | third_party/boost_1_65_1/boost/atomic/detail/atomic_template.hpp | C++ | gpl-2.0 | 30,415 |
/*
* arch/arm/mach-tegra/pm-t3.c
*
* Tegra3 SOC-specific power and cluster management
*
* Copyright (c) 2009-2011, NVIDIA Corporation.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/irq.h>
#include <mach/gpio.h>
#include <mach/iomap.h>
#include <mach/irqs.h>
#include <asm/cpu_pm.h>
#include <asm/hardware/gic.h>
#include <trace/events/power.h>
#include "clock.h"
#include "cpuidle.h"
#include "pm.h"
#include "sleep.h"
#include "tegra3_emc.h"
#include "dvfs.h"
#ifdef CONFIG_TEGRA_CLUSTER_CONTROL
#define CAR_CCLK_BURST_POLICY \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x20)
#define CAR_SUPER_CCLK_DIVIDER \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x24)
#define CAR_CCLKG_BURST_POLICY \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x368)
#define CAR_SUPER_CCLKG_DIVIDER \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x36C)
#define CAR_CCLKLP_BURST_POLICY \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x370)
#define PLLX_DIV2_BYPASS_LP (1<<16)
#define CAR_SUPER_CCLKLP_DIVIDER \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x374)
#define CAR_BOND_OUT_V \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x390)
#define CAR_BOND_OUT_V_CPU_G (1<<0)
#define CAR_BOND_OUT_V_CPU_LP (1<<1)
#define CAR_CLK_ENB_V_SET \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x440)
#define CAR_CLK_ENB_V_CPU_G (1<<0)
#define CAR_CLK_ENB_V_CPU_LP (1<<1)
#define CAR_RST_CPUG_CMPLX_SET \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x450)
#define CAR_RST_CPUG_CMPLX_CLR \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x454)
#define CAR_RST_CPULP_CMPLX_SET \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x458)
#define CAR_RST_CPULP_CMPLX_CLR \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x45C)
#define CAR_CLK_CPUG_CMPLX_SET \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x460)
#define CAR_CLK_CPUG_CMPLX_CLR \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x464)
#define CAR_CLK_CPULP_CMPLX_SET \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x468)
#define CAR_CLK_CPULP_CMPLX_CLR \
(IO_ADDRESS(TEGRA_CLK_RESET_BASE) + 0x46C)
#define CPU_CLOCK(cpu) (0x1<<(8+cpu))
#define CPU_RESET(cpu) (0x1111ul<<(cpu))
static int cluster_switch_prolog_clock(unsigned int flags)
{
u32 reg;
u32 CclkBurstPolicy;
u32 SuperCclkDivier;
/* Read the bond out register containing the G and LP CPUs. */
reg = readl(CAR_BOND_OUT_V);
/* Sync G-PLLX divider bypass with LP (no effect on G, just to prevent
LP settings overwrite by save/restore code */
CclkBurstPolicy = ~PLLX_DIV2_BYPASS_LP & readl(CAR_CCLKG_BURST_POLICY);
CclkBurstPolicy |= PLLX_DIV2_BYPASS_LP & readl(CAR_CCLKLP_BURST_POLICY);
writel(CclkBurstPolicy, CAR_CCLKG_BURST_POLICY);
/* Switching to G? */
if (flags & TEGRA_POWER_CLUSTER_G) {
/* Do the G CPUs exist? */
if (reg & CAR_BOND_OUT_V_CPU_G)
return -ENXIO;
/* Keep G CPU clock policy set by upper laayer, with the
exception of the transition via LP1 */
if (flags & TEGRA_POWER_SDRAM_SELFREFRESH) {
/* In LP1 power mode come up on CLKM (oscillator) */
CclkBurstPolicy = readl(CAR_CCLKG_BURST_POLICY);
CclkBurstPolicy &= ~0xF;
SuperCclkDivier = 0;
writel(CclkBurstPolicy, CAR_CCLKG_BURST_POLICY);
writel(SuperCclkDivier, CAR_SUPER_CCLKG_DIVIDER);
}
/* Hold G CPUs 1-3 in reset after the switch */
reg = CPU_RESET(1) | CPU_RESET(2) | CPU_RESET(3);
writel(reg, CAR_RST_CPUG_CMPLX_SET);
/* Take G CPU 0 out of reset after the switch */
reg = CPU_RESET(0);
writel(reg, CAR_RST_CPUG_CMPLX_CLR);
/* Disable the clocks on G CPUs 1-3 after the switch */
reg = CPU_CLOCK(1) | CPU_CLOCK(2) | CPU_CLOCK(3);
writel(reg, CAR_CLK_CPUG_CMPLX_SET);
/* Enable the clock on G CPU 0 after the switch */
reg = CPU_CLOCK(0);
writel(reg, CAR_CLK_CPUG_CMPLX_CLR);
/* Enable the G CPU complex clock after the switch */
reg = CAR_CLK_ENB_V_CPU_G;
writel(reg, CAR_CLK_ENB_V_SET);
}
/* Switching to LP? */
else if (flags & TEGRA_POWER_CLUSTER_LP) {
/* Does the LP CPU exist? */
if (reg & CAR_BOND_OUT_V_CPU_LP)
return -ENXIO;
/* Keep LP CPU clock policy set by upper layer, with the
exception of the transition via LP1 */
if (flags & TEGRA_POWER_SDRAM_SELFREFRESH) {
/* In LP1 power mode come up on CLKM (oscillator) */
CclkBurstPolicy = readl(CAR_CCLKLP_BURST_POLICY);
CclkBurstPolicy &= ~0xF;
SuperCclkDivier = 0;
writel(CclkBurstPolicy, CAR_CCLKLP_BURST_POLICY);
writel(SuperCclkDivier, CAR_SUPER_CCLKLP_DIVIDER);
}
/* Take the LP CPU ut of reset after the switch */
reg = CPU_RESET(0);
writel(reg, CAR_RST_CPULP_CMPLX_CLR);
/* Enable the clock on the LP CPU after the switch */
reg = CPU_CLOCK(0);
writel(reg, CAR_CLK_CPULP_CMPLX_CLR);
/* Enable the LP CPU complex clock after the switch */
reg = CAR_CLK_ENB_V_CPU_LP;
writel(reg, CAR_CLK_ENB_V_SET);
}
return 0;
}
void tegra_cluster_switch_prolog(unsigned int flags)
{
unsigned int target_cluster = flags & TEGRA_POWER_CLUSTER_MASK;
unsigned int current_cluster = is_lp_cluster()
? TEGRA_POWER_CLUSTER_LP
: TEGRA_POWER_CLUSTER_G;
u32 reg;
/* Read the flow controler CSR register and clear the CPU switch
and immediate flags. If an actual CPU switch is to be performed,
re-write the CSR register with the desired values. */
reg = readl(FLOW_CTRL_CPU_CSR(0));
reg &= ~(FLOW_CTRL_CPU_CSR_IMMEDIATE_WAKE |
FLOW_CTRL_CPU_CSR_SWITCH_CLUSTER);
/* Program flow controller for immediate wake if requested */
if (flags & TEGRA_POWER_CLUSTER_IMMEDIATE)
reg |= FLOW_CTRL_CPU_CSR_IMMEDIATE_WAKE;
/* Do nothing if no switch actions requested */
if (!target_cluster)
goto done;
if ((current_cluster != target_cluster) ||
(flags & TEGRA_POWER_CLUSTER_FORCE)) {
if (current_cluster != target_cluster) {
// Set up the clocks for the target CPU.
if (cluster_switch_prolog_clock(flags)) {
/* The target CPU does not exist */
goto done;
}
/* Set up the flow controller to switch CPUs. */
reg |= FLOW_CTRL_CPU_CSR_SWITCH_CLUSTER;
}
}
done:
writel(reg, FLOW_CTRL_CPU_CSR(0));
}
static void cluster_switch_epilog_actlr(void)
{
u32 actlr;
/* TLB maintenance broadcast bit (FW) is stubbed out on LP CPU (reads
as zero, writes ignored). Hence, it is not preserved across G=>LP=>G
switch by CPU save/restore code, but SMP bit is restored correctly.
Synchronize these two bits here after LP=>G transition. Note that
only CPU0 core is powered on before and after the switch. See also
bug 807595. */
__asm__("mrc p15, 0, %0, c1, c0, 1\n" : "=r" (actlr));
if (actlr & (0x1 << 6)) {
actlr |= 0x1;
__asm__("mcr p15, 0, %0, c1, c0, 1\n" : : "r" (actlr));
}
}
static void cluster_switch_epilog_gic(void)
{
unsigned int max_irq, i;
void __iomem *gic_base = IO_ADDRESS(TEGRA_ARM_INT_DIST_BASE);
/* Reprogram the interrupt affinity because the on the LP CPU,
the interrupt distributor affinity regsiters are stubbed out
by ARM (reads as zero, writes ignored). So when the LP CPU
context save code runs, the affinity registers will read
as all zero. This causes all interrupts to be effectively
disabled when back on the G CPU because they aren't routable
to any CPU. See bug 667720 for details. */
max_irq = readl(gic_base + GIC_DIST_CTR) & 0x1f;
max_irq = (max_irq + 1) * 32;
for (i = 32; i < max_irq; i += 4) {
u32 val = 0x01010101;
#ifdef CONFIG_GIC_SET_MULTIPLE_CPUS
unsigned int irq;
for (irq = i; irq < (i + 4); irq++) {
struct cpumask mask;
struct irq_desc *desc = irq_to_desc(irq);
if (desc && desc->affinity_hint &&
desc->irq_data.affinity) {
if (cpumask_and(&mask, desc->affinity_hint,
desc->irq_data.affinity))
val |= (*cpumask_bits(&mask) & 0xff) <<
((irq & 3) * 8);
}
}
#endif
writel(val, gic_base + GIC_DIST_TARGET + i * 4 / 4);
}
}
void tegra_cluster_switch_epilog(unsigned int flags)
{
u32 reg;
/* Make sure the switch and immediate flags are cleared in
the flow controller to prevent undesirable side-effects
for future users of the flow controller. */
reg = readl(FLOW_CTRL_CPU_CSR(0));
reg &= ~(FLOW_CTRL_CPU_CSR_IMMEDIATE_WAKE |
FLOW_CTRL_CPU_CSR_SWITCH_CLUSTER);
writel(reg, FLOW_CTRL_CPU_CSR(0));
/* Perform post-switch LP=>G clean-up */
if (!is_lp_cluster()) {
cluster_switch_epilog_actlr();
cluster_switch_epilog_gic();
}
#if DEBUG_CLUSTER_SWITCH
{
/* FIXME: clock functions below are taking mutex */
struct clk *c = tegra_get_clock_by_name(
is_lp_cluster() ? "cpu_lp" : "cpu_g");
DEBUG_CLUSTER(("%s: %s freq %lu\r\n", __func__,
is_lp_cluster() ? "LP" : "G", clk_get_rate(c)));
}
#endif
}
int tegra_cluster_control(unsigned int us, unsigned int flags)
{
static ktime_t last_g2lp;
unsigned int target_cluster = flags & TEGRA_POWER_CLUSTER_MASK;
unsigned int current_cluster = is_lp_cluster()
? TEGRA_POWER_CLUSTER_LP
: TEGRA_POWER_CLUSTER_G;
unsigned long irq_flags;
if ((target_cluster == TEGRA_POWER_CLUSTER_MASK) || !target_cluster)
return -EINVAL;
if (num_online_cpus() > 1)
return -EBUSY;
if ((current_cluster == target_cluster)
&& !(flags & TEGRA_POWER_CLUSTER_FORCE))
return -EEXIST;
if (target_cluster == TEGRA_POWER_CLUSTER_G)
if (!is_g_cluster_present())
return -EPERM;
trace_power_start(POWER_PSTATE, target_cluster, 0);
if (flags & TEGRA_POWER_CLUSTER_IMMEDIATE)
us = 0;
DEBUG_CLUSTER(("%s(LP%d): %s->%s %s %s %d\r\n", __func__,
(flags & TEGRA_POWER_SDRAM_SELFREFRESH) ? 1 : 2,
is_lp_cluster() ? "LP" : "G",
(target_cluster == TEGRA_POWER_CLUSTER_G) ? "G" : "LP",
(flags & TEGRA_POWER_CLUSTER_IMMEDIATE) ? "immediate" : "",
(flags & TEGRA_POWER_CLUSTER_FORCE) ? "force" : "",
us));
local_irq_save(irq_flags);
if (current_cluster != target_cluster && !timekeeping_suspended) {
ktime_t now = ktime_get();
if (target_cluster == TEGRA_POWER_CLUSTER_G) {
s64 t = ktime_to_us(ktime_sub(now, last_g2lp));
s64 t_off = tegra_cpu_power_off_time();
if (t_off > t)
udelay((unsigned int)(t_off - t));
tegra_dvfs_rail_on(tegra_cpu_rail, now);
} else {
last_g2lp = now;
tegra_dvfs_rail_off(tegra_cpu_rail, now);
}
}
if (flags & TEGRA_POWER_SDRAM_SELFREFRESH) {
if (us)
tegra_lp2_set_trigger(us);
tegra_cluster_switch_prolog(flags);
tegra_suspend_dram(TEGRA_SUSPEND_LP1, flags);
tegra_cluster_switch_epilog(flags);
if (us)
tegra_lp2_set_trigger(0);
} else {
tegra_set_cpu_in_lp2(0);
cpu_pm_enter();
tegra_idle_lp2_last(0, flags);
cpu_pm_exit();
tegra_clear_cpu_in_lp2(0);
}
local_irq_restore(irq_flags);
DEBUG_CLUSTER(("%s: %s\r\n", __func__, is_lp_cluster() ? "LP" : "G"));
return 0;
}
#endif
#ifdef CONFIG_PM_SLEEP
void tegra_lp0_suspend_mc(void)
{
/* Since memory frequency after LP0 is restored to boot rate
mc timing is saved during init, not on entry to LP0. Keep
this hook just in case, anyway */
}
void tegra_lp0_resume_mc(void)
{
tegra_mc_timing_restore();
}
void tegra_exit_lp_mode(void)
{
unsigned int flags;
printk("tegra_exit_lp_mod+\n");
if (is_lp_cluster()) {
flags = TEGRA_POWER_CLUSTER_G;
flags |= TEGRA_POWER_CLUSTER_IMMEDIATE;
tegra_cluster_control(0, flags);
}
printk("tegra_exit_lp_mod-\n");
}
void tegra_enter_lp_mode(void)
{
unsigned int flags;
printk("tegra_enter_lp_mod+\n");
if (!is_lp_cluster()) {
flags = TEGRA_POWER_CLUSTER_LP;
flags |= TEGRA_POWER_CLUSTER_IMMEDIATE;
tegra_cluster_control(0, flags);
}
printk("tegra_enter_lp_mod-\n");
}
void tegra_lp0_cpu_mode(bool enter)
{
static bool entered_on_g = false;
unsigned int flags;
if (enter)
entered_on_g = !is_lp_cluster();
if (entered_on_g) {
flags = enter ? TEGRA_POWER_CLUSTER_LP : TEGRA_POWER_CLUSTER_G;
flags |= TEGRA_POWER_CLUSTER_IMMEDIATE;
tegra_cluster_control(0, flags);
}
}
#endif
| Galaxian-Soup/android_kernel_asus_tf300t | arch/arm/mach-tegra/pm-t3.c | C | gpl-2.0 | 12,299 |
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2006-03-13 Bernard the first version
*/
#include <rtthread.h>
#include <sep4020.h>
/**
* @addtogroup S3C24X0
*/
/*@{*/
/**
* This function will initialize thread stack
*
* @param tentry the entry of thread
* @param parameter the parameter of entry
* @param stack_addr the beginning stack address
* @param texit the function will be called when thread exit
*
* @return stack address
*/
rt_uint8_t *rt_hw_stack_init(void *tentry, void *parameter,
rt_uint8_t *stack_addr, void *texit)
{
rt_uint32_t *stk;
stack_addr += sizeof(rt_uint32_t);
stack_addr = (rt_uint8_t *)RT_ALIGN_DOWN((rt_uint32_t)stack_addr, 8);
stk = (rt_uint32_t *)stack_addr;
*(--stk) = (rt_uint32_t)tentry; /* entry point */
*(--stk) = (rt_uint32_t)texit; /* lr */
*(--stk) = 0xdeadbeef; /* r12 */
*(--stk) = 0xdeadbeef; /* r11 */
*(--stk) = 0xdeadbeef; /* r10 */
*(--stk) = 0xdeadbeef; /* r9 */
*(--stk) = 0xdeadbeef; /* r8 */
*(--stk) = 0xdeadbeef; /* r7 */
*(--stk) = 0xdeadbeef; /* r6 */
*(--stk) = 0xdeadbeef; /* r5 */
*(--stk) = 0xdeadbeef; /* r4 */
*(--stk) = 0xdeadbeef; /* r3 */
*(--stk) = 0xdeadbeef; /* r2 */
*(--stk) = 0xdeadbeef; /* r1 */
*(--stk) = (rt_uint32_t)parameter; /* r0 : argument */
*(--stk) = Mode_SVC; /* cpsr */
*(--stk) = Mode_SVC; /* spsr */
/* return task's current stack address */
return (rt_uint8_t *)stk;
}
/*@}*/
| grissiom/rt-thread | libcpu/arm/sep4020/stack.c | C | gpl-2.0 | 1,888 |
/*
* Copyright (C) 2011,2012,2013,2014 Samuel Audet
*
* This file is part of JavaCPP.
*
* JavaCPP is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* JavaCPP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with JavaCPP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.javacpp;
import com.googlecode.javacpp.annotation.Adapter;
import com.googlecode.javacpp.annotation.Allocator;
import com.googlecode.javacpp.annotation.ArrayAllocator;
import com.googlecode.javacpp.annotation.ByPtr;
import com.googlecode.javacpp.annotation.ByPtrPtr;
import com.googlecode.javacpp.annotation.ByPtrRef;
import com.googlecode.javacpp.annotation.ByRef;
import com.googlecode.javacpp.annotation.ByVal;
import com.googlecode.javacpp.annotation.Cast;
import com.googlecode.javacpp.annotation.Const;
import com.googlecode.javacpp.annotation.Convention;
import com.googlecode.javacpp.annotation.Function;
import com.googlecode.javacpp.annotation.Index;
import com.googlecode.javacpp.annotation.MemberGetter;
import com.googlecode.javacpp.annotation.MemberSetter;
import com.googlecode.javacpp.annotation.Name;
import com.googlecode.javacpp.annotation.Namespace;
import com.googlecode.javacpp.annotation.NoDeallocator;
import com.googlecode.javacpp.annotation.NoException;
import com.googlecode.javacpp.annotation.NoOffset;
import com.googlecode.javacpp.annotation.Opaque;
import com.googlecode.javacpp.annotation.Platform;
import com.googlecode.javacpp.annotation.Raw;
import com.googlecode.javacpp.annotation.ValueGetter;
import com.googlecode.javacpp.annotation.ValueSetter;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
/**
* The Generator is where all the C++ source code that we need gets generated.
* It has not been designed in any meaningful way since the requirements were
* not well understood. It is basically a prototype and is really quite a mess.
* Now that we understand better what we need, it could use some refactoring.
* <p>
* When attempting to understand what the Generator does, try to run experiments
* and inspect the generated code: It is quite readable.
* <p>
* Moreover, although Generator is the one ultimately doing something with the
* various annotations it relies on, it was easier to describe the behavior its
* meant to have with them as part of the documentation of the annotations, so
* we can refer to them to understand more about how Generator should work:
*
* @see Adapter
* @see Allocator
* @see ArrayAllocator
* @see ByPtr
* @see ByPtrPtr
* @see ByPtrRef
* @see ByRef
* @see ByVal
* @see Cast
* @see Const
* @see Convention
* @see Function
* @see Index
* @see MemberGetter
* @see MemberSetter
* @see Name
* @see Namespace
* @see NoDeallocator
* @see NoException
* @see NoOffset
* @see Opaque
* @see Platform
* @see Raw
* @see ValueGetter
* @see ValueSetter
*
* @author Samuel Audet
*/
public class Generator implements Closeable {
public Generator(Logger logger, Loader.ClassProperties properties) {
this.logger = logger;
this.properties = properties;
}
static class IndexedSet<E> extends LinkedHashMap<E,Integer> implements Iterable<E> {
public int index(E e) {
Integer i = get(e);
if (i == null) {
put(e, i = size());
}
return i;
}
public Iterator<E> iterator() {
return keySet().iterator();
}
}
static final String JNI_VERSION = "JNI_VERSION_1_4";
static final List<Class> baseClasses = Arrays.asList(new Class[] {
Pointer.class,
//FunctionPointer.class,
BytePointer.class,
ShortPointer.class,
IntPointer.class,
LongPointer.class,
FloatPointer.class,
DoublePointer.class,
CharPointer.class,
PointerPointer.class,
BoolPointer.class,
CLongPointer.class,
SizeTPointer.class });
final Logger logger;
final Loader.ClassProperties properties;
PrintWriter out, out2;
IndexedSet<String> callbacks;
IndexedSet<Class> functions, deallocators, arrayDeallocators, jclasses, jclassesInit;
HashMap<Class,LinkedList<String>> members;
boolean mayThrowExceptions, usesAdapters;
public boolean generate(String sourceFilename, String headerFilename,
String classPath, Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
jclassesInit = new IndexedSet<Class>();
members = new HashMap<Class,LinkedList<String>>();
mayThrowExceptions = false;
usesAdapters = false;
if (classes(true, true, classPath, classes)) {
// second pass with a real writer
out = new PrintWriter(sourceFilename);
if (headerFilename != null) {
out2 = new PrintWriter(headerFilename);
}
return classes(mayThrowExceptions, usesAdapters, classPath, classes);
} else {
return false;
}
}
public void close() {
if (out != null) {
out.close();
}
if (out2 != null) {
out2.close();
}
}
boolean classes(boolean handleExceptions, boolean defineAdapters, String classPath, Class<?> ... classes) {
String version = Generator.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
String warning = "// Generated by JavaCPP version " + version;
out.println(warning);
out.println();
if (out2 != null) {
out2.println(warning);
out2.println();
}
for (String s : properties.get("platform.define")) {
out.println("#define " + s);
}
out.println();
out.println("#ifdef __APPLE__");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __attribute__((visibility(\"default\")))");
out.println(" #define JNIIMPORT");
out.println(" #define JNICALL");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println("#ifdef _WIN32");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __declspec(dllexport)");
out.println(" #define JNIIMPORT __declspec(dllimport)");
out.println(" #define JNICALL __stdcall");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println("#include <jni.h>");
if (out2 != null) {
out2.println("#include <jni.h>");
}
out.println("#ifdef ANDROID");
out.println(" #include <android/log.h>");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" #include <TargetConditionals.h>");
out.println(" #include <Foundation/Foundation.h>");
out.println("#endif");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" #define NewWeakGlobalRef(obj) NewGlobalRef(obj)");
out.println(" #define DeleteWeakGlobalRef(obj) DeleteGlobalRef(obj)");
out.println("#endif");
out.println();
out.println("#include <stddef.h>");
out.println("#ifndef _WIN32");
out.println(" #include <stdint.h>");
out.println("#endif");
out.println("#include <stdio.h>");
out.println("#include <stdlib.h>");
out.println("#include <string.h>");
out.println("#include <exception>");
out.println("#include <new>");
out.println();
out.println("#define jlong_to_ptr(a) ((void*)(uintptr_t)(a))");
out.println("#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))");
out.println();
out.println("#if defined(_MSC_VER)");
out.println(" #define JavaCPP_noinline __declspec(noinline)");
out.println(" #define JavaCPP_hidden /* hidden by default */");
out.println("#elif defined(__GNUC__)");
out.println(" #define JavaCPP_noinline __attribute__((noinline))");
out.println(" #define JavaCPP_hidden __attribute__((visibility(\"hidden\")))");
out.println("#else");
out.println(" #define JavaCPP_noinline");
out.println(" #define JavaCPP_hidden");
out.println("#endif");
out.println();
List[] include = { properties.get("platform.include"),
properties.get("platform.cinclude") };
for (int i = 0; i < include.length; i++) {
if (include[i] != null && include[i].size() > 0) {
if (i == 1) {
out.println("extern \"C\" {");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
}
}
for (String s : (List<String>)include[i]) {
String line = "#include ";
if (!s.startsWith("<") && !s.startsWith("\"")) {
line += '"';
}
line += s;
if (!s.endsWith(">") && !s.endsWith("\"")) {
line += '"';
}
out.println(line);
if (out2 != null) {
out2.println(line);
}
}
if (i == 1) {
out.println("}");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
}
out.println();
}
}
out.println("static JavaVM* JavaCPP_vm = NULL;");
out.println("static bool JavaCPP_haveAllocObject = false;");
out.println("static bool JavaCPP_haveNonvirtual = false;");
out.println("static const char* JavaCPP_classNames[" + jclasses.size() + "] = {");
Iterator<Class> classIterator = jclasses.iterator();
int maxMemberSize = 0;
while (classIterator.hasNext()) {
Class c = classIterator.next();
out.print(" \"" + c.getName().replace('.','/') + "\"");
if (classIterator.hasNext()) {
out.println(",");
}
LinkedList<String> m = members.get(c);
if (m != null && m.size() > maxMemberSize) {
maxMemberSize = m.size();
}
}
out.println(" };");
out.println("static jclass JavaCPP_classes[" + jclasses.size() + "] = { NULL };");
out.println("static jfieldID JavaCPP_addressFID = NULL;");
out.println("static jfieldID JavaCPP_positionFID = NULL;");
out.println("static jfieldID JavaCPP_limitFID = NULL;");
out.println("static jfieldID JavaCPP_capacityFID = NULL;");
out.println("static jmethodID JavaCPP_initMID = NULL;");
out.println("static jmethodID JavaCPP_toStringMID = NULL;");
out.println();
out.println("static inline void JavaCPP_log(const char* fmt, ...) {");
out.println(" va_list ap;");
out.println(" va_start(ap, fmt);");
out.println("#ifdef ANDROID");
out.println(" __android_log_vprint(ANDROID_LOG_ERROR, \"javacpp\", fmt, ap);");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" NSLogv([NSString stringWithUTF8String:fmt], ap);");
out.println("#else");
out.println(" vfprintf(stderr, fmt, ap);");
out.println(" fprintf(stderr, \"\\n\");");
out.println("#endif");
out.println(" va_end(ap);");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jclass JavaCPP_getClass(JNIEnv* env, int i) {");
out.println(" if (JavaCPP_classes[i] == NULL && env->PushLocalFrame(1) == 0) {");
out.println(" jclass cls = env->FindClass(JavaCPP_classNames[i]);");
out.println(" if (cls == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error loading class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);");
out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" return JavaCPP_classes[i];");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jfieldID JavaCPP_getFieldID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jfieldID fid = env->GetFieldID(cls, name, sig);");
out.println(" if (fid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting field ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return fid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getStaticMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetStaticMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting static method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jobject JavaCPP_createPointer(JNIEnv* env, int i, jclass cls = NULL) {");
out.println(" if (cls == NULL && (cls = JavaCPP_getClass(env, i)) == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" if (JavaCPP_haveAllocObject) {");
out.println(" return env->AllocObject(cls);");
out.println(" } else {");
out.println(" jmethodID mid = env->GetMethodID(cls, \"<init>\", \"()V\");");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting default constructor of %s, while VM does not support AllocObject()\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" return env->NewObject(cls, mid);");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline void JavaCPP_initPointer(JNIEnv* env, jobject obj, const void* ptr, int size, void (*deallocator)(void*)) {");
out.println(" if (deallocator != NULL) {");
out.println(" jvalue args[3];");
out.println(" args[0].j = ptr_to_jlong(ptr);");
out.println(" args[1].i = size;");
out.println(" args[2].j = ptr_to_jlong(deallocator);");
out.println(" if (JavaCPP_haveNonvirtual) {");
out.println(" env->CallNonvirtualVoidMethodA(obj, JavaCPP_getClass(env, "
+ jclasses.index(Pointer.class) + "), JavaCPP_initMID, args);");
out.println(" } else {");
out.println(" env->CallVoidMethodA(obj, JavaCPP_initMID, args);");
out.println(" }");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(ptr));");
out.println(" env->SetIntField(obj, JavaCPP_limitFID, size);");
out.println(" env->SetIntField(obj, JavaCPP_capacityFID, size);");
out.println(" }");
out.println("}");
out.println();
out.println("class JavaCPP_hidden JavaCPP_exception : public std::exception {");
out.println("public:");
out.println(" JavaCPP_exception(const char* str) throw() {");
out.println(" if (str == NULL) {");
out.println(" strcpy(msg, \"Unknown exception.\");");
out.println(" } else {");
out.println(" strncpy(msg, str, sizeof(msg));");
out.println(" msg[sizeof(msg) - 1] = 0;");
out.println(" }");
out.println(" }");
out.println(" virtual const char* what() const throw() { return msg; }");
out.println(" char msg[1024];");
out.println("};");
out.println();
if (handleExceptions) {
out.println("static JavaCPP_noinline jthrowable JavaCPP_handleException(JNIEnv* env, int i) {");
out.println(" jstring str = NULL;");
out.println(" try {");
out.println(" throw;");
out.println(" } catch (std::exception& e) {");
out.println(" str = env->NewStringUTF(e.what());");
out.println(" } catch (...) {");
out.println(" str = env->NewStringUTF(\"Unknown exception.\");");
out.println(" }");
out.println(" jmethodID mid = JavaCPP_getMethodID(env, i, \"<init>\", \"(Ljava/lang/String;)V\");");
out.println(" if (mid == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" return (jthrowable)env->NewObject(JavaCPP_getClass(env, i), mid, str);");
out.println("}");
out.println();
}
if (defineAdapters) {
out.println("#include <vector>");
out.println("template<typename P, typename T = P> class JavaCPP_hidden VectorAdapter {");
out.println("public:");
out.println(" VectorAdapter(const P* ptr, typename std::vector<T>::size_type size) : ptr((P*)ptr), size(size),");
out.println(" vec2(ptr ? std::vector<T>((P*)ptr, (P*)ptr + size) : std::vector<T>()), vec(vec2) { }");
out.println(" VectorAdapter(const std::vector<T>& vec) : ptr(0), size(0), vec2(vec), vec(vec2) { }");
out.println(" VectorAdapter( std::vector<T>& vec) : ptr(0), size(0), vec(vec) { }");
out.println(" void assign(P* ptr, typename std::vector<T>::size_type size) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" vec.assign(ptr, ptr + size);");
out.println(" }");
out.println(" static void deallocate(void* ptr) { delete[] (P*)ptr; }");
out.println(" operator P*() {");
out.println(" if (vec.size() > size) {");
out.println(" ptr = new (std::nothrow) P[vec.size()];");
out.println(" }");
out.println(" if (ptr) {");
out.println(" std::copy(vec.begin(), vec.end(), ptr);");
out.println(" }");
out.println(" size = vec.size();");
out.println(" return ptr;");
out.println(" }");
out.println(" operator const P*() { return &vec[0]; }");
out.println(" operator std::vector<T>&() { return vec; }");
out.println(" operator std::vector<T>*() { return ptr ? &vec : 0; }");
out.println(" P* ptr;");
out.println(" typename std::vector<T>::size_type size;");
out.println(" std::vector<T> vec2;");
out.println(" std::vector<T>& vec;");
out.println("};");
out.println();
out.println("#include <string>");
out.println("class JavaCPP_hidden StringAdapter {");
out.println("public:");
out.println(" StringAdapter(const char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const signed char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const unsigned char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const std::string& str) : ptr(0), size(0), str2(str), str(str2) { }");
out.println(" StringAdapter( std::string& str) : ptr(0), size(0), str(str) { }");
out.println(" void assign(char* ptr, size_t size) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" str.assign(ptr ? ptr : \"\");");
out.println(" }");
out.println(" static void deallocate(void* ptr) { free(ptr); }");
out.println(" operator char*() {");
out.println(" const char* c_str = str.c_str();");
out.println(" if (ptr == NULL || strcmp(c_str, ptr) != 0) {");
out.println(" ptr = strdup(c_str);");
out.println(" }");
out.println(" size = strlen(c_str) + 1;");
out.println(" return ptr;");
out.println(" }");
out.println(" operator signed char*() { return (signed char*)(operator char*)(); }");
out.println(" operator unsigned char*() { return (unsigned char*)(operator char*)(); }");
out.println(" operator const char*() { return str.c_str(); }");
out.println(" operator const signed char*() { return (signed char*)str.c_str(); }");
out.println(" operator const unsigned char*() { return (unsigned char*)str.c_str(); }");
out.println(" operator std::string&() { return str; }");
out.println(" operator std::string*() { return ptr ? &str : 0; }");
out.println(" char* ptr;");
out.println(" size_t size;");
out.println(" std::string str2;");
out.println(" std::string& str;");
out.println("};");
out.println();
}
if (!functions.isEmpty()) {
out.println("static JavaCPP_noinline void JavaCPP_detach(bool detach) {");
out.println(" if (detach && JavaCPP_vm->DetachCurrentThread() != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not detach the JavaVM from the current thread.\");");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline bool JavaCPP_getEnv(JNIEnv** env) {");
out.println(" bool attached = false;");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" if (vm == NULL) {");
if (out2 != null) {
out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE");
out.println(" int size = 1;");
out.println(" if (JNI_GetCreatedJavaVMs(&vm, 1, &size) != JNI_OK || size == 0) {");
out.println("#endif");
}
out.println(" JavaCPP_log(\"Could not get any created JavaVM.\");");
out.println(" *env = NULL;");
out.println(" return false;");
if (out2 != null) {
out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE");
out.println(" }");
out.println("#endif");
}
out.println(" }");
out.println(" if (vm->GetEnv((void**)env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" struct {");
out.println(" JNIEnv **env;");
out.println(" operator JNIEnv**() { return env; } // Android JNI");
out.println(" operator void**() { return (void**)env; } // standard JNI");
out.println(" } env2 = { env };");
out.println(" if (vm->AttachCurrentThread(env2, NULL) != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not attach the JavaVM to the current thread.\");");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" attached = true;");
out.println(" }");
out.println(" if (JavaCPP_vm == NULL) {");
out.println(" if (JNI_OnLoad(vm, NULL) < 0) {");
out.println(" JavaCPP_detach(attached);");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" }");
out.println(" return attached;");
out.println("}");
out.println();
}
for (Class c : functions) {
String[] typeName = cppTypeName(c);
String[] returnConvention = typeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = typeName[1].substring(1);
String instanceTypeName = functionClassName(c);
out.println("struct JavaCPP_hidden " + instanceTypeName + " {");
out.println(" " + instanceTypeName + "() : ptr(NULL), obj(NULL) { }");
out.println(" " + returnConvention[0] + "operator()" + parameterDeclaration + ";");
out.println(" " + typeName[0] + "ptr" + typeName[1] + ";");
out.println(" jobject obj; static jmethodID mid;");
out.println("};");
out.println("jmethodID " + instanceTypeName + "::mid = NULL;");
}
out.println();
for (String s : callbacks) {
out.println(s);
}
out.println();
for (Class c : deallocators) {
String name = "JavaCPP_" + mangle(c.getName());
out.print("static void " + name + "_deallocate(void *p) { ");
if (FunctionPointer.class.isAssignableFrom(c)) {
String typeName = functionClassName(c) + "*";
out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((("
+ typeName + ")p)->obj); delete (" + typeName + ")p; JavaCPP_detach(a); }");
} else {
String[] typeName = cppTypeName(c);
out.println("delete (" + typeName[0] + typeName[1] + ")p; }");
}
}
for (Class c : arrayDeallocators) {
String name = "JavaCPP_" + mangle(c.getName());
String[] typeName = cppTypeName(c);
out.println("static void " + name + "_deallocateArray(void* p) { delete[] (" + typeName[0] + typeName[1] + ")p; }");
}
out.println();
out.println("extern \"C\" {");
if (out2 != null) {
out2.println();
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
out2.println("JNIIMPORT int JavaCPP_init(int argc, const char *argv[]);");
out.println();
out.println("JNIEXPORT int JavaCPP_init(int argc, const char *argv[]) {");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" if (JavaCPP_vm != NULL) {");
out.println(" return JNI_OK;");
out.println(" }");
out.println(" int err;");
out.println(" JavaVM *vm;");
out.println(" JNIEnv *env;");
out.println(" int nOptions = 1 + (argc > 255 ? 255 : argc);");
out.println(" JavaVMOption options[256] = { { NULL } };");
out.println(" options[0].optionString = (char*)\"-Djava.class.path=" + classPath.replace('\\', '/') + "\";");
out.println(" for (int i = 1; i < nOptions && argv != NULL; i++) {");
out.println(" options[i].optionString = (char*)argv[i - 1];");
out.println(" }");
out.println(" JavaVMInitArgs vm_args = { " + JNI_VERSION + ", nOptions, options };");
out.println(" return (err = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args)) == JNI_OK && vm != NULL && (err = JNI_OnLoad(vm, NULL)) >= 0 ? JNI_OK : err;");
out.println("#endif");
out.println("}");
}
out.println(); // XXX: JNI_OnLoad() should ideally be protected by some mutex
out.println("JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnLoad().\");");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" if (JavaCPP_vm == vm) {");
out.println(" return env->GetVersion();");
out.println(" }");
out.println(" JavaCPP_vm = vm;");
out.println(" JavaCPP_haveAllocObject = env->functions->AllocObject != NULL;");
out.println(" JavaCPP_haveNonvirtual = env->functions->CallNonvirtualVoidMethodA != NULL;");
out.println(" const char* members[" + jclasses.size() + "][" + maxMemberSize + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
LinkedList<String> m = members.get(classIterator.next());
Iterator<String> memberIterator = m == null ? null : m.iterator();
while (memberIterator != null && memberIterator.hasNext()) {
out.print("\"" + memberIterator.next() + "\"");
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.println(" int offsets[" + jclasses.size() + "][" + maxMemberSize + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
Class c = classIterator.next();
LinkedList<String> m = members.get(c);
Iterator<String> memberIterator = m == null ? null : m.iterator();
while (memberIterator != null && memberIterator.hasNext()) {
String[] typeName = cppTypeName(c);
String valueTypeName = valueTypeName(typeName);
String memberName = memberIterator.next();
if ("sizeof".equals(memberName)) {
if ("void".equals(valueTypeName)) {
valueTypeName = "void*";
}
out.print("sizeof(" + valueTypeName + ")");
} else {
out.print("offsetof(" + valueTypeName + ", " + memberName + ")");
}
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.print(" int memberOffsetSizes[" + jclasses.size() + "] = { ");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
LinkedList<String> m = members.get(classIterator.next());
out.print(m == null ? 0 : m.size());
if (classIterator.hasNext()) {
out.print(", ");
}
}
out.println(" };");
out.println(" jmethodID putMemberOffsetMID = JavaCPP_getStaticMethodID(env, " +
jclasses.index(Loader.class) + ", \"putMemberOffset\", \"(Ljava/lang/String;Ljava/lang/String;I)V\");");
out.println(" if (putMemberOffsetMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + " && !env->ExceptionCheck(); i++) {");
out.println(" for (int j = 0; j < memberOffsetSizes[i] && !env->ExceptionCheck(); j++) {");
out.println(" if (env->PushLocalFrame(2) == 0) {");
out.println(" jvalue args[3];");
out.println(" args[0].l = env->NewStringUTF(JavaCPP_classNames[i]);");
out.println(" args[1].l = env->NewStringUTF(members[i][j]);");
out.println(" args[2].i = offsets[i][j];");
out.println(" env->CallStaticVoidMethodA(JavaCPP_getClass(env, " +
jclasses.index(Loader.class) + "), putMemberOffsetMID, args);");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" JavaCPP_addressFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"address\", \"J\");");
out.println(" if (JavaCPP_addressFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_positionFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"position\", \"I\");");
out.println(" if (JavaCPP_positionFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_limitFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"limit\", \"I\");");
out.println(" if (JavaCPP_limitFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_capacityFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"capacity\", \"I\");");
out.println(" if (JavaCPP_capacityFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_initMID = JavaCPP_getMethodID(env, " +
jclasses.index(Pointer.class) + ", \"init\", \"(JIJ)V\");");
out.println(" if (JavaCPP_initMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_toStringMID = JavaCPP_getMethodID(env, " +
jclasses.index(Object.class) + ", \"toString\", \"()Ljava/lang/String;\");");
out.println(" if (JavaCPP_toStringMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
classIterator = jclassesInit.iterator();
while (classIterator.hasNext()) {
Class c = classIterator.next();
if (c == Pointer.class) {
continue;
}
out.println(" if (JavaCPP_getClass(env, " + jclasses.index(c) + ") == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
}
out.println(" return env->GetVersion();");
out.println("}");
out.println();
if (out2 != null) {
out2.println("JNIIMPORT int JavaCPP_uninit();");
out2.println();
out.println("JNIEXPORT int JavaCPP_uninit() {");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" JNI_OnUnload(JavaCPP_vm, NULL);");
out.println(" return vm->DestroyJavaVM();");
out.println("#endif");
out.println("}");
}
out.println();
out.println("JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnUnLoad().\");");
out.println(" return;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + "; i++) {");
out.println(" env->DeleteWeakGlobalRef(JavaCPP_classes[i]);");
out.println(" JavaCPP_classes[i] = NULL;");
out.println(" }");
out.println(" JavaCPP_vm = NULL;");
out.println("}");
out.println();
for (Class<?> cls : baseClasses) {
methods(cls);
}
boolean didSomethingUseful = false;
for (Class<?> cls : classes) {
try {
didSomethingUseful |= methods(cls);
} catch (NoClassDefFoundError e) {
logger.warn("Could not generate code for class " + cls.getCanonicalName() + ": " + e);
}
}
out.println("}");
out.println();
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
return didSomethingUseful;
}
boolean methods(Class<?> cls) {
if (!checkPlatform(cls)) {
return false;
}
LinkedList<String> memberList = members.get(cls);
if (!cls.isAnnotationPresent(Opaque.class) &&
!FunctionPointer.class.isAssignableFrom(cls)) {
if (memberList == null) {
members.put(cls, memberList = new LinkedList<String>());
}
if (!memberList.contains("sizeof")) {
memberList.add("sizeof");
}
}
boolean didSomething = false;
for (Class<?> c : cls.getDeclaredClasses()) {
if (Pointer.class.isAssignableFrom(c) ||
Pointer.Deallocator.class.isAssignableFrom(c)) {
didSomething |= methods(c);
}
}
Method[] methods = cls.getDeclaredMethods();
boolean[] callbackAllocators = new boolean[methods.length];
Method functionMethod = functionMethod(cls, callbackAllocators);
boolean firstCallback = true;
for (int i = 0; i < methods.length; i++) {
String nativeName = mangle(cls.getName()) + "_" + mangle(methods[i].getName());
if (!checkPlatform(methods[i].getAnnotation(Platform.class))) {
continue;
}
MethodInformation methodInfo = methodInformation(methods[i]);
String callbackName = "JavaCPP_" + nativeName + "_callback";
if (callbackAllocators[i] && functionMethod == null) {
logger.warn("No callback method call() or apply() has been not declared in \"" +
cls.getCanonicalName() + "\". No code will be generated for callback allocator.");
continue;
} else if (callbackAllocators[i] || (methods[i].equals(functionMethod) && methodInfo == null)) {
functions.index(cls);
Name name = methods[i].getAnnotation(Name.class);
if (name != null && name.value().length > 0 && name.value()[0].length() > 0) {
callbackName = name.value()[0];
}
callback(cls, functionMethod, callbackName, firstCallback);
firstCallback = false;
didSomething = true;
}
if (methodInfo == null) {
continue;
}
if ((methodInfo.memberGetter || methodInfo.memberSetter) && !methodInfo.noOffset &&
memberList != null && !Modifier.isStatic(methodInfo.modifiers)) {
if (!memberList.contains(methodInfo.memberName[0])) {
memberList.add(methodInfo.memberName[0]);
}
}
didSomething = true;
out.print("JNIEXPORT " + jniTypeName(methodInfo.returnType) + " JNICALL Java_" + nativeName);
if (methodInfo.overloaded) {
out.print("__" + mangle(signature(methodInfo.parameterTypes)));
}
if (Modifier.isStatic(methodInfo.modifiers)) {
out.print("(JNIEnv* env, jclass cls");
} else {
out.print("(JNIEnv* env, jobject obj");
}
for (int j = 0; j < methodInfo.parameterTypes.length; j++) {
out.print(", " + jniTypeName(methodInfo.parameterTypes[j]) + " arg" + j);
}
out.println(") {");
if (callbackAllocators[i]) {
callbackAllocator(cls, callbackName);
continue;
} else if (!Modifier.isStatic(methodInfo.modifiers) && !methodInfo.allocator &&
!methodInfo.arrayAllocator && !methodInfo.deallocator) {
// get our "this" pointer
String[] typeName = cppTypeName(cls);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
} else if (FunctionPointer.class.isAssignableFrom(cls)) {
functions.index(cls);
typeName[0] = functionClassName(cls) + "*";
typeName[1] = "";
}
out.println(" " + typeName[0] + " ptr" + typeName[1] + " = (" + typeName[0] +
typeName[1] + ")jlong_to_ptr(env->GetLongField(obj, JavaCPP_addressFID));");
out.println(" if (ptr == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"This pointer address is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
if (FunctionPointer.class.isAssignableFrom(cls)) {
out.println(" if (ptr->ptr == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"This function pointer address is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
}
if (!cls.isAnnotationPresent(Opaque.class)) {
out.println(" jint position = env->GetIntField(obj, JavaCPP_positionFID);");
out.println(" ptr += position;");
if (methodInfo.bufferGetter) {
out.println(" jint size = env->GetIntField(obj, JavaCPP_limitFID);");
out.println(" size -= position;");
}
}
}
parametersBefore(methodInfo);
String returnPrefix = returnBefore(methodInfo);
call(methodInfo, returnPrefix);
returnAfter(methodInfo);
parametersAfter(methodInfo);
if (methodInfo.throwsException != null) {
out.println(" if (exc != NULL) {");
out.println(" env->Throw(exc);");
out.println(" }");
}
if (methodInfo.returnType != void.class) {
out.println(" return rarg;");
}
out.println("}");
}
out.println();
return didSomething;
}
void parametersBefore(MethodInformation methodInfo) {
String adapterLine = "";
AdapterInformation prevAdapterInfo = null;
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) {
if (!methodInfo.parameterTypes[j].isPrimitive()) {
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
String[] typeName = cppTypeName(methodInfo.parameterTypes[j]);
AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j);
if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
functions.index(methodInfo.parameterTypes[j]);
if (methodInfo.parameterTypes[j] == FunctionPointer.class) {
logger.warn("Method \"" + methodInfo.method + "\" has an abstract FunctionPointer parameter, " +
"but a concrete subclass is required. Compilation will most likely fail.");
}
typeName[0] = functionClassName(methodInfo.parameterTypes[j]) + "*";
typeName[1] = "";
}
if (typeName[0].length() == 0 || methodInfo.parameterRaw[j]) {
methodInfo.parameterRaw[j] = true;
typeName[0] = jniTypeName(methodInfo.parameterTypes[j]);
out.println(" " + typeName[0] + " ptr" + j + " = arg" + j + ";");
continue;
}
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
out.print(" " + typeName[0] + " ptr" + j + typeName[1] + " = ");
if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] +
")jlong_to_ptr(env->GetLongField(arg" + j + ", JavaCPP_addressFID));");
if ((j == 0 && FunctionPointer.class.isAssignableFrom(methodInfo.cls) &&
methodInfo.cls.isAnnotationPresent(Namespace.class)) ||
passBy instanceof ByVal || passBy instanceof ByRef) {
// in the case of member ptr, ptr0 is our object pointer, which cannot be NULL
out.println(" if (ptr" + j + " == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"Pointer address of argument " + j + " is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
}
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j +
", JavaCPP_limitFID);");
}
if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" jint position" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j +
", JavaCPP_positionFID);");
out.println(" ptr" + j + " += position" + j + ";");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" size" + j + " -= position" + j + ";");
}
}
} else if (methodInfo.parameterTypes[j] == String.class) {
out.println("arg" + j + " == NULL ? NULL : env->GetStringUTFChars(arg" + j + ", NULL);");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j + " = 0;");
}
} else if (methodInfo.parameterTypes[j].isArray() &&
methodInfo.parameterTypes[j].getComponentType().isPrimitive()) {
out.print("arg" + j + " == NULL ? NULL : ");
String s = methodInfo.parameterTypes[j].getComponentType().getName();
if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
out.println("(j" + s + "*)env->GetPrimitiveArrayCritical(arg" + j + ", NULL);");
} else {
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println("env->Get" + s + "ArrayElements(arg" + j + ", NULL);");
}
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j +
" = arg" + j + " == NULL ? 0 : env->GetArrayLength(arg" + j + ");");
}
} else if (Buffer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] + ")env->GetDirectBufferAddress(arg" + j + ");");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j +
" = arg" + j + " == NULL ? 0 : env->GetDirectBufferCapacity(arg" + j + ");");
}
} else {
out.println("arg" + j + ";");
logger.warn("Method \"" + methodInfo.method + "\" has an unsupported parameter of type \"" +
methodInfo.parameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail.");
}
if (adapterInfo != null) {
usesAdapters = true;
adapterLine = " " + adapterInfo.name + " adapter" + j + "(";
prevAdapterInfo = adapterInfo;
}
if (prevAdapterInfo != null) {
if (!FunctionPointer.class.isAssignableFrom(methodInfo.cls)) {
// sometimes we need to use the Cast annotation for declaring functions only
adapterLine += cast;
}
adapterLine += "ptr" + j + ", size" + j;
if (--prevAdapterInfo.argc > 0) {
adapterLine += ", ";
}
}
if (prevAdapterInfo != null && prevAdapterInfo.argc <= 0) {
out.println(adapterLine + ");");
prevAdapterInfo = null;
}
}
}
}
String returnBefore(MethodInformation methodInfo) {
String returnPrefix = "";
if (methodInfo.returnType == void.class) {
if (methodInfo.allocator || methodInfo.arrayAllocator) {
if (methodInfo.cls != Pointer.class) {
out.println(" if (!env->IsSameObject(env->GetObjectClass(obj), JavaCPP_getClass(env, " +
jclasses.index(methodInfo.cls) + "))) {");
out.println(" return;");
out.println(" }");
}
String[] typeName = cppTypeName(methodInfo.cls);
returnPrefix = typeName[0] + " rptr" + typeName[1] + " = ";
}
} else {
String cast = cast(methodInfo.returnType, methodInfo.annotations);
String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations);
if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) {
out.println(" jobject rarg = obj;");
} else if (methodInfo.returnType.isPrimitive()) {
out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = 0;");
returnPrefix = typeName[0] + " rvalue" + typeName[1] + " = " + cast;
} else {
Annotation returnBy = by(methodInfo.annotations);
String valueTypeName = valueTypeName(typeName);
returnPrefix = "rptr = " + cast;
if (typeName[0].length() == 0 || methodInfo.returnRaw) {
methodInfo.returnRaw = true;
typeName[0] = jniTypeName(methodInfo.returnType);
out.println(" " + typeName[0] + " rarg = NULL;");
out.println(" " + typeName[0] + " rptr;");
} else if (Pointer.class.isAssignableFrom(methodInfo.returnType) ||
Buffer.class.isAssignableFrom(methodInfo.returnType) ||
(methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive())) {
if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
functions.index(methodInfo.returnType);
typeName[0] = functionClassName(methodInfo.returnType) + "*";
typeName[1] = "";
valueTypeName = valueTypeName(typeName);
returnPrefix = "if (rptr != NULL) rptr->ptr = ";
}
if (returnBy instanceof ByVal) {
returnPrefix += (noException(methodInfo.returnType, methodInfo.method) ?
"new (std::nothrow) " : "new ") + valueTypeName + typeName[1] + "(";
} else if (returnBy instanceof ByRef) {
returnPrefix += "&";
} else if (returnBy instanceof ByPtrPtr) {
if (cast.length() > 0) {
typeName[0] = typeName[0].substring(0, typeName[0].length()-1);
}
returnPrefix = "rptr = NULL; " + typeName[0] + "* rptrptr" + typeName[1] + " = " + cast;
} // else ByPtr || ByPtrRef
if (methodInfo.bufferGetter) {
out.println(" jobject rarg = NULL;");
out.println(" char* rptr;");
} else {
out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = NULL;");
out.println(" " + typeName[0] + " rptr" + typeName[1] + ";");
}
if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
out.println(" rptr = new (std::nothrow) " + valueTypeName + ";");
}
} else if (methodInfo.returnType == String.class) {
out.println(" jstring rarg = NULL;");
out.println(" const char* rptr;");
if (returnBy instanceof ByRef) {
returnPrefix = "std::string rstr(";
} else {
returnPrefix += "(const char*)";
}
} else {
logger.warn("Method \"" + methodInfo.method + "\" has unsupported return type \"" +
methodInfo.returnType.getCanonicalName() + "\". Compilation will most likely fail.");
}
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations);
if (adapterInfo != null) {
usesAdapters = true;
returnPrefix = adapterInfo.name + " radapter(";
}
}
}
if (methodInfo.throwsException != null) {
out.println(" jthrowable exc = NULL;");
out.println(" try {");
}
return returnPrefix;
}
void call(MethodInformation methodInfo, String returnPrefix) {
String indent = methodInfo.throwsException != null ? " " : " ";
String prefix = "(";
String suffix = ")";
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
boolean index = methodInfo.method.isAnnotationPresent(Index.class) ||
(methodInfo.pairedMethod != null &&
methodInfo.pairedMethod.isAnnotationPresent(Index.class));
if (methodInfo.deallocator) {
out.println(indent + "void* allocatedAddress = jlong_to_ptr(arg0);");
out.println(indent + "void (*deallocatorAddress)(void*) = (void(*)(void*))jlong_to_ptr(arg1);");
out.println(indent + "if (deallocatorAddress != NULL && allocatedAddress != NULL) {");
out.println(indent + " (*deallocatorAddress)(allocatedAddress);");
out.println(indent + "}");
return; // nothing else should be appended here for deallocator
} else if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
boolean wantsPointer = false;
int k = methodInfo.parameterTypes.length-1;
if ((methodInfo.valueSetter || methodInfo.memberSetter) &&
!(by(methodInfo, k) instanceof ByRef) &&
adapterInformation(false, methodInfo, k) == null &&
methodInfo.parameterTypes[k] == String.class) {
// special considerations for char arrays as strings
out.print(indent + "strcpy((char*)");
wantsPointer = true;
prefix = ", ";
} else if (k >= 1 && methodInfo.parameterTypes[0].isArray() &&
methodInfo.parameterTypes[0].getComponentType().isPrimitive() &&
(methodInfo.parameterTypes[1] == int.class ||
methodInfo.parameterTypes[1] == long.class)) {
// special considerations for primitive arrays
out.print(indent + "memcpy(");
wantsPointer = true;
prefix = ", ";
if (methodInfo.memberGetter || methodInfo.valueGetter) {
out.print("ptr0 + arg1, ");
} else { // methodInfo.memberSetter || methodInfo.valueSetter
prefix += "ptr0 + arg1, ";
}
skipParameters = 2;
suffix = " * sizeof(*ptr0)" + suffix;
} else {
out.print(indent + returnPrefix);
prefix = methodInfo.valueGetter || methodInfo.memberGetter ? "" : " = ";
suffix = "";
}
if (Modifier.isStatic(methodInfo.modifiers)) {
out.print(cppScopeName(methodInfo));
} else if (methodInfo.memberGetter || methodInfo.memberSetter) {
if (index) {
out.print("(*ptr)");
prefix = "." + methodInfo.memberName[0] + prefix;
} else {
out.print("ptr->" + methodInfo.memberName[0]);
}
} else { // methodInfo.valueGetter || methodInfo.valueSetter
out.print(index ? "(*ptr)" : methodInfo.dim > 0 || wantsPointer ? "ptr" : "*ptr");
}
} else if (methodInfo.bufferGetter) {
out.print(indent + returnPrefix + "ptr");
prefix = "";
suffix = "";
} else { // function call
out.print(indent + returnPrefix);
if (FunctionPointer.class.isAssignableFrom(methodInfo.cls)) {
if (methodInfo.cls.isAnnotationPresent(Namespace.class)) {
out.print("(ptr0->*(ptr->ptr))");
skipParameters = 1;
} else {
out.print("(*ptr->ptr)");
}
} else if (methodInfo.allocator) {
String[] typeName = cppTypeName(methodInfo.cls);
String valueTypeName = valueTypeName(typeName);
if (methodInfo.cls == Pointer.class) {
// can't allocate a "void", so simply assign the argument instead
prefix = "";
suffix = "";
} else {
out.print((noException(methodInfo.cls, methodInfo.method) ?
"new (std::nothrow) " : "new ") + valueTypeName + typeName[1]);
if (methodInfo.arrayAllocator) {
prefix = "[";
suffix = "]";
}
}
} else if (Modifier.isStatic(methodInfo.modifiers)) {
out.print(cppScopeName(methodInfo));
} else {
if (index) {
out.print("(*ptr)");
prefix = "." + methodInfo.memberName[0] + prefix;
} else {
out.print("ptr->" + methodInfo.memberName[0]);
}
}
}
for (int j = skipParameters; j <= methodInfo.parameterTypes.length; j++) {
if (j == skipParameters + methodInfo.dim) {
if (methodInfo.memberName.length > 1) {
out.print(methodInfo.memberName[1]);
}
out.print(prefix);
if (methodInfo.withEnv) {
out.print(Modifier.isStatic(methodInfo.modifiers) ? "env, cls" : "env, obj");
if (methodInfo.parameterTypes.length - skipParameters - methodInfo.dim > 0) {
out.print(", ");
}
}
}
if (j == methodInfo.parameterTypes.length) {
break;
}
if (j < skipParameters + methodInfo.dim) {
// print array indices to access array members, or whatever
// the C++ operator does with them when the Index annotation is present
out.print("[");
}
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j);
if (("(void*)".equals(cast) || "(void *)".equals(cast)) &&
methodInfo.parameterTypes[j] == long.class) {
out.print("jlong_to_ptr(arg" + j + ")");
} else if (methodInfo.parameterTypes[j].isPrimitive()) {
out.print(cast + "arg" + j);
} else if (adapterInfo != null) {
cast = adapterInfo.cast.trim();
if (cast.length() > 0 && !cast.startsWith("(") && !cast.endsWith(")")) {
cast = "(" + cast + ")";
}
out.print(cast + "adapter" + j);
j += adapterInfo.argc - 1;
} else if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j]) && passBy == null) {
out.print(cast + "(ptr" + j + " == NULL ? NULL : ptr" + j + "->ptr)");
} else if (passBy instanceof ByVal || (passBy instanceof ByRef &&
methodInfo.parameterTypes[j] != String.class)) {
out.print("*" + cast + "ptr" + j);
} else if (passBy instanceof ByPtrPtr) {
out.print(cast + "(arg" + j + " == NULL ? NULL : &ptr" + j + ")");
} else { // ByPtr || ByPtrRef || (ByRef && std::string)
out.print(cast + "ptr" + j);
}
if (j < skipParameters + methodInfo.dim) {
out.print("]");
} else if (j < methodInfo.parameterTypes.length - 1) {
out.print(", ");
}
}
out.print(suffix);
if (methodInfo.memberName.length > 2) {
out.print(methodInfo.memberName[2]);
}
if (by(methodInfo.annotations) instanceof ByRef &&
methodInfo.returnType == String.class) {
// special considerations for std::string
out.print(");\n" + indent + "rptr = rstr.c_str()");
}
}
void returnAfter(MethodInformation methodInfo) {
String indent = methodInfo.throwsException != null ? " " : " ";
String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations);
Annotation returnBy = by(methodInfo.annotations);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations);
String suffix = methodInfo.deallocator ? "" : ";";
if (!methodInfo.returnType.isPrimitive() && adapterInfo != null) {
suffix = ")" + suffix;
}
if ((Pointer.class.isAssignableFrom(methodInfo.returnType) ||
(methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive()) ||
Buffer.class.isAssignableFrom(methodInfo.returnType))) {
if (returnBy instanceof ByVal) {
suffix = ")" + suffix;
} else if (returnBy instanceof ByPtrPtr) {
out.println(suffix);
suffix = "";
out.println(indent + "if (rptrptr == NULL) {");
out.println(indent + " env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"Return pointer address is NULL.\");");
out.println(indent + "} else {");
out.println(indent + " rptr = *rptrptr;");
out.println(indent + "}");
}
}
out.println(suffix);
if (methodInfo.returnType == void.class) {
if (methodInfo.allocator || methodInfo.arrayAllocator) {
out.println(indent + "jint rcapacity = " + (methodInfo.arrayAllocator ? "arg0;" : "1;"));
boolean noDeallocator = methodInfo.cls == Pointer.class ||
methodInfo.cls.isAnnotationPresent(NoDeallocator.class);
for (Annotation a : methodInfo.annotations) {
if (a instanceof NoDeallocator) {
noDeallocator = true;
break;
}
}
out.print(indent + "JavaCPP_initPointer(env, obj, rptr, rcapacity, ");
if (noDeallocator) {
out.println("NULL);");
} else if (methodInfo.arrayAllocator) {
out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocateArray);");
arrayDeallocators.index(methodInfo.cls);
} else {
out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocate);");
deallocators.index(methodInfo.cls);
}
}
} else {
if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) {
// nothing
} else if (methodInfo.returnType.isPrimitive()) {
out.println(indent + "rarg = (" + jniTypeName(methodInfo.returnType) + ")rvalue;");
} else if (methodInfo.returnRaw) {
out.println(indent + "rarg = rptr;");
} else {
boolean needInit = false;
if (adapterInfo != null) {
out.println(indent + "rptr = radapter;");
if (methodInfo.returnType != String.class) {
out.println(indent + "jint rcapacity = (jint)radapter.size;");
out.println(indent + "void (*deallocator)(void*) = " +
(adapterInfo.constant ? "NULL;" : "&" + adapterInfo.name + "::deallocate;"));
}
needInit = true;
} else if (returnBy instanceof ByVal ||
FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
out.println(indent + "jint rcapacity = 1;");
out.println(indent + "void (*deallocator)(void*) = &JavaCPP_" +
mangle(methodInfo.returnType.getName()) + "_deallocate;");
deallocators.index(methodInfo.returnType);
needInit = true;
}
if (Pointer.class.isAssignableFrom(methodInfo.returnType)) {
out.print(indent);
if (!(returnBy instanceof ByVal)) {
// check if we can reuse one of the Pointer objects from the arguments
if (Modifier.isStatic(methodInfo.modifiers) && methodInfo.parameterTypes.length > 0) {
for (int i = 0; i < methodInfo.parameterTypes.length; i++) {
String cast = cast(methodInfo, i);
if (Arrays.equals(methodInfo.parameterAnnotations[i], methodInfo.annotations)
&& methodInfo.parameterTypes[i] == methodInfo.returnType) {
out.println( "if (rptr == " + cast + "ptr" + i + ") {");
out.println(indent + " rarg = arg" + i + ";");
out.print(indent + "} else ");
}
}
} else if (!Modifier.isStatic(methodInfo.modifiers) && methodInfo.cls == methodInfo.returnType) {
out.println( "if (rptr == ptr) {");
out.println(indent + " rarg = obj;");
out.print(indent + "} else ");
}
}
out.println( "if (rptr != NULL) {");
out.println(indent + " rarg = JavaCPP_createPointer(env, " + jclasses.index(methodInfo.returnType) +
(methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? ", arg0);" : ");"));
if (needInit) {
out.println(indent + " JavaCPP_initPointer(env, rarg, rptr, rcapacity, deallocator);");
} else {
out.println(indent + " env->SetLongField(rarg, JavaCPP_addressFID, ptr_to_jlong(rptr));");
}
out.println(indent + "}");
} else if (methodInfo.returnType == String.class) {
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->NewStringUTF(rptr);");
out.println(indent + "}");
} else if (methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive()) {
if (adapterInfo == null && !(returnBy instanceof ByVal)) {
out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;");
}
String s = methodInfo.returnType.getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->New" + S + "Array(rcapacity);");
out.println(indent + " env->Set" + S + "ArrayRegion(rarg, 0, rcapacity, (j" + s + "*)rptr);");
out.println(indent + "}");
if (adapterInfo != null) {
out.println(indent + "if (deallocator != 0 && rptr != NULL) {");
out.println(indent + " (*(void(*)(void*))jlong_to_ptr(deallocator))((void*)rptr);");
out.println(indent + "}");
}
} else if (Buffer.class.isAssignableFrom(methodInfo.returnType)) {
if (methodInfo.bufferGetter) {
out.println(indent + "jint rcapacity = size;");
} else if (adapterInfo == null && !(returnBy instanceof ByVal)) {
out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;");
}
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->NewDirectByteBuffer((void*)rptr, rcapacity);");
out.println(indent + "}");
}
}
}
}
void parametersAfter(MethodInformation methodInfo) {
if (methodInfo.throwsException != null) {
mayThrowExceptions = true;
out.println(" } catch (...) {");
out.println(" exc = JavaCPP_handleException(env, " + jclasses.index(methodInfo.throwsException) + ");");
out.println(" }");
out.println();
}
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) {
if (methodInfo.parameterRaw[j]) {
continue;
}
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
String[] typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]);
AdapterInformation adapterInfo = adapterInformation(true, methodInfo, j);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
if (adapterInfo != null) {
for (int k = 0; k < adapterInfo.argc; k++) {
out.println(" " + typeName[0] + " rptr" + (j+k) + typeName[1] + " = " + cast + "adapter" + j + ";");
out.println(" jint rsize" + (j+k) + " = (jint)adapter" + j + ".size" + (k > 0 ? (k+1) + ";" : ";"));
out.println(" if (rptr" + (j+k) + " != " + cast + "ptr" + (j+k) + ") {");
out.println(" JavaCPP_initPointer(env, arg" + j + ", rptr" + (j+k) + ", rsize" + (j+k) + ", &" + adapterInfo.name + "::deallocate);");
out.println(" } else {");
out.println(" env->SetIntField(arg" + j + ", JavaCPP_limitFID, rsize" + (j+k) + " + position" + (j+k) + ");");
out.println(" }");
}
} else if ((passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) &&
!methodInfo.valueSetter && !methodInfo.memberSetter) {
if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" ptr" + j + " -= position" + j + ";");
}
out.println(" if (arg" + j + " != NULL) env->SetLongField(arg" + j +
", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));");
}
} else if (methodInfo.parameterTypes[j] == String.class) {
out.println(" if (arg" + j + " != NULL) env->ReleaseStringUTFChars(arg" + j + ", ptr" + j + ");");
} else if (methodInfo.parameterTypes[j].isArray() &&
methodInfo.parameterTypes[j].getComponentType().isPrimitive()) {
out.print(" if (arg" + j + " != NULL) ");
if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
out.println("env->ReleasePrimitiveArrayCritical(arg" + j + ", ptr" + j + ", 0);");
} else {
String s = methodInfo.parameterTypes[j].getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println("env->Release" + S + "ArrayElements(arg" + j + ", (j" + s + "*)ptr" + j + ", 0);");
}
}
}
}
void callback(Class<?> cls, Method callbackMethod, String callbackName, boolean needFunctor) {
Class<?> callbackReturnType = callbackMethod.getReturnType();
Class<?>[] callbackParameterTypes = callbackMethod.getParameterTypes();
Annotation[] callbackAnnotations = callbackMethod.getAnnotations();
Annotation[][] callbackParameterAnnotations = callbackMethod.getParameterAnnotations();
String instanceTypeName = functionClassName(cls);
String[] callbackTypeName = cppTypeName(cls);
String[] returnConvention = callbackTypeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = callbackTypeName[1].substring(1);
callbacks.index("static " + instanceTypeName + " " + callbackName + "_instance;");
jclassesInit.index(cls); // for custom class loaders
if (out2 != null) {
out2.println("JNIIMPORT " + returnConvention[0] + (returnConvention.length > 1 ?
returnConvention[1] : "") + callbackName + parameterDeclaration + ";");
}
out.println("JNIEXPORT " + returnConvention[0] + (returnConvention.length > 1 ?
returnConvention[1] : "") + callbackName + parameterDeclaration + " {");
out.print((callbackReturnType != void.class ? " return " : " ") + callbackName + "_instance(");
for (int j = 0; j < callbackParameterTypes.length; j++) {
out.print("arg" + j);
if (j < callbackParameterTypes.length - 1) {
out.print(", ");
}
}
out.println(");");
out.println("}");
if (!needFunctor) {
return;
}
out.println(returnConvention[0] + instanceTypeName + "::operator()" + parameterDeclaration + " {");
String returnPrefix = "";
if (callbackReturnType != void.class) {
out.println(" " + jniTypeName(callbackReturnType) + " rarg = 0;");
returnPrefix = "rarg = ";
if (callbackReturnType == String.class) {
returnPrefix += "(jstring)";
}
}
String callbackReturnCast = cast(callbackReturnType, callbackAnnotations);
Annotation returnBy = by(callbackAnnotations);
String[] returnTypeName = cppTypeName(callbackReturnType);
String returnValueTypeName = valueTypeName(returnTypeName);
AdapterInformation returnAdapterInfo = adapterInformation(false, returnValueTypeName, callbackAnnotations);
out.println(" jthrowable exc = NULL;");
out.println(" JNIEnv* env;");
out.println(" bool attached = JavaCPP_getEnv(&env);");
out.println(" if (env == NULL) {");
out.println(" goto end;");
out.println(" }");
out.println("{");
if (callbackParameterTypes.length > 0) {
out.println(" jvalue args[" + callbackParameterTypes.length + "];");
for (int j = 0; j < callbackParameterTypes.length; j++) {
if (callbackParameterTypes[j].isPrimitive()) {
out.println(" args[" + j + "]." +
signature(callbackParameterTypes[j]).toLowerCase() + " = (" +
jniTypeName(callbackParameterTypes[j]) + ")arg" + j + ";");
} else {
Annotation passBy = by(callbackParameterAnnotations[j]);
String[] typeName = cppTypeName(callbackParameterTypes[j]);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, callbackParameterAnnotations[j]);
boolean needInit = false;
if (adapterInfo != null) {
usesAdapters = true;
out.println(" " + adapterInfo.name + " adapter" + j + "(arg" + j + ");");
if (callbackParameterTypes[j] != String.class) {
out.println(" jint size" + j + " = (jint)adapter" + j + ".size;");
out.println(" void (*deallocator" + j + ")(void*) = &" + adapterInfo.name + "::deallocate;");
}
needInit = true;
} else if ((passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) ||
FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
out.println(" jint size" + j + " = 1;");
out.println(" void (*deallocator" + j + ")(void*) = &JavaCPP_" +
mangle(callbackParameterTypes[j].getName()) + "_deallocate;");
deallocators.index(callbackParameterTypes[j]);
needInit = true;
}
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j]) ||
Buffer.class.isAssignableFrom(callbackParameterTypes[j]) ||
(callbackParameterTypes[j].isArray() &&
callbackParameterTypes[j].getComponentType().isPrimitive())) {
if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
functions.index(callbackParameterTypes[j]);
typeName[0] = functionClassName(callbackParameterTypes[j]) + "*";
typeName[1] = "";
valueTypeName = valueTypeName(typeName);
}
out.println(" " + jniTypeName(callbackParameterTypes[j]) + " obj" + j + " = NULL;");
out.println(" " + typeName[0] + " ptr" + j + typeName[1] + " = NULL;");
if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
out.println(" ptr" + j + " = new (std::nothrow) " + valueTypeName + ";");
out.println(" if (ptr" + j + " != NULL) {");
out.println(" ptr" + j + "->ptr = arg" + j + ";");
out.println(" }");
} else if (adapterInfo != null) {
out.println(" ptr" + j + " = adapter" + j + ";");
} else if (passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) {
out.println(" ptr" + j + (noException(callbackParameterTypes[j], callbackMethod) ?
" = new (std::nothrow) " : " = new ") + valueTypeName + typeName[1] +
"(*(" + typeName[0] + typeName[1] + ")&arg" + j + ");");
} else if (passBy instanceof ByVal || passBy instanceof ByRef) {
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")&arg" + j + ";");
} else if (passBy instanceof ByPtrPtr) {
out.println(" if (arg" + j + " == NULL) {");
out.println(" JavaCPP_log(\"Pointer address of argument " + j + " is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" } else {");
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")*arg" + j + ";");
out.println(" }");
} else { // ByPtr || ByPtrRef
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")arg" + j + ";");
}
}
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) {
String s = " obj" + j + " = JavaCPP_createPointer(env, " + jclasses.index(callbackParameterTypes[j]) + ");";
jclassesInit.index(callbackParameterTypes[j]); // for custom class loaders
adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]);
if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) {
out.println(s);
} else {
out.println(" if (ptr" + j + " != NULL) { ");
out.println(" " + s);
out.println(" }");
}
out.println(" if (obj" + j + " != NULL) { ");
if (needInit) {
out.println(" JavaCPP_initPointer(env, obj" + j + ", ptr" + j + ", size" + j + ", deallocator" + j + ");");
} else {
out.println(" env->SetLongField(obj" + j + ", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));");
}
out.println(" }");
out.println(" args[" + j + "].l = obj" + j + ";");
} else if (callbackParameterTypes[j] == String.class) {
out.println(" jstring obj" + j + " = (const char*)" + (adapterInfo != null ? "adapter" : "arg") + j +
" == NULL ? NULL : env->NewStringUTF((const char*)" + (adapterInfo != null ? "adapter" : "arg") + j + ");");
out.println(" args[" + j + "].l = obj" + j + ";");
} else if (callbackParameterTypes[j].isArray() &&
callbackParameterTypes[j].getComponentType().isPrimitive()) {
if (adapterInfo == null) {
out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;");
}
String s = callbackParameterTypes[j].getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println(" if (ptr" + j + " != NULL) {");
out.println(" obj" + j + " = env->New" + S + "Array(size"+ j + ");");
out.println(" env->Set" + S + "ArrayRegion(obj" + j + ", 0, size" + j + ", (j" + s + "*)ptr" + j + ");");
out.println(" }");
if (adapterInfo != null) {
out.println(" if (deallocator" + j + " != 0 && ptr" + j + " != NULL) {");
out.println(" (*(void(*)(void*))jlong_to_ptr(deallocator" + j + "))((void*)ptr" + j + ");");
out.println(" }");
}
} else if (Buffer.class.isAssignableFrom(callbackParameterTypes[j])) {
if (adapterInfo == null) {
out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;");
}
out.println(" if (ptr" + j + " != NULL) {");
out.println(" obj" + j + " = env->NewDirectByteBuffer((void*)ptr" + j + ", size" + j + ");");
out.println(" }");
} else {
logger.warn("Callback \"" + callbackMethod + "\" has unsupported parameter type \"" +
callbackParameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail.");
}
}
}
}
out.println(" if (obj == NULL) {");
out.println(" obj = env->NewGlobalRef(JavaCPP_createPointer(env, " + jclasses.index(cls) + "));");
out.println(" if (obj == NULL) {");
out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(this));");
out.println(" }");
out.println(" ptr = &" + callbackName + ";");
out.println(" }");
out.println(" if (mid == NULL) {");
out.println(" mid = JavaCPP_getMethodID(env, " + jclasses.index(cls) + ", \"" + callbackMethod.getName() + "\", \"(" +
signature(callbackMethod.getParameterTypes()) + ")" + signature(callbackMethod.getReturnType()) + "\");");
out.println(" }");
out.println(" if (env->IsSameObject(obj, NULL)) {");
out.println(" JavaCPP_log(\"Function pointer object is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" } else if (mid == NULL) {");
out.println(" JavaCPP_log(\"Error getting method ID of function caller \\\"" + callbackMethod + "\\\" for callback.\");");
out.println(" } else {");
String s = "Object";
if (callbackReturnType.isPrimitive()) {
s = callbackReturnType.getName();
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
out.println(" " + returnPrefix + "env->Call" + s + "MethodA(obj, mid, " + (callbackParameterTypes.length == 0 ? "NULL);" : "args);"));
out.println(" if ((exc = env->ExceptionOccurred()) != NULL) {");
out.println(" env->ExceptionClear();");
out.println(" }");
out.println(" }");
for (int j = 0; j < callbackParameterTypes.length; j++) {
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) {
String[] typeName = cppTypeName(callbackParameterTypes[j]);
Annotation passBy = by(callbackParameterAnnotations[j]);
String cast = cast(callbackParameterTypes[j], callbackParameterAnnotations[j]);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) {
out.println(" " + typeName[0] + " rptr" + j + typeName[1] + " = (" +
typeName[0] + typeName[1] + ")jlong_to_ptr(env->GetLongField(obj" + j + ", JavaCPP_addressFID));");
if (adapterInfo != null) {
out.println(" jint rsize" + j + " = env->GetIntField(obj" + j + ", JavaCPP_limitFID);");
}
if (!callbackParameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" jint rposition" + j + " = env->GetIntField(obj" + j + ", JavaCPP_positionFID);");
out.println(" rptr" + j + " += rposition" + j + ";");
if (adapterInfo != null) {
out.println(" rsize" + j + " -= rposition" + j + ";");
}
}
if (adapterInfo != null) {
out.println(" adapter" + j + ".assign(rptr" + j + ", rsize" + j + ");");
} else if (passBy instanceof ByPtrPtr) {
out.println(" if (arg" + j + " != NULL) {");
out.println(" *arg" + j + " = *" + cast + "&rptr" + j + ";");
out.println(" }");
} else if (passBy instanceof ByPtrRef) {
out.println(" arg" + j + " = " + cast + "rptr" + j + ";");
}
}
}
if (!callbackParameterTypes[j].isPrimitive()) {
out.println(" env->DeleteLocalRef(obj" + j + ");");
}
}
out.println("}");
out.println("end:");
if (callbackReturnType != void.class) {
if ("void*".equals(returnTypeName[0])) {
returnTypeName[0] = "char*";
}
if (Pointer.class.isAssignableFrom(callbackReturnType)) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : (" +
returnTypeName[0] + returnTypeName[1] + ")jlong_to_ptr(env->GetLongField(rarg, JavaCPP_addressFID));");
if (returnAdapterInfo != null) {
out.println(" jint rsize = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_limitFID);");
}
if (!callbackReturnType.isAnnotationPresent(Opaque.class)) {
out.println(" jint rposition = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_positionFID);");
out.println(" rptr += rposition;");
if (returnAdapterInfo != null) {
out.println(" rsize -= rposition;");
}
}
} else if (callbackReturnType == String.class) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetStringUTFChars(rarg, NULL);");
if (returnAdapterInfo != null) {
out.println(" jint rsize = 0;");
}
} else if (Buffer.class.isAssignableFrom(callbackReturnType)) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetDirectBufferAddress(rarg);");
if (returnAdapterInfo != null) {
out.println(" jint rsize = rarg == NULL ? 0 : env->GetDirectBufferCapacity(rarg);");
}
} else if (!callbackReturnType.isPrimitive()) {
logger.warn("Callback \"" + callbackMethod + "\" has unsupported return type \"" +
callbackReturnType.getCanonicalName() + "\". Compilation will most likely fail.");
}
}
out.println(" if (exc != NULL) {");
out.println(" jstring str = (jstring)env->CallObjectMethod(exc, JavaCPP_toStringMID);");
out.println(" env->DeleteLocalRef(exc);");
out.println(" const char *msg = env->GetStringUTFChars(str, NULL);");
out.println(" JavaCPP_exception e(msg);");
out.println(" env->ReleaseStringUTFChars(str, msg);");
out.println(" env->DeleteLocalRef(str);");
out.println(" JavaCPP_detach(attached);");
out.println(" throw e;");
out.println(" } else {");
out.println(" JavaCPP_detach(attached);");
out.println(" }");
if (callbackReturnType != void.class) {
if (callbackReturnType.isPrimitive()) {
out.println(" return " + callbackReturnCast + "rarg;");
} else if (returnAdapterInfo != null) {
usesAdapters = true;
out.println(" return " + returnAdapterInfo.name + "(" + callbackReturnCast + "rptr, rsize);");
} else if (FunctionPointer.class.isAssignableFrom(callbackReturnType)) {
functions.index(callbackReturnType);
out.println(" return " + callbackReturnCast + "(rptr == NULL ? NULL : rptr->ptr);");
} else if (returnBy instanceof ByVal || returnBy instanceof ByRef) {
out.println(" if (rptr == NULL) {");
out.println(" JavaCPP_log(\"Return pointer address is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" static " + returnValueTypeName + " empty" + returnTypeName[1] + ";");
out.println(" return empty;");
out.println(" } else {");
out.println(" return *" + callbackReturnCast + "rptr;");
out.println(" }");
} else if (returnBy instanceof ByPtrPtr) {
out.println(" return " + callbackReturnCast + "&rptr;");
} else { // ByPtr || ByPtrRef
out.println(" return " + callbackReturnCast + "rptr;");
}
}
out.println("}");
}
void callbackAllocator(Class cls, String callbackName) {
// XXX: Here, we should actually allocate new trampolines on the heap somehow...
// For now it just bumps out from the global variable the last object that called this method
String instanceTypeName = functionClassName(cls);
out.println(" obj = env->NewWeakGlobalRef(obj);");
out.println(" if (obj == NULL) {");
out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");");
out.println(" return;");
out.println(" }");
out.println(" " + instanceTypeName + "* rptr = new (std::nothrow) " + instanceTypeName + ";");
out.println(" if (rptr != NULL) {");
out.println(" rptr->ptr = &" + callbackName + ";");
out.println(" rptr->obj = obj;");
out.println(" JavaCPP_initPointer(env, obj, rptr, 1, &JavaCPP_" + mangle(cls.getName()) + "_deallocate);");
deallocators.index(cls);
out.println(" " + callbackName + "_instance = *rptr;");
out.println(" }");
out.println("}");
}
boolean checkPlatform(Class<?> cls) {
com.googlecode.javacpp.annotation.Properties classProperties =
cls.getAnnotation(com.googlecode.javacpp.annotation.Properties.class);
if (classProperties != null) {
Class[] classes = classProperties.inherit();
if (classes != null) {
for (Class c : classes) {
if (checkPlatform(c)) {
return true;
}
}
}
Platform[] platforms = classProperties.value();
if (platforms != null) {
for (Platform p : platforms) {
if (checkPlatform(p)) {
return true;
}
}
}
} else if (checkPlatform(cls.getAnnotation(Platform.class))) {
return true;
}
return false;
}
boolean checkPlatform(Platform platform) {
if (platform == null) {
return true;
}
String platform2 = properties.getProperty("platform");
String[][] names = { platform.value(), platform.not() };
boolean[] matches = { false, false };
for (int i = 0; i < names.length; i++) {
for (String s : names[i]) {
if (platform2.startsWith(s)) {
matches[i] = true;
break;
}
}
}
if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) {
return true;
}
return false;
}
static String functionClassName(Class<?> cls) {
Name name = cls.getAnnotation(Name.class);
return name != null ? name.value()[0] : "JavaCPP_" + mangle(cls.getName());
}
static Method functionMethod(Class<?> cls, boolean[] callbackAllocators) {
if (!FunctionPointer.class.isAssignableFrom(cls)) {
return null;
}
Method[] methods = cls.getDeclaredMethods();
Method functionMethod = null;
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
int modifiers = methods[i].getModifiers();
Class[] parameterTypes = methods[i].getParameterTypes();
Class returnType = methods[i].getReturnType();
if (Modifier.isStatic(modifiers)) {
continue;
}
if (callbackAllocators != null && methodName.startsWith("allocate") &&
Modifier.isNative(modifiers) && returnType == void.class &&
parameterTypes.length == 0) {
// found a callback allocator method
callbackAllocators[i] = true;
} else if (methodName.startsWith("call") || methodName.startsWith("apply")) {
// found a function caller method and/or callback method
functionMethod = methods[i];
}
}
return functionMethod;
}
static class MethodInformation {
Class<?> cls;
Method method;
Annotation[] annotations;
int modifiers;
Class<?> returnType;
String name, memberName[];
int dim;
boolean[] parameterRaw;
Class<?>[] parameterTypes;
Annotation[][] parameterAnnotations;
boolean returnRaw, withEnv, overloaded, noOffset, deallocator, allocator, arrayAllocator,
bufferGetter, valueGetter, valueSetter, memberGetter, memberSetter, noReturnGetter;
Method pairedMethod;
Class<?> throwsException;
}
MethodInformation methodInformation(Method method) {
if (!Modifier.isNative(method.getModifiers())) {
return null;
}
MethodInformation info = new MethodInformation();
info.cls = method.getDeclaringClass();
info.method = method;
info.annotations = method.getAnnotations();
info.modifiers = method.getModifiers();
info.returnType = method.getReturnType();
info.name = method.getName();
Name name = method.getAnnotation(Name.class);
info.memberName = name != null ? name.value() : new String[] { info.name };
Index index = method.getAnnotation(Index.class);
info.dim = index != null ? index.value() : 0;
info.parameterTypes = method.getParameterTypes();
info.parameterAnnotations = method.getParameterAnnotations();
info.returnRaw = method.isAnnotationPresent(Raw.class);
info.withEnv = info.returnRaw ? method.getAnnotation(Raw.class).withEnv() : false;
info.parameterRaw = new boolean[info.parameterAnnotations.length];
for (int i = 0; i < info.parameterAnnotations.length; i++) {
for (int j = 0; j < info.parameterAnnotations[i].length; j++) {
if (info.parameterAnnotations[i][j] instanceof Raw) {
info.parameterRaw[i] = true;
info.withEnv |= ((Raw)info.parameterAnnotations[i][j]).withEnv();
}
}
}
boolean canBeGetter = info.returnType != void.class || (info.parameterTypes.length > 0 &&
info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive());
boolean canBeSetter = (info.returnType == void.class ||
info.returnType == info.cls) && info.parameterTypes.length > 0;
boolean canBeAllocator = !Modifier.isStatic(info.modifiers) && info.returnType == void.class;
boolean canBeArrayAllocator = canBeAllocator && info.parameterTypes.length == 1 &&
(info.parameterTypes[0] == int.class || info.parameterTypes[0] == long.class);
boolean valueGetter = false;
boolean valueSetter = false;
boolean memberGetter = false;
boolean memberSetter = false;
boolean noReturnGetter = false;
Method pairedMethod = null;
for (Method method2 : info.cls.getDeclaredMethods()) {
int modifiers2 = method2.getModifiers();
Class returnType2 = method2.getReturnType();
String methodName2 = method2.getName();
Class[] parameterTypes2 = method2.getParameterTypes();
Annotation[] annotations2 = method2.getAnnotations();
Annotation[][] parameterAnnotations2 = method2.getParameterAnnotations();
int skipParameters = info.parameterTypes.length > 0 && info.parameterTypes[0] == Class.class ? 1 : 0;
int skipParameters2 = parameterTypes2.length > 0 && parameterTypes2[0] == Class.class ? 1 : 0;
if (method.equals(method2) || !Modifier.isNative(modifiers2)) {
continue;
}
boolean canBeValueGetter = false;
boolean canBeValueSetter = false;
boolean canBeMemberGetter = false;
boolean canBeMemberSetter = false;
if (canBeGetter && "get".equals(info.name) && "put".equals(methodName2)) {
canBeValueGetter = true;
} else if (canBeSetter && "put".equals(info.name) && "get".equals(methodName2)) {
canBeValueSetter = true;
} else if (methodName2.equals(info.name)) {
info.overloaded = true;
canBeMemberGetter = canBeGetter;
canBeMemberSetter = canBeSetter;
for (int j = skipParameters; j < info.parameterTypes.length; j++) {
if (info.parameterTypes[j] != int.class && info.parameterTypes[j] != long.class) {
canBeMemberGetter = false;
if (j < info.parameterTypes.length - 1) {
canBeMemberSetter = false;
}
}
}
} else {
continue;
}
boolean sameIndexParameters = true;
for (int j = 0; j < info.parameterTypes.length - skipParameters && j < parameterTypes2.length - skipParameters2; j++) {
if (info.parameterTypes[j + skipParameters] != parameterTypes2[j + skipParameters2]) {
sameIndexParameters = false;
}
}
if (!sameIndexParameters) {
continue;
}
boolean parameterAsReturn = canBeValueGetter && info.parameterTypes.length > 0 &&
info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive();
boolean parameterAsReturn2 = canBeValueSetter && parameterTypes2.length > 0 &&
parameterTypes2[0].isArray() && parameterTypes2[0].getComponentType().isPrimitive();
if (canBeGetter && parameterTypes2.length - (parameterAsReturn ? 0 : 1) == info.parameterTypes.length - skipParameters
&& (parameterAsReturn ? info.parameterTypes[info.parameterTypes.length - 1] : info.returnType) ==
parameterTypes2[parameterTypes2.length - 1] && (returnType2 == void.class || returnType2 == info.cls)
&& (parameterAnnotations2[parameterAnnotations2.length - 1].length == 0
|| (Arrays.equals(parameterAnnotations2[parameterAnnotations2.length - 1], info.annotations)))) {
pairedMethod = method2;
valueGetter = canBeValueGetter;
memberGetter = canBeMemberGetter;
noReturnGetter = parameterAsReturn;
} else if (canBeSetter && info.parameterTypes.length - (parameterAsReturn2 ? 0 : 1) == parameterTypes2.length - skipParameters2
&& (parameterAsReturn2 ? parameterTypes2[parameterTypes2.length - 1] : returnType2) ==
info.parameterTypes[info.parameterTypes.length - 1] && (info.returnType == void.class || info.returnType == info.cls)
&& (info.parameterAnnotations[info.parameterAnnotations.length - 1].length == 0
|| (Arrays.equals(info.parameterAnnotations[info.parameterAnnotations.length - 1], annotations2)))) {
pairedMethod = method2;
valueSetter = canBeValueSetter;
memberSetter = canBeMemberSetter;
}
}
Annotation behavior = behavior(info.annotations);
if (canBeGetter && behavior instanceof ValueGetter) {
info.valueGetter = true;
info.noReturnGetter = noReturnGetter;
} else if (canBeSetter && behavior instanceof ValueSetter) {
info.valueSetter = true;
} else if (canBeGetter && behavior instanceof MemberGetter) {
info.memberGetter = true;
info.noReturnGetter = noReturnGetter;
} else if (canBeSetter && behavior instanceof MemberSetter) {
info.memberSetter = true;
} else if (canBeAllocator && behavior instanceof Allocator) {
info.allocator = true;
} else if (canBeArrayAllocator && behavior instanceof ArrayAllocator) {
info.allocator = info.arrayAllocator = true;
} else if (behavior == null) {
// try to guess the behavior of the method
if (info.returnType == void.class && "deallocate".equals(info.name) &&
!Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 2 &&
info.parameterTypes[0] == long.class && info.parameterTypes[1] == long.class) {
info.deallocator = true;
} else if (canBeAllocator && "allocate".equals(info.name)) {
info.allocator = true;
} else if (canBeArrayAllocator && "allocateArray".equals(info.name)) {
info.allocator = info.arrayAllocator = true;
} else if (info.returnType.isAssignableFrom(ByteBuffer.class) && "asDirectBuffer".equals(info.name) &&
!Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 0) {
info.bufferGetter = true;
} else if (valueGetter) {
info.valueGetter = true;
info.noReturnGetter = noReturnGetter;
info.pairedMethod = pairedMethod;
} else if (valueSetter) {
info.valueSetter = true;
info.pairedMethod = pairedMethod;
} else if (memberGetter) {
info.memberGetter = true;
info.noReturnGetter = noReturnGetter;
info.pairedMethod = pairedMethod;
} else if (memberSetter) {
info.memberSetter = true;
info.pairedMethod = pairedMethod;
}
} else if (!(behavior instanceof Function)) {
logger.warn("Method \"" + method + "\" cannot behave like a \"" +
behavior.annotationType().getSimpleName() + "\". No code will be generated.");
return null;
}
if (name == null && info.pairedMethod != null) {
name = info.pairedMethod.getAnnotation(Name.class);
if (name != null) {
info.memberName = name.value();
}
}
info.noOffset = info.cls.isAnnotationPresent(NoOffset.class) ||
method.isAnnotationPresent(NoOffset.class) ||
method.isAnnotationPresent(Index.class);
if (!info.noOffset && info.pairedMethod != null) {
info.noOffset = info.pairedMethod.isAnnotationPresent(NoOffset.class) ||
info.pairedMethod.isAnnotationPresent(Index.class);
}
if (info.parameterTypes.length == 0 || !info.parameterTypes[0].isArray()) {
if (info.valueGetter || info.memberGetter) {
info.dim = info.parameterTypes.length;
} else if (info.memberSetter || info.valueSetter) {
info.dim = info.parameterTypes.length-1;
}
}
info.throwsException = null;
if (!noException(info.cls, method)) {
if ((by(info.annotations) instanceof ByVal && !noException(info.returnType, method)) ||
!info.deallocator && !info.valueGetter && !info.valueSetter &&
!info.memberGetter && !info.memberSetter && !info.bufferGetter) {
Class<?>[] exceptions = method.getExceptionTypes();
info.throwsException = exceptions.length > 0 ? exceptions[0] : RuntimeException.class;
}
}
return info;
}
static boolean noException(Class<?> cls, Method method) {
boolean noException = baseClasses.contains(cls) ||
method.isAnnotationPresent(NoException.class);
while (!noException && cls != null) {
if (noException = cls.isAnnotationPresent(NoException.class)) {
break;
}
cls = cls.getDeclaringClass();
}
return noException;
}
static class AdapterInformation {
String name;
int argc;
String cast;
boolean constant;
}
AdapterInformation adapterInformation(boolean out, MethodInformation methodInfo, int j) {
if (out && (methodInfo.parameterTypes[j] == String.class || methodInfo.valueSetter || methodInfo.memberSetter)) {
return null;
}
String typeName = cast(methodInfo, j);
if (typeName != null && typeName.startsWith("(") && typeName.endsWith(")")) {
typeName = typeName.substring(1, typeName.length()-1);
}
if (typeName == null || typeName.length() == 0) {
typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j])[0];
}
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapter = adapterInformation(out, valueTypeName, methodInfo.parameterAnnotations[j]);
if (adapter == null && methodInfo.pairedMethod != null && j == methodInfo.parameterTypes.length - 1 &&
(methodInfo.valueSetter || methodInfo.memberSetter)) {
adapter = adapterInformation(out, valueTypeName, methodInfo.pairedMethod.getAnnotations());
}
return adapter;
}
AdapterInformation adapterInformation(boolean out, String valueTypeName, Annotation ... annotations) {
AdapterInformation adapterInfo = null;
boolean constant = false;
String cast = "";
for (Annotation a : annotations) {
Adapter adapter = a instanceof Adapter ? (Adapter)a : a.annotationType().getAnnotation(Adapter.class);
if (adapter != null) {
adapterInfo = new AdapterInformation();
adapterInfo.name = adapter.value();
adapterInfo.argc = adapter.argc();
if (a != adapter) {
try {
Class cls = a.annotationType();
if (cls.isAnnotationPresent(Const.class)) {
constant = true;
}
try {
String value = cls.getDeclaredMethod("value").invoke(a).toString();
if (value != null && value.length() > 0) {
valueTypeName = value;
}
// else use inferred type
} catch (NoSuchMethodException e) {
// this adapter does not support a template type
valueTypeName = null;
}
Cast c = (Cast)cls.getAnnotation(Cast.class);
if (c != null && cast.length() == 0) {
cast = c.value()[0];
if (valueTypeName != null) {
cast += "< " + valueTypeName + " >";
}
if (c.value().length > 1) {
cast += c.value()[1];
}
}
} catch (Exception ex) {
logger.warn("Could not invoke the value() method on annotation \"" + a + "\": " + ex);
}
if (valueTypeName != null && valueTypeName.length() > 0) {
adapterInfo.name += "< " + valueTypeName + " >";
}
}
} else if (a instanceof Const) {
constant = true;
} else if (a instanceof Cast) {
Cast c = ((Cast)a);
if (c.value().length > 1) {
cast = c.value()[1];
}
}
}
if (adapterInfo != null) {
adapterInfo.cast = cast;
adapterInfo.constant = constant;
}
return out && constant ? null : adapterInfo;
}
String cast(MethodInformation methodInfo, int j) {
String cast = cast(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]);
if ((cast == null || cast.length() == 0) && j == methodInfo.parameterTypes.length-1 &&
(methodInfo.valueSetter || methodInfo.memberSetter) && methodInfo.pairedMethod != null) {
cast = cast(methodInfo.pairedMethod.getReturnType(), methodInfo.pairedMethod.getAnnotations());
}
return cast;
}
String cast(Class<?> type, Annotation ... annotations) {
String[] typeName = null;
for (Annotation a : annotations) {
if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) {
typeName = cppCastTypeName(type, annotations);
break;
}
}
return typeName != null && typeName.length > 0 ? "(" + typeName[0] + typeName[1] + ")" : "";
}
Annotation by(MethodInformation methodInfo, int j) {
Annotation passBy = by(methodInfo.parameterAnnotations[j]);
if (passBy == null && methodInfo.pairedMethod != null &&
(methodInfo.valueSetter || methodInfo.memberSetter)) {
passBy = by(methodInfo.pairedMethod.getAnnotations());
}
return passBy;
}
Annotation by(Annotation ... annotations) {
Annotation byAnnotation = null;
for (Annotation a : annotations) {
if (a instanceof ByPtr || a instanceof ByPtrPtr || a instanceof ByPtrRef ||
a instanceof ByRef || a instanceof ByVal) {
if (byAnnotation != null) {
logger.warn("\"By\" annotation \"" + byAnnotation +
"\" already found. Ignoring superfluous annotation \"" + a + "\".");
} else {
byAnnotation = a;
}
}
}
return byAnnotation;
}
Annotation behavior(Annotation ... annotations) {
Annotation behaviorAnnotation = null;
for (Annotation a : annotations) {
if (a instanceof Function || a instanceof Allocator || a instanceof ArrayAllocator ||
a instanceof ValueSetter || a instanceof ValueGetter ||
a instanceof MemberGetter || a instanceof MemberSetter) {
if (behaviorAnnotation != null) {
logger.warn("Behavior annotation \"" + behaviorAnnotation +
"\" already found. Ignoring superfluous annotation \"" + a + "\".");
} else {
behaviorAnnotation = a;
}
}
}
return behaviorAnnotation;
}
static String constValueTypeName(String ... typeName) {
String type = typeName[0];
if (type.endsWith("*") || type.endsWith("&")) {
type = type.substring(0, type.length()-1);
}
return type;
}
static String valueTypeName(String ... typeName) {
String type = typeName[0];
if (type.startsWith("const ")) {
type = type.substring(6, type.length()-1);
} else if (type.endsWith("*") || type.endsWith("&")) {
type = type.substring(0, type.length()-1);
}
return type;
}
String[] cppAnnotationTypeName(Class<?> type, Annotation ... annotations) {
String[] typeName = cppCastTypeName(type, annotations);
String prefix = typeName[0];
String suffix = typeName[1];
boolean casted = false;
for (Annotation a : annotations) {
if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) {
casted = true;
break;
}
}
Annotation by = by(annotations);
if (by instanceof ByVal) {
prefix = constValueTypeName(typeName);
} else if (by instanceof ByRef) {
prefix = constValueTypeName(typeName) + "&";
} else if (by instanceof ByPtrPtr && !casted) {
prefix = prefix + "*";
} else if (by instanceof ByPtrRef) {
prefix = prefix + "&";
} // else ByPtr
typeName[0] = prefix;
typeName[1] = suffix;
return typeName;
}
String[] cppCastTypeName(Class<?> type, Annotation ... annotations) {
String[] typeName = null;
boolean warning = false, adapter = false;
for (Annotation a : annotations) {
if (a instanceof Cast) {
warning = typeName != null;
String prefix = ((Cast)a).value()[0], suffix = "";
int parenthesis = prefix.indexOf(')');
if (parenthesis > 0) {
suffix = prefix.substring(parenthesis).trim();
prefix = prefix.substring(0, parenthesis).trim();
}
typeName = prefix.length() > 0 ? new String[] { prefix, suffix } : null;
} else if (a instanceof Const) {
if (warning = typeName != null) {
// prioritize @Cast
continue;
}
typeName = cppTypeName(type);
boolean[] b = ((Const)a).value();
if (b.length > 1 && b[1]) {
typeName[0] = valueTypeName(typeName) + " const *";
}
if (b.length > 0 && b[0]) {
typeName[0] = "const " + typeName[0];
}
Annotation by = by(annotations);
if (by instanceof ByPtrPtr) {
typeName[0] += "*";
} else if (by instanceof ByPtrRef) {
typeName[0] += "&";
}
} else if (a instanceof Adapter || a.annotationType().isAnnotationPresent(Adapter.class)) {
adapter = true;
}
}
if (warning && !adapter) {
logger.warn("Without \"Adapter\", \"Cast\" and \"Const\" annotations are mutually exclusive.");
}
if (typeName == null) {
typeName = cppTypeName(type);
}
return typeName;
}
String[] cppTypeName(Class<?> type) {
String prefix = "", suffix = "";
if (type == Buffer.class || type == Pointer.class) {
prefix = "void*";
} else if (type == byte[].class || type == ByteBuffer.class || type == BytePointer.class) {
prefix = "signed char*";
} else if (type == short[].class || type == ShortBuffer.class || type == ShortPointer.class) {
prefix = "short*";
} else if (type == int[].class || type == IntBuffer.class || type == IntPointer.class) {
prefix = "int*";
} else if (type == long[].class || type == LongBuffer.class || type == LongPointer.class) {
prefix = "jlong*";
} else if (type == float[].class || type == FloatBuffer.class || type == FloatPointer.class) {
prefix = "float*";
} else if (type == double[].class || type == DoubleBuffer.class || type == DoublePointer.class) {
prefix = "double*";
} else if (type == char[].class || type == CharBuffer.class || type == CharPointer.class) {
prefix = "unsigned short*";
} else if (type == boolean[].class) {
prefix = "unsigned char*";
} else if (type == PointerPointer.class) {
prefix = "void**";
} else if (type == String.class) {
prefix = "const char*";
} else if (type == byte.class) {
prefix = "signed char";
} else if (type == long.class) {
prefix = "jlong";
} else if (type == char.class) {
prefix = "unsigned short";
} else if (type == boolean.class) {
prefix = "unsigned char";
} else if (type.isPrimitive()) {
prefix = type.getName();
} else if (FunctionPointer.class.isAssignableFrom(type)) {
Method functionMethod = functionMethod(type, null);
if (functionMethod != null) {
Convention convention = type.getAnnotation(Convention.class);
String callingConvention = convention == null ? "" : convention.value() + " ";
Namespace namespace = type.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
Class returnType = functionMethod.getReturnType();
Class[] parameterTypes = functionMethod.getParameterTypes();
Annotation[] annotations = functionMethod.getAnnotations();
Annotation[][] parameterAnnotations = functionMethod.getParameterAnnotations();
String[] returnTypeName = cppAnnotationTypeName(returnType, annotations);
AdapterInformation returnAdapterInfo = adapterInformation(false, valueTypeName(returnTypeName), annotations);
if (returnAdapterInfo != null && returnAdapterInfo.cast.length() > 0) {
prefix = returnAdapterInfo.cast;
} else {
prefix = returnTypeName[0] + returnTypeName[1];
}
prefix += " (" + callingConvention + spaceName + "*";
suffix = ")(";
if (namespace != null && !Pointer.class.isAssignableFrom(parameterTypes[0])) {
logger.warn("First parameter of caller method call() or apply() for member function pointer " +
type.getCanonicalName() + " is not a Pointer. Compilation will most likely fail.");
}
for (int j = namespace == null ? 0 : 1; j < parameterTypes.length; j++) {
String[] paramTypeName = cppAnnotationTypeName(parameterTypes[j], parameterAnnotations[j]);
AdapterInformation paramAdapterInfo = adapterInformation(false, valueTypeName(paramTypeName), parameterAnnotations[j]);
if (paramAdapterInfo != null && paramAdapterInfo.cast.length() > 0) {
suffix += paramAdapterInfo.cast + " arg" + j;
} else {
suffix += paramTypeName[0] + " arg" + j + paramTypeName[1];
}
if (j < parameterTypes.length - 1) {
suffix += ", ";
}
}
suffix += ")";
if (type.isAnnotationPresent(Const.class)) {
suffix += " const";
}
}
} else {
String scopedType = cppScopeName(type);
if (scopedType.length() > 0) {
prefix = scopedType + "*";
} else {
logger.warn("The class " + type.getCanonicalName() +
" does not map to any C++ type. Compilation will most likely fail.");
}
}
return new String[] { prefix, suffix };
}
static String cppScopeName(MethodInformation methodInfo) {
String scopeName = cppScopeName(methodInfo.cls);
Namespace namespace = methodInfo.method.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) {
scopeName = ""; // user wants to reset namespace here
}
if (scopeName.length() > 0 && !scopeName.endsWith("::")) {
scopeName += "::";
}
scopeName += spaceName;
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
scopeName += "::";
}
return scopeName + methodInfo.memberName[0];
}
static String cppScopeName(Class<?> type) {
String scopeName = "";
while (type != null) {
Namespace namespace = type.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if (Pointer.class.isAssignableFrom(type) && type != Pointer.class) {
Name name = type.getAnnotation(Name.class);
String s;
if (name == null) {
s = type.getName();
int i = s.lastIndexOf("$");
if (i < 0) {
i = s.lastIndexOf(".");
}
s = s.substring(i+1);
} else {
s = name.value()[0];
}
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
spaceName += s;
}
if (scopeName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
scopeName = spaceName + scopeName;
if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) {
// user wants to reset namespace here
break;
}
type = type.getDeclaringClass();
}
return scopeName;
}
static String jniTypeName(Class type) {
if (type == byte.class) {
return "jbyte";
} else if (type == short.class) {
return "jshort";
} else if (type == int.class) {
return "jint";
} else if (type == long.class) {
return "jlong";
} else if (type == float.class) {
return "jfloat";
} else if (type == double.class) {
return "jdouble";
} else if (type == char.class) {
return "jchar";
} else if (type == boolean.class) {
return "jboolean";
} else if (type == byte[].class) {
return "jbyteArray";
} else if (type == short[].class) {
return "jshortArray";
} else if (type == int[].class) {
return "jintArray";
} else if (type == long[].class) {
return "jlongArray";
} else if (type == float[].class) {
return "jfloatArray";
} else if (type == double[].class) {
return "jdoubleArray";
} else if (type == char[].class) {
return "jcharArray";
} else if (type == boolean[].class) {
return "jbooleanArray";
} else if (type.isArray()) {
return "jobjectArray";
} else if (type == String.class) {
return "jstring";
} else if (type == Class.class) {
return "jclass";
} else if (type == void.class) {
return "void";
} else {
return "jobject";
}
}
static String signature(Class ... types) {
StringBuilder signature = new StringBuilder(2*types.length);
for (Class type : types) {
if (type == byte.class) {
signature.append("B");
} else if (type == short.class) {
signature.append("S");
} else if (type == int.class) {
signature.append("I");
} else if (type == long.class) {
signature.append("J");
} else if (type == float.class) {
signature.append("F");
} else if (type == double.class) {
signature.append("D");
} else if (type == boolean.class) {
signature.append("Z");
} else if (type == char.class) {
signature.append("C");
} else if (type == void.class) {
signature.append("V");
} else if (type.isArray()) {
signature.append(type.getName().replace('.', '/'));
} else {
signature.append("L").append(type.getName().replace('.', '/')).append(";");
}
}
return signature.toString();
}
static String mangle(String name) {
StringBuilder mangledName = new StringBuilder(2*name.length());
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
mangledName.append(c);
} else if (c == '_') {
mangledName.append("_1");
} else if (c == ';') {
mangledName.append("_2");
} else if (c == '[') {
mangledName.append("_3");
} else if (c == '.' || c == '/') {
mangledName.append("_");
} else {
String code = Integer.toHexString(c);
mangledName.append("_0");
switch (code.length()) {
case 1: mangledName.append("0");
case 2: mangledName.append("0");
case 3: mangledName.append("0");
default: mangledName.append(code);
}
}
}
return mangledName.toString();
}
}
| tarzanking/javacpp | src/main/java/com/googlecode/javacpp/Generator.java | Java | gpl-2.0 | 138,100 |
// I18N constants
// LANG: "pl", ENCODING: UTF-8
// translated: Krzysztof Kotowicz koto@webworkers.pl
{
"Align": "Wyrównanie",
"All four sides": "Wszystkie 4 strony",
"Background": "Tło",
"Baseline": "Linia bazowa",
"Border": "Ramka",
"Borders": "Ramki",
"Bottom": "Dół",
"Style [CSS]": "Styl [CSS]",
"CSS Style": "Styl CSS",
"Caption": "Podpis",
"Cell Properties": "Właściwości komórki",
"Center": "Środek",
"Char": "Znak",
"Collapsed borders": "Ramki skolapsowane",
"Color": "Kolor",
"Description": "Opis",
"FG Color": "Kolor czcionek",
"Float": "Opływanie",
"Frames": "Ramki zewn.",
"Frame and borders": "Obramowania",
"Height": "Wysokość",
"How many columns would you like to merge?": "Ile kolumn chcesz scalić?",
"How many rows would you like to merge?": "Ile wierszy chcesz scalić?",
"Image URL": "URL obrazka",
"Justify": "Wyjustuj",
"Layout": "Layout",
"Left": "Lewo",
"Margin": "Margines",
"Middle": "Środek",
"No rules": "Bez wewnętrzych",
"No sides": "Bez ramek",
"None": "Brak",
"Padding": "Wcięcia",
"Please click into some cell": "Kliknij w jakąś komórkę",
"Right": "Prawo",
"Row Properties": "Właściwości wiersza",
"Rules will appear between all rows and columns": "Linie będą widoczne pomiędzy kolumnami i wierszami",
"Rules will appear between columns only": "Linie będą widoczne tylko pomiędzy kolumnami",
"Rules will appear between rows only": "Linie będą widoczne tylko pomiędzy wierszami",
"Rules": "Linie wewn.",
"Spacing and padding": "Spacjowanie",
"Spacing": "Odstęp",
"Summary": "Podsumowanie",
"Delete cell": "Usuń komórkę",
"Insert cell after": "Wstaw komórkę po",
"Insert cell before": "Wstaw komórkę przed",
"Merge cells": "Scal komórki",
"Cell properties": "Właściwości komórki",
"Split cell": "Rozdziel komórkę",
"Delete column": "Usuń kolumnę",
"Insert column after": "Wstaw kolumnę po",
"Insert column before": "Wstaw kolumnę przed",
"Split column": "Rozdziel kolumnę",
"Delete row": "Usuń wiersz",
"Insert row before": "Wstaw wiersz przed",
"Insert row after": "Wstaw wiersz po",
"Row properties": "Właściwości wiersza",
"Split row": "Rozdziel wiersz",
"Table properties": "Właściwości tabeli",
"Table Properties": "Właściwości tabeli",
"Text align": "Wyr. w poziomie",
"The bottom side only": "Tylko dolna linia",
"The left-hand side only": "Tylko lewa linia",
"The right and left sides only": "Lewa i prawa linia",
"The right-hand side only": "Tylko prawa linia",
"The top and bottom sides only": "Górna i dolna linia",
"The top side only": "Tylko górna linia",
"Top": "Góra",
"Unset color": "Usuń kolor",
"Vertical align": "Wyr. w pionie",
"Width": "Szerokość",
"HTMLArea cowardly refuses to delete the last cell in row.": "Nie możesz skasować ostatniej komórki w wierszu.",
"HTMLArea cowardly refuses to delete the last column in table.": "Nie możesz skasować ostatniej kolumny w tabeli.",
"HTMLArea cowardly refuses to delete the last row in table.": "Nie możesz skasować ostatniego wiersza w tabeli.",
"percent": "%",
"pixels": "pikseli",
"OK": "OK",
"Cancel": "Anuluj"
};
| claunia/qemudb | xinha/plugins/TableOperations/lang/pl.js | JavaScript | gpl-2.0 | 3,246 |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#ifdef HAVE_SELINUX
#include <selinux/selinux.h>
#endif
#include "selinux-setup.h"
#include "selinux-util.h"
#include "label.h"
#include "mount-setup.h"
#include "macro.h"
#include "util.h"
#include "log.h"
#ifdef HAVE_SELINUX
static int null_log(int type, const char *fmt, ...) {
return 0;
}
#endif
int selinux_setup(bool *loaded_policy) {
#ifdef HAVE_SELINUX
int enforce = 0;
usec_t before_load, after_load;
security_context_t con;
int r;
union selinux_callback cb;
bool initialized = false;
assert(loaded_policy);
/* Turn off all of SELinux' own logging, we want to do that */
cb.func_log = null_log;
selinux_set_callback(SELINUX_CB_LOG, cb);
/* Don't load policy in the initrd if we don't appear to have
* it. For the real root, we check below if we've already
* loaded policy, and return gracefully.
*/
if (in_initrd() && access(selinux_path(), F_OK) < 0)
return 0;
/* Already initialized by somebody else? */
r = getcon_raw(&con);
if (r == 0) {
initialized = !streq(con, "kernel");
freecon(con);
}
/* Make sure we have no fds open while loading the policy and
* transitioning */
log_close();
/* Now load the policy */
before_load = now(CLOCK_MONOTONIC);
r = selinux_init_load_policy(&enforce);
if (r == 0) {
char timespan[FORMAT_TIMESPAN_MAX];
char *label;
retest_selinux();
/* Transition to the new context */
r = label_get_create_label_from_exe(SYSTEMD_BINARY_PATH, &label);
if (r < 0 || label == NULL) {
log_open();
log_error("Failed to compute init label, ignoring.");
} else {
r = setcon(label);
log_open();
if (r < 0)
log_error("Failed to transition into init label '%s', ignoring.", label);
label_free(label);
}
after_load = now(CLOCK_MONOTONIC);
log_info("Successfully loaded SELinux policy in %s.",
format_timespan(timespan, sizeof(timespan), after_load - before_load, 0));
*loaded_policy = true;
} else {
log_open();
if (enforce > 0) {
if (!initialized) {
log_error("Failed to load SELinux policy. Freezing.");
return -EIO;
}
log_warning("Failed to load new SELinux policy. Continuing with old policy.");
} else
log_debug("Unable to load SELinux policy. Ignoring.");
}
#endif
return 0;
}
| flonatel/systemd-pne1 | src/core/selinux-setup.c | C | gpl-2.0 | 3,884 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.